title
stringlengths
3
221
text
stringlengths
17
477k
parsed
listlengths
0
3.17k
Multinomial Models for Nominal Data | by Yufeng | Towards Data Science
The popular multinomial logistic regression is known as an extension of the binomial logistic regression model, in order to deal with more than two possible discrete outcomes. However, the multinomial logistic regression is not designed to be a general multi-class classifier but designed specifically for the nominal multinomial data. To note, nominal data and ordinal data are two major categories of multinomial data. The difference is that there is no order to the categories in nominal multinomial data while there is an order to those in ordinal multinomial data. For example, if our goal is to distinguish the three classes of plants in the IRIS dataset, we need to treat the plant categories as a nominal outcome because there is no specific order in the classes of plants. However, if we want to predict the score at the end of the first half in an NBA final into three categories, “winning”, “losing”, or “tie”, we need to regard it as an ordinal outcome because the pairwise distances are not the same among the three classes. Therefore, it’s necessary to figure out what the type of outcome is before the multinomial modeling. In this post, I am going to briefly talk about the multinomial regression models for the nominal data. I hope it will help you in your real-life work. As aforementioned, the multinomial logistic regression was specifically designed for the nominal data. The idea is very similar to that of logistic regression on the binary data, which is to link the probability of belonging to one of the categories to the predictors. For those who struggle to understand the link functions, you can refer to one of my previous posts about it. Let Yi be a random variable that can fall in one of the classes, 1, 2, ..., J. And we define pij as the ith variable to be in the jth class. so, we have the formula above is for the general case, so when J=2, it becomes the case with binary data. If we have the total number of observations as ni, then the multinomial distribution could be described as below. In the multinomial logistic regression, the link function is defined as where In this way, we link the log odds ratio between the probability to be in class J and that to be in class 1 to the linear combination of the predictors. Now let’s take a look at the real data and coding of the multinomial logistic regression. The example is from Faraway’s book, which describes the 1996 American National Election Study. The response variable involves three categories, Democrat, Republican, and Independent. The predictors include age, education level, and income group of the respondents. # R code> head(nes96)## popul TVnews selfLR ClinLR DoleLR PID age educ income vote## 1 0 7 extCon extLib Con strRep 36 HS $3Kminus Dole## 2 190 1 sliLib sliLib sliCon weakDem 20 Coll $3Kminus Clinton## 3 31 7 Lib Lib Con weakDem 24 BAdeg $3Kminus Clinton## 4 83 4 sliLib Mod sliCon weakDem 28 BAdeg $3Kminus Clinton## 5 640 7 sliCon Con Mod strDem 68 BAdeg $3Kminus Clinton## 6 110 3 sliLib Mod Con weakDem 21 Coll $3Kminus Clinton After some pre-processing of the dataset, we build the multinomial logistic regression in R as below. # R codelibrary(nnet)mulmod = multinom(sPID ~ age + educ + nincome, nes96) where “sPID” is the response variable, “age”, “educ”, and “nincome” corresponds to the age, the education level, and the income of the respondents, respectively. And nes96 is just the dataset name. We then check the summary of the fitted model. # R codesummary(mulmod) which yields, ## Call:## multinom(formula = sPID ~ age + educ + nincome, data = nes96)## ## Coefficients:## (Intercept) age educ.L educ.Q educ.C## Independent -1.197260 0.0001534525 0.06351451 -0.1217038 0.1119542## Republican -1.642656 0.0081943691 1.19413345 -1.2292869 0.1544575## educ^4 educ^5 educ^6 nincome## Independent -0.07657336 0.1360851 0.15427826 0.01623911## Republican -0.02827297 -0.1221176 -0.03741389 0.01724679## ## Std. Errors:## (Intercept) age educ.L educ.Q educ.C educ^4## Independent 0.3265951 0.005374592 0.4571884 0.4142859 0.3498491 0.2883031## Republican 0.3312877 0.004902668 0.6502670 0.6041924 0.4866432 0.3605620## educ^5 educ^6 nincome## Independent 0.2494706 0.2171578 0.003108585## Republican 0.2696036 0.2031859 0.002881745## ## Residual Deviance: 1968.333 ## AIC: 2004.333 The estimated coefficients, as well as the standard errors, are reported by the model summary. The output is a little different from those in the linear models. Only the statistics of “Independent” and “Republican” are listed in the summary because here “Democrat” is used as the baseline category and the regression is modeling the log odds ratio against this baseline category. You may notice that there is no indicator to show the significance of the predictors in the model. We can evaluate them in two ways. First, we can use the popular Z-score to evaluate the significance of the preditors. # R codez = summary(mulmod)$coefficients/summary(mulmod)$standard.errorsp = (1 - pnorm(abs(z), 0, 1))*2 This procedure is easy to implement because it has a simplified assumption of the normal distribution which holds for a rough estimation. Let’s look at the p-values. ## (Intercept) age educ.L educ.Q educ.C educ^4## Independent 2.464850e-04 0.97722232 0.88951010 0.76893540 0.7489628 0.7905471## Republican 7.107723e-07 0.09464069 0.06630235 0.04189165 0.7509449 0.9374990## educ^5 educ^6 nincome## Independent 0.5854128 0.4774294 1.751402e-07## Republican 0.6505832 0.8539066 2.165977e-09 It seems that income is a strong preditor with no doubt, but not all the education variables are listed as significant. This is also a shortcoming of using Z-distribution to evaluate the coefficients, which makes it hard to interpret. A more precise way is to build a new model with a reduced number of predictors and then check the change in the likelihood. First, let’s build the model without variable education. # R codemulmod_noedu = multinom(sPID ~ age + nincome, nes96) Then we use a chi-squared distribution to evaluate the change in likelihood between the two multinomial models. The p-value could be calculated as below. # R codepchisq(deviance(mulmod_noedu)-deviance(mulmod),mulmod$edf - mulmod_noedu$edf, lower.tail = F) which yields, 0.1819634 which indicates that the variable ‘education’ is not significant relative to the full model. If we do the same thing to the variable ‘income’, we will get the following result. # R codemulmod_noinc = multinom(sPID ~ age + educ, nes96)pchisq(deviance(mulmod_noinc)-deviance(mulmod),mulmod$edf - mulmod_noinc$edf, lower.tail = F) which yields, 1.267249e-10 These results indicate that “income” is a significant predictor in the full model. The interpretation of the coefficient should be such: one unit change in some predictor will result in k unit change in the log odds ratio between the target category to the baseline category (“Democrat” in this example). I will not explore the details of this part. Another very important check on the response variable before the multinomial modeling is whether the response outcome is hierarchical. Let’s look at an example of the central nervous system disease data from Faraway’s book. data(cns)head(cns) yields, ## Area NoCNS An Sp Other Water Work## 1 Cardiff 4091 5 9 5 110 NonManual## 2 Newport 1515 1 7 0 100 NonManual## 3 Swansea 2394 9 5 0 95 NonManual## 4 GlamorganE 3163 9 14 3 42 NonManual## 5 GlamorganW 1979 5 10 1 39 NonManual## 6 GlamorganC 4838 11 12 2 161 NonManual Here, “NoCNS” means no central nervous system disease, “An” means anencephalus, “Sp” means spina bifida, and “Other” means other types of CNS. “Area”, “Water” and “Work” describe the features of the families. If we want to model the CNS status using the features of the families, we can simply implement the multinomial logistic regression on the four categories. However, we can see that “An”, “Sp” and “Other” are just subtypes of CNS and the response variable is dominated by healthy individuals (NoCNS). In such a situation, we’d better treat the response variables as hierarchical variables, where “CNS” and “NoCNS” form a binomial distribution and “An”, “Sp”, and “Other” form a multinomial distribution within the “CNS” category. Let’s compare the codes and results. Let’s first establish a binomial logistic regression between the “CNS” and “NoCNS”. # R codecns$CNS = cns$An + cns$Sp + cns$Otherbinom_mod = glm(cbind(CNS,NoCNS) ~ Water + Work, cns, family=binomial)summary(binom_mod) which yields, ## ## Call:## glm(formula = cbind(CNS, NoCNS) ~ Water + Work, family = binomial, ## data = cns)## ## Deviance Residuals: ## Min 1Q Median 3Q Max ## -2.65570 -0.30179 -0.03131 0.57213 1.32998 ## ## Coefficients:## Estimate Std. Error z value Pr(>|z|) ## (Intercept) -4.4325803 0.0897889 -49.367 < 2e-16 ***## Water -0.0032644 0.0009684 -3.371 0.000749 ***## WorkNonManual -0.3390577 0.0970943 -3.492 0.000479 ***## ---## Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1## ## (Dispersion parameter for binomial family taken to be 1)## ## Null deviance: 41.047 on 15 degrees of freedom## Residual deviance: 12.363 on 13 degrees of freedom## AIC: 102.49## ## Number of Fisher Scoring iterations: 4 We can find that both “Water” and “WorkNonManual” are significant variables in predicting CNS or not. Then, we perform the multinomial logistic regression on the subtypes of CNS. # R codecns_mod = multinom(cbind(An,Sp,Other) ~ Water + Work, cns)z = summary(cns_mod)$coefficients/summary(cns_mod)$standard.errorsp= (1 - pnorm(abs(z), 0, 1))*2p which yields, ## (Intercept) Water WorkNonManual## Sp 4.833577e-02 0.5234640 0.5791105## Other 5.935107e-05 0.4511663 0.4052210 We can see that neither “Water” nor “WorkNonManual” is significant to distinguish different subtypes of CNS. These results suggest that water quality and manual work do have an influence on the new births’ CNS condition, but neither of them explains the subtypes of the CNS. However, if we throw everything to a four-category full model, the results are different. # R codefull_mod = multinom(cbind(NoCNS, An, Sp, Other) ~ Water + Work, cns)z = summary(full_mod)$coefficients/summary(full_mod)$standard.errorsp= (1 - pnorm(abs(z), 0, 1))*2p which shows, ## (Intercept) Water WorkNonManual## An 0 0.066695285 0.02338312## Sp 0 0.001835095 0.07077816## Other 0 0.840643368 0.02348335 This time the predictors show some mixed results in interpreting the subtype of CNSs with different p-values. The fact that subtypes of CNS cannot be predicted by the two variables is not disclosed in the full model. In summary, I introduced the multinomial regression model and its application situations. The most important point is to check the response variables before the modeling. The multinomial logistic regression can only be applied to the nominal data instead of the ordinal data.The response variables with potential hierarchical structures should be treated carefully. Pooling everything together to a full model is not optimal sometimes. The multinomial logistic regression can only be applied to the nominal data instead of the ordinal data. The response variables with potential hierarchical structures should be treated carefully. Pooling everything together to a full model is not optimal sometimes. www.analyticsvidhya.com Faraway, Julian J. Extending the linear model with R: generalized linear, mixed effects and nonparametric regression models. CRC press, 2016.
[ { "code": null, "e": 347, "s": 171, "text": "The popular multinomial logistic regression is known as an extension of the binomial logistic regression model, in order to deal with more than two possible discrete outcomes." }, { "code": null, "e": 507, "s": 347, "text": "However, the multinomial logistic regression is not designed to be a general multi-class classifier but designed specifically for the nominal multinomial data." }, { "code": null, "e": 741, "s": 507, "text": "To note, nominal data and ordinal data are two major categories of multinomial data. The difference is that there is no order to the categories in nominal multinomial data while there is an order to those in ordinal multinomial data." }, { "code": null, "e": 1209, "s": 741, "text": "For example, if our goal is to distinguish the three classes of plants in the IRIS dataset, we need to treat the plant categories as a nominal outcome because there is no specific order in the classes of plants. However, if we want to predict the score at the end of the first half in an NBA final into three categories, “winning”, “losing”, or “tie”, we need to regard it as an ordinal outcome because the pairwise distances are not the same among the three classes." }, { "code": null, "e": 1310, "s": 1209, "text": "Therefore, it’s necessary to figure out what the type of outcome is before the multinomial modeling." }, { "code": null, "e": 1461, "s": 1310, "text": "In this post, I am going to briefly talk about the multinomial regression models for the nominal data. I hope it will help you in your real-life work." }, { "code": null, "e": 1730, "s": 1461, "text": "As aforementioned, the multinomial logistic regression was specifically designed for the nominal data. The idea is very similar to that of logistic regression on the binary data, which is to link the probability of belonging to one of the categories to the predictors." }, { "code": null, "e": 1839, "s": 1730, "text": "For those who struggle to understand the link functions, you can refer to one of my previous posts about it." }, { "code": null, "e": 1980, "s": 1839, "text": "Let Yi be a random variable that can fall in one of the classes, 1, 2, ..., J. And we define pij as the ith variable to be in the jth class." }, { "code": null, "e": 1992, "s": 1980, "text": "so, we have" }, { "code": null, "e": 2086, "s": 1992, "text": "the formula above is for the general case, so when J=2, it becomes the case with binary data." }, { "code": null, "e": 2200, "s": 2086, "text": "If we have the total number of observations as ni, then the multinomial distribution could be described as below." }, { "code": null, "e": 2272, "s": 2200, "text": "In the multinomial logistic regression, the link function is defined as" }, { "code": null, "e": 2278, "s": 2272, "text": "where" }, { "code": null, "e": 2520, "s": 2278, "text": "In this way, we link the log odds ratio between the probability to be in class J and that to be in class 1 to the linear combination of the predictors. Now let’s take a look at the real data and coding of the multinomial logistic regression." }, { "code": null, "e": 2785, "s": 2520, "text": "The example is from Faraway’s book, which describes the 1996 American National Election Study. The response variable involves three categories, Democrat, Republican, and Independent. The predictors include age, education level, and income group of the respondents." }, { "code": null, "e": 3318, "s": 2785, "text": "# R code> head(nes96)## popul TVnews selfLR ClinLR DoleLR PID age educ income vote## 1 0 7 extCon extLib Con strRep 36 HS $3Kminus Dole## 2 190 1 sliLib sliLib sliCon weakDem 20 Coll $3Kminus Clinton## 3 31 7 Lib Lib Con weakDem 24 BAdeg $3Kminus Clinton## 4 83 4 sliLib Mod sliCon weakDem 28 BAdeg $3Kminus Clinton## 5 640 7 sliCon Con Mod strDem 68 BAdeg $3Kminus Clinton## 6 110 3 sliLib Mod Con weakDem 21 Coll $3Kminus Clinton" }, { "code": null, "e": 3420, "s": 3318, "text": "After some pre-processing of the dataset, we build the multinomial logistic regression in R as below." }, { "code": null, "e": 3495, "s": 3420, "text": "# R codelibrary(nnet)mulmod = multinom(sPID ~ age + educ + nincome, nes96)" }, { "code": null, "e": 3693, "s": 3495, "text": "where “sPID” is the response variable, “age”, “educ”, and “nincome” corresponds to the age, the education level, and the income of the respondents, respectively. And nes96 is just the dataset name." }, { "code": null, "e": 3740, "s": 3693, "text": "We then check the summary of the fitted model." }, { "code": null, "e": 3764, "s": 3740, "text": "# R codesummary(mulmod)" }, { "code": null, "e": 3778, "s": 3764, "text": "which yields," }, { "code": null, "e": 4703, "s": 3778, "text": "## Call:## multinom(formula = sPID ~ age + educ + nincome, data = nes96)## ## Coefficients:## (Intercept) age educ.L educ.Q educ.C## Independent -1.197260 0.0001534525 0.06351451 -0.1217038 0.1119542## Republican -1.642656 0.0081943691 1.19413345 -1.2292869 0.1544575## educ^4 educ^5 educ^6 nincome## Independent -0.07657336 0.1360851 0.15427826 0.01623911## Republican -0.02827297 -0.1221176 -0.03741389 0.01724679## ## Std. Errors:## (Intercept) age educ.L educ.Q educ.C educ^4## Independent 0.3265951 0.005374592 0.4571884 0.4142859 0.3498491 0.2883031## Republican 0.3312877 0.004902668 0.6502670 0.6041924 0.4866432 0.3605620## educ^5 educ^6 nincome## Independent 0.2494706 0.2171578 0.003108585## Republican 0.2696036 0.2031859 0.002881745## ## Residual Deviance: 1968.333 ## AIC: 2004.333" }, { "code": null, "e": 4864, "s": 4703, "text": "The estimated coefficients, as well as the standard errors, are reported by the model summary. The output is a little different from those in the linear models." }, { "code": null, "e": 5083, "s": 4864, "text": "Only the statistics of “Independent” and “Republican” are listed in the summary because here “Democrat” is used as the baseline category and the regression is modeling the log odds ratio against this baseline category." }, { "code": null, "e": 5216, "s": 5083, "text": "You may notice that there is no indicator to show the significance of the predictors in the model. We can evaluate them in two ways." }, { "code": null, "e": 5301, "s": 5216, "text": "First, we can use the popular Z-score to evaluate the significance of the preditors." }, { "code": null, "e": 5405, "s": 5301, "text": "# R codez = summary(mulmod)$coefficients/summary(mulmod)$standard.errorsp = (1 - pnorm(abs(z), 0, 1))*2" }, { "code": null, "e": 5571, "s": 5405, "text": "This procedure is easy to implement because it has a simplified assumption of the normal distribution which holds for a rough estimation. Let’s look at the p-values." }, { "code": null, "e": 5953, "s": 5571, "text": "## (Intercept) age educ.L educ.Q educ.C educ^4## Independent 2.464850e-04 0.97722232 0.88951010 0.76893540 0.7489628 0.7905471## Republican 7.107723e-07 0.09464069 0.06630235 0.04189165 0.7509449 0.9374990## educ^5 educ^6 nincome## Independent 0.5854128 0.4774294 1.751402e-07## Republican 0.6505832 0.8539066 2.165977e-09" }, { "code": null, "e": 6188, "s": 5953, "text": "It seems that income is a strong preditor with no doubt, but not all the education variables are listed as significant. This is also a shortcoming of using Z-distribution to evaluate the coefficients, which makes it hard to interpret." }, { "code": null, "e": 6369, "s": 6188, "text": "A more precise way is to build a new model with a reduced number of predictors and then check the change in the likelihood. First, let’s build the model without variable education." }, { "code": null, "e": 6430, "s": 6369, "text": "# R codemulmod_noedu = multinom(sPID ~ age + nincome, nes96)" }, { "code": null, "e": 6584, "s": 6430, "text": "Then we use a chi-squared distribution to evaluate the change in likelihood between the two multinomial models. The p-value could be calculated as below." }, { "code": null, "e": 6686, "s": 6584, "text": "# R codepchisq(deviance(mulmod_noedu)-deviance(mulmod),mulmod$edf - mulmod_noedu$edf, lower.tail = F)" }, { "code": null, "e": 6700, "s": 6686, "text": "which yields," }, { "code": null, "e": 6710, "s": 6700, "text": "0.1819634" }, { "code": null, "e": 6887, "s": 6710, "text": "which indicates that the variable ‘education’ is not significant relative to the full model. If we do the same thing to the variable ‘income’, we will get the following result." }, { "code": null, "e": 7038, "s": 6887, "text": "# R codemulmod_noinc = multinom(sPID ~ age + educ, nes96)pchisq(deviance(mulmod_noinc)-deviance(mulmod),mulmod$edf - mulmod_noinc$edf, lower.tail = F)" }, { "code": null, "e": 7052, "s": 7038, "text": "which yields," }, { "code": null, "e": 7065, "s": 7052, "text": "1.267249e-10" }, { "code": null, "e": 7148, "s": 7065, "text": "These results indicate that “income” is a significant predictor in the full model." }, { "code": null, "e": 7415, "s": 7148, "text": "The interpretation of the coefficient should be such: one unit change in some predictor will result in k unit change in the log odds ratio between the target category to the baseline category (“Democrat” in this example). I will not explore the details of this part." }, { "code": null, "e": 7550, "s": 7415, "text": "Another very important check on the response variable before the multinomial modeling is whether the response outcome is hierarchical." }, { "code": null, "e": 7639, "s": 7550, "text": "Let’s look at an example of the central nervous system disease data from Faraway’s book." }, { "code": null, "e": 7658, "s": 7639, "text": "data(cns)head(cns)" }, { "code": null, "e": 7666, "s": 7658, "text": "yields," }, { "code": null, "e": 8010, "s": 7666, "text": "## Area NoCNS An Sp Other Water Work## 1 Cardiff 4091 5 9 5 110 NonManual## 2 Newport 1515 1 7 0 100 NonManual## 3 Swansea 2394 9 5 0 95 NonManual## 4 GlamorganE 3163 9 14 3 42 NonManual## 5 GlamorganW 1979 5 10 1 39 NonManual## 6 GlamorganC 4838 11 12 2 161 NonManual" }, { "code": null, "e": 8219, "s": 8010, "text": "Here, “NoCNS” means no central nervous system disease, “An” means anencephalus, “Sp” means spina bifida, and “Other” means other types of CNS. “Area”, “Water” and “Work” describe the features of the families." }, { "code": null, "e": 8374, "s": 8219, "text": "If we want to model the CNS status using the features of the families, we can simply implement the multinomial logistic regression on the four categories." }, { "code": null, "e": 8747, "s": 8374, "text": "However, we can see that “An”, “Sp” and “Other” are just subtypes of CNS and the response variable is dominated by healthy individuals (NoCNS). In such a situation, we’d better treat the response variables as hierarchical variables, where “CNS” and “NoCNS” form a binomial distribution and “An”, “Sp”, and “Other” form a multinomial distribution within the “CNS” category." }, { "code": null, "e": 8784, "s": 8747, "text": "Let’s compare the codes and results." }, { "code": null, "e": 8868, "s": 8784, "text": "Let’s first establish a binomial logistic regression between the “CNS” and “NoCNS”." }, { "code": null, "e": 9002, "s": 8868, "text": "# R codecns$CNS = cns$An + cns$Sp + cns$Otherbinom_mod = glm(cbind(CNS,NoCNS) ~ Water + Work, cns, family=binomial)summary(binom_mod)" }, { "code": null, "e": 9016, "s": 9002, "text": "which yields," }, { "code": null, "e": 9807, "s": 9016, "text": "## ## Call:## glm(formula = cbind(CNS, NoCNS) ~ Water + Work, family = binomial, ## data = cns)## ## Deviance Residuals: ## Min 1Q Median 3Q Max ## -2.65570 -0.30179 -0.03131 0.57213 1.32998 ## ## Coefficients:## Estimate Std. Error z value Pr(>|z|) ## (Intercept) -4.4325803 0.0897889 -49.367 < 2e-16 ***## Water -0.0032644 0.0009684 -3.371 0.000749 ***## WorkNonManual -0.3390577 0.0970943 -3.492 0.000479 ***## ---## Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1## ## (Dispersion parameter for binomial family taken to be 1)## ## Null deviance: 41.047 on 15 degrees of freedom## Residual deviance: 12.363 on 13 degrees of freedom## AIC: 102.49## ## Number of Fisher Scoring iterations: 4" }, { "code": null, "e": 9909, "s": 9807, "text": "We can find that both “Water” and “WorkNonManual” are significant variables in predicting CNS or not." }, { "code": null, "e": 9986, "s": 9909, "text": "Then, we perform the multinomial logistic regression on the subtypes of CNS." }, { "code": null, "e": 10150, "s": 9986, "text": "# R codecns_mod = multinom(cbind(An,Sp,Other) ~ Water + Work, cns)z = summary(cns_mod)$coefficients/summary(cns_mod)$standard.errorsp= (1 - pnorm(abs(z), 0, 1))*2p" }, { "code": null, "e": 10164, "s": 10150, "text": "which yields," }, { "code": null, "e": 10300, "s": 10164, "text": "## (Intercept) Water WorkNonManual## Sp 4.833577e-02 0.5234640 0.5791105## Other 5.935107e-05 0.4511663 0.4052210" }, { "code": null, "e": 10409, "s": 10300, "text": "We can see that neither “Water” nor “WorkNonManual” is significant to distinguish different subtypes of CNS." }, { "code": null, "e": 10575, "s": 10409, "text": "These results suggest that water quality and manual work do have an influence on the new births’ CNS condition, but neither of them explains the subtypes of the CNS." }, { "code": null, "e": 10665, "s": 10575, "text": "However, if we throw everything to a four-category full model, the results are different." }, { "code": null, "e": 10841, "s": 10665, "text": "# R codefull_mod = multinom(cbind(NoCNS, An, Sp, Other) ~ Water + Work, cns)z = summary(full_mod)$coefficients/summary(full_mod)$standard.errorsp= (1 - pnorm(abs(z), 0, 1))*2p" }, { "code": null, "e": 10854, "s": 10841, "text": "which shows," }, { "code": null, "e": 11039, "s": 10854, "text": "## (Intercept) Water WorkNonManual## An 0 0.066695285 0.02338312## Sp 0 0.001835095 0.07077816## Other 0 0.840643368 0.02348335" }, { "code": null, "e": 11256, "s": 11039, "text": "This time the predictors show some mixed results in interpreting the subtype of CNSs with different p-values. The fact that subtypes of CNS cannot be predicted by the two variables is not disclosed in the full model." }, { "code": null, "e": 11427, "s": 11256, "text": "In summary, I introduced the multinomial regression model and its application situations. The most important point is to check the response variables before the modeling." }, { "code": null, "e": 11692, "s": 11427, "text": "The multinomial logistic regression can only be applied to the nominal data instead of the ordinal data.The response variables with potential hierarchical structures should be treated carefully. Pooling everything together to a full model is not optimal sometimes." }, { "code": null, "e": 11797, "s": 11692, "text": "The multinomial logistic regression can only be applied to the nominal data instead of the ordinal data." }, { "code": null, "e": 11958, "s": 11797, "text": "The response variables with potential hierarchical structures should be treated carefully. Pooling everything together to a full model is not optimal sometimes." }, { "code": null, "e": 11982, "s": 11958, "text": "www.analyticsvidhya.com" } ]
GATE | GATE CS 2010 | Question 43 - GeeksforGeeks
28 Jun, 2021 Which of the following functional dependencies hold for relations R(A, B, C) and S(B, D, E): B -> A A -> C The relation R contains 200 tuples and the rel ation S contains 100 tuples. What is the maximum number of tuples possible in the natural join of R and S (R natural join S)(A) 100(B) 200(C) 300(D) 2000Answer: (A)Explanation: From the given set of functional dependencies, it can be observed that B is a candidate key of R. So all 200 values of B must be unique in R. There is no functional dependency given for S. To get the maximum number of tuples in output, there can be two possibilities for S.1) All 100 values of B in S are same and there is an entry in R that matches with this value. In this case, we get 100 tuples in output.2) All 100 values of B in S are different and these values are present in R also. In this case also, we get 100 tuples. Quiz of this Question GATE-CS-2010 GATE-GATE CS 2010 GATE Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments GATE | GATE-CS-2016 (Set 2) | Question 48 GATE | GATE-CS-2014-(Set-1) | Question 30 GATE | GATE-CS-2001 | Question 23 GATE | GATE CS 2010 | Question 45 GATE | GATE-CS-2015 (Set 1) | Question 65 GATE | GATE-CS-2015 (Set 3) | Question 65 GATE | GATE-CS-2015 (Set 1) | Question 42 GATE | GATE-CS-2004 | Question 3 GATE | GATE-CS-2014-(Set-1) | Question 65 C++ Program to count Vowels in a string using Pointer
[ { "code": null, "e": 24123, "s": 24095, "text": "\n28 Jun, 2021" }, { "code": null, "e": 24216, "s": 24123, "text": "Which of the following functional dependencies hold for relations R(A, B, C) and S(B, D, E):" }, { "code": null, "e": 24230, "s": 24216, "text": "B -> A\nA -> C" }, { "code": null, "e": 24454, "s": 24230, "text": "The relation R contains 200 tuples and the rel ation S contains 100 tuples. What is the maximum number of tuples possible in the natural join of R and S (R natural join S)(A) 100(B) 200(C) 300(D) 2000Answer: (A)Explanation:" }, { "code": null, "e": 24983, "s": 24454, "text": "From the given set of functional dependencies, it can be observed that B is a candidate key of R. So all 200 values of B must be unique in R. There is no functional dependency given for S. To get the maximum number of tuples in output, there can be two possibilities for S.1) All 100 values of B in S are same and there is an entry in R that matches with this value. In this case, we get 100 tuples in output.2) All 100 values of B in S are different and these values are present in R also. In this case also, we get 100 tuples." }, { "code": null, "e": 25005, "s": 24983, "text": "Quiz of this Question" }, { "code": null, "e": 25018, "s": 25005, "text": "GATE-CS-2010" }, { "code": null, "e": 25036, "s": 25018, "text": "GATE-GATE CS 2010" }, { "code": null, "e": 25041, "s": 25036, "text": "GATE" }, { "code": null, "e": 25139, "s": 25041, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 25148, "s": 25139, "text": "Comments" }, { "code": null, "e": 25161, "s": 25148, "text": "Old Comments" }, { "code": null, "e": 25203, "s": 25161, "text": "GATE | GATE-CS-2016 (Set 2) | Question 48" }, { "code": null, "e": 25245, "s": 25203, "text": "GATE | GATE-CS-2014-(Set-1) | Question 30" }, { "code": null, "e": 25279, "s": 25245, "text": "GATE | GATE-CS-2001 | Question 23" }, { "code": null, "e": 25313, "s": 25279, "text": "GATE | GATE CS 2010 | Question 45" }, { "code": null, "e": 25355, "s": 25313, "text": "GATE | GATE-CS-2015 (Set 1) | Question 65" }, { "code": null, "e": 25397, "s": 25355, "text": "GATE | GATE-CS-2015 (Set 3) | Question 65" }, { "code": null, "e": 25439, "s": 25397, "text": "GATE | GATE-CS-2015 (Set 1) | Question 42" }, { "code": null, "e": 25472, "s": 25439, "text": "GATE | GATE-CS-2004 | Question 3" }, { "code": null, "e": 25514, "s": 25472, "text": "GATE | GATE-CS-2014-(Set-1) | Question 65" } ]
Linked List Matrix | Practice | GeeksforGeeks
Given a Matrix mat of N*N size, the task is to complete the function constructLinkedMatrix(), that constructs a 2D linked list representation of the given matrix. Input : 2D matrix 1 2 3 4 5 6 7 8 9 Output : 1 -> 2 -> 3 -> NULL | | | v v v 4 -> 5 -> 6 -> NULL | | | v v v 7 -> 8 -> 9 -> NULL | | | v v v NULL NULL NULL Input: The fuction takes 2 argument as input, first the 2D matrix mat[][] and second an integer variable N, denoting the size of the matrix. There will be T test cases and for each test case the function will be called separately. Output: The function must return the reference pointer to the head of the linked list. Constraints: 1<=T<=100 1<=N<=150 Example: Input: 2 3 1 2 3 4 5 6 7 8 9 2 1 2 3 4 Output: 1 2 3 4 5 6 7 8 9 1 2 3 4 Note:The Input/Ouput format and Example given are used for system's internal purpose, and should be used by a user for Expected Output only. As it is a function problem, hence a user should not read any input from stdin/console. The task is to complete the function specified, and not to write the full code. 0 satyamkumar96002 months ago static Node constructl(Node head,int data){ if(head == null){ Node temp = new Node(data); head = temp; return head; } Node temp = head; while(temp.right!=null){ temp =temp.right; } Node t = new Node(data); temp.right = t; return head; } static Node construct(int arr[][],int n) { //Add your code here. Node arrl[] = new Node[n]; for (int i = 0;i<n;i++){ for(int j =0;j<n;j++){ arrl[i] = constructl(arrl[i],arr[i][j]); } } for(int i = 0;i<n-1;i++){ Node head = arrl[i]; Node anhead = arrl[i+1]; while(head!= null){ head.down = anhead; head = head.right; anhead = anhead.right; } } return arrl[0]; } +2 haritasboy12052 months ago C++ | Solution Node* constructLinkedMatrix(int mat[MAX][MAX], int n) { // code here Node* head = new Node(mat[0][0]); Node* temp = head; for(int i=0;i<n;i++) { Node* temp2 = temp; for(int j=0;j<n;j++) { if(j+1 == n) temp->right = NULL; else temp->right = new Node(mat[i][j+1]); if(i+1 == n) temp->down = NULL; else temp->down = new Node(mat[i+1][j]); temp = temp->right; } temp = temp2; temp = temp->down; } return head; } +1 mohankrishnapeddineni3 months ago //JAVA CODE static Node construct(int arr[][],int n) { Node head=new Node(arr[0][0]); Node temp=head; for(int i=0;i<n;i++){ Node t = temp; for(int j=0;j<n;j++){ if(j+1==n){ temp.right =null; } else temp.right = new Node(arr[i][j+1]); if(i+1==n){ temp.down = null; } else temp.down = new Node(arr[i+1][j]); temp =temp.right; } temp = t; temp =temp.down; } return head; } 0 user_4tly3 months ago Node* constructLinkedMatrix(int mat[MAX][MAX], int n){ // code here Node* head = NULL; Node* lastRowHead = NULL; Node* lastRowPointer = NULL; for(int i=0 ; i<n ; i++) { Node* temp = NULL; for(int j=0 ; j<n ; j++) { Node* nw = new Node(mat[i][j]); if(temp != NULL){ temp->right = nw; } if(i != 0){ lastRowPointer->down = nw; lastRowPointer = lastRowPointer->right; } temp = nw; if(j==0){ lastRowHead = temp; } if(head == NULL) head = temp; } lastRowPointer = lastRowHead; } return head;} 0 yadavkapil23363 months ago C++ Node* constructLinkedMatrix(int mat[MAX][MAX], int n){ int i,j; Node* head=new Node(mat[0][0]); Node* temp1=head; Node* temp2=head; for(i=1;i<n;i++) { temp1->right=new Node(mat[0][i]); temp1=temp1->right; } for(j=1;j<n;j++) { temp1=head; temp2=head; while(temp1->down!=NULL) temp1=temp1->down; while(temp2->down!=NULL) temp2=temp2->down; temp2->down=new Node(mat[j][0]); temp2=temp2->down; for(i=1;i<n;i++) { temp1=temp1->right; temp2->right=new Node(mat[j][i]); temp1->down=temp2->right; temp2=temp2->right; } } return(head); } 0 abhisinha6563 months ago Node* newNode(int d){ Node* temp = (struct Node*)malloc(sizeof(struct Node)); temp->data = d; temp->right = temp->down = NULL; return temp;}Node* constructLinkedMatrix(int mat[MAX][MAX], int n){ // code here Node* mainhead = NULL; Node* head[n]; Node *righttemp, *newptr; for (int i = 0; i < n; i++) { head[i] = NULL; for (int j = 0; j < n; j++) { newptr = newNode(mat[i][j]); if (!mainhead) mainhead = newptr; if (!head[i]) head[i] = newptr; else righttemp->right = newptr; righttemp = newptr; } } for (int i = 0; i < n - 1; i++) { Node *temp1 = head[i], *temp2 = head[i + 1]; while (temp1 && temp2) { temp1->down = temp2; temp1 = temp1->right; temp2 = temp2->right; } } return mainhead;} 0 ankitsinha1112005 months ago Node* constructLinkedMatrix(int mat[MAX][MAX], int n) { Node* temp2=NULL,*temp3,*temp4; for(int i=n-1;i>=0;i--) { Node* temp1=NULL; for(int j=n-1;j>=0;j--) { Node* temp=new Node(mat[i][j]); temp->right=temp1; if(i==n-1) temp->down=temp2; if(j==0) temp3=temp; temp1=temp; } if(i!=n-1) { temp4=temp3; while(temp4!=NULL) { temp4->down=temp2; temp4=temp4->right; temp2=temp2->right; } } temp2=temp3; } return temp3; } 0 ankitsinha1112005 months ago +1 imranwahid6 months ago Easy C++ solution 0 sushilkumarskp6187 months ago What is wrong with this, error- null pointer error in bold-line below. static Node construct(int arr[][],int n) { Node headnode = new Node(arr[0][0]); Node temp1 = headnode; for(int i = 0; i<n; i++){ Node temp =temp1; for(int j=0; j<n;j++){ temp.data = arr[i][j]; temp = temp.right; } temp1 = temp1.down; } return headnode; } 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": 401, "s": 238, "text": "Given a Matrix mat of N*N size, the task is to complete the function constructLinkedMatrix(), that constructs a 2D linked list representation of the given matrix." }, { "code": null, "e": 595, "s": 401, "text": "Input : 2D matrix \n1 2 3\n4 5 6\n7 8 9\n\nOutput :\n1 -> 2 -> 3 -> NULL\n| | |\nv v v\n4 -> 5 -> 6 -> NULL\n| | |\nv v v\n7 -> 8 -> 9 -> NULL\n| | |\nv v v\nNULL NULL NULL" }, { "code": null, "e": 1031, "s": 595, "text": "Input:\nThe fuction takes 2 argument as input, first the 2D matrix mat[][] and second an integer variable N, denoting the size of the matrix.\nThere will be T test cases and for each test case the function will be called separately.\n\nOutput:\nThe function must return the reference pointer to the head of the linked list.\n\nConstraints:\n1<=T<=100\n1<=N<=150\n\nExample:\nInput:\n2\n3\n1 2 3 4 5 6 7 8 9\n2\n1 2 3 4\nOutput:\n1 2 3 4 5 6 7 8 9\n1 2 3 4" }, { "code": null, "e": 1340, "s": 1031, "text": "Note:The Input/Ouput format and Example given are used for system's internal purpose, and should be used by a user for Expected Output only. As it is a function problem, hence a user should not read any input from stdin/console. The task is to complete the function specified, and not to write the full code." }, { "code": null, "e": 1342, "s": 1340, "text": "0" }, { "code": null, "e": 1370, "s": 1342, "text": "satyamkumar96002 months ago" }, { "code": null, "e": 2382, "s": 1370, "text": " static Node constructl(Node head,int data){\n if(head == null){\n Node temp = new Node(data);\n head = temp;\n return head;\n }\n Node temp = head;\n while(temp.right!=null){\n temp =temp.right;\n }\n Node t = new Node(data);\n temp.right = t;\n return head;\n }\n static Node construct(int arr[][],int n)\n {\n //Add your code here.\n Node arrl[] = new Node[n];\n for (int i = 0;i<n;i++){\n \n for(int j =0;j<n;j++){\n \n arrl[i] = constructl(arrl[i],arr[i][j]); \n }\n \n } \n \n for(int i = 0;i<n-1;i++){\n Node head = arrl[i];\n Node anhead = arrl[i+1];\n while(head!= null){\n head.down = anhead;\n head = head.right;\n anhead = anhead.right;\n }\n }\n \n return arrl[0];\n \n }" }, { "code": null, "e": 2385, "s": 2382, "text": "+2" }, { "code": null, "e": 2412, "s": 2385, "text": "haritasboy12052 months ago" }, { "code": null, "e": 2427, "s": 2412, "text": "C++ | Solution" }, { "code": null, "e": 3044, "s": 2427, "text": "Node* constructLinkedMatrix(int mat[MAX][MAX], int n)\n{\n // code here\n Node* head = new Node(mat[0][0]);\n Node* temp = head;\n \n for(int i=0;i<n;i++)\n {\n Node* temp2 = temp;\n for(int j=0;j<n;j++)\n {\n if(j+1 == n)\n temp->right = NULL;\n else\n temp->right = new Node(mat[i][j+1]);\n if(i+1 == n)\n temp->down = NULL;\n else\n temp->down = new Node(mat[i+1][j]);\n temp = temp->right; \n }\n temp = temp2;\n temp = temp->down;\n }\n return head;\n}" }, { "code": null, "e": 3047, "s": 3044, "text": "+1" }, { "code": null, "e": 3081, "s": 3047, "text": "mohankrishnapeddineni3 months ago" }, { "code": null, "e": 3093, "s": 3081, "text": "//JAVA CODE" }, { "code": null, "e": 3671, "s": 3093, "text": " static Node construct(int arr[][],int n) { Node head=new Node(arr[0][0]); Node temp=head; for(int i=0;i<n;i++){ Node t = temp; for(int j=0;j<n;j++){ if(j+1==n){ temp.right =null; } else temp.right = new Node(arr[i][j+1]); if(i+1==n){ temp.down = null; } else temp.down = new Node(arr[i+1][j]); temp =temp.right; } temp = t; temp =temp.down; } return head; }" }, { "code": null, "e": 3673, "s": 3671, "text": "0" }, { "code": null, "e": 3695, "s": 3673, "text": "user_4tly3 months ago" }, { "code": null, "e": 4384, "s": 3695, "text": "Node* constructLinkedMatrix(int mat[MAX][MAX], int n){ // code here Node* head = NULL; Node* lastRowHead = NULL; Node* lastRowPointer = NULL; for(int i=0 ; i<n ; i++) { Node* temp = NULL; for(int j=0 ; j<n ; j++) { Node* nw = new Node(mat[i][j]); if(temp != NULL){ temp->right = nw; } if(i != 0){ lastRowPointer->down = nw; lastRowPointer = lastRowPointer->right; } temp = nw; if(j==0){ lastRowHead = temp; } if(head == NULL) head = temp; } lastRowPointer = lastRowHead; } return head;} " }, { "code": null, "e": 4386, "s": 4384, "text": "0" }, { "code": null, "e": 4413, "s": 4386, "text": "yadavkapil23363 months ago" }, { "code": null, "e": 4417, "s": 4413, "text": "C++" }, { "code": null, "e": 4678, "s": 4417, "text": "Node* constructLinkedMatrix(int mat[MAX][MAX], int n){ int i,j; Node* head=new Node(mat[0][0]); Node* temp1=head; Node* temp2=head; for(i=1;i<n;i++) { temp1->right=new Node(mat[0][i]); temp1=temp1->right; }" }, { "code": null, "e": 5154, "s": 4678, "text": " for(j=1;j<n;j++) { temp1=head; temp2=head; while(temp1->down!=NULL) temp1=temp1->down; while(temp2->down!=NULL) temp2=temp2->down; temp2->down=new Node(mat[j][0]); temp2=temp2->down; for(i=1;i<n;i++) { temp1=temp1->right; temp2->right=new Node(mat[j][i]); temp1->down=temp2->right; temp2=temp2->right; } } return(head); }" }, { "code": null, "e": 5156, "s": 5154, "text": "0" }, { "code": null, "e": 5181, "s": 5156, "text": "abhisinha6563 months ago" }, { "code": null, "e": 5424, "s": 5181, "text": "Node* newNode(int d){ Node* temp = (struct Node*)malloc(sizeof(struct Node)); temp->data = d; temp->right = temp->down = NULL; return temp;}Node* constructLinkedMatrix(int mat[MAX][MAX], int n){ // code here Node* mainhead = NULL;" }, { "code": null, "e": 5470, "s": 5424, "text": " Node* head[n]; Node *righttemp, *newptr;" }, { "code": null, "e": 5600, "s": 5470, "text": " for (int i = 0; i < n; i++) { head[i] = NULL; for (int j = 0; j < n; j++) { newptr = newNode(mat[i][j]);" }, { "code": null, "e": 6059, "s": 5600, "text": " if (!mainhead) mainhead = newptr; if (!head[i]) head[i] = newptr; else righttemp->right = newptr; righttemp = newptr; } } for (int i = 0; i < n - 1; i++) { Node *temp1 = head[i], *temp2 = head[i + 1]; while (temp1 && temp2) { temp1->down = temp2; temp1 = temp1->right; temp2 = temp2->right; } } return mainhead;} " }, { "code": null, "e": 6061, "s": 6059, "text": "0" }, { "code": null, "e": 6090, "s": 6061, "text": "ankitsinha1112005 months ago" }, { "code": null, "e": 6777, "s": 6090, "text": "Node* constructLinkedMatrix(int mat[MAX][MAX], int n)\n{\n Node* temp2=NULL,*temp3,*temp4;\n for(int i=n-1;i>=0;i--)\n {\n Node* temp1=NULL;\n for(int j=n-1;j>=0;j--)\n {\n Node* temp=new Node(mat[i][j]);\n temp->right=temp1;\n if(i==n-1)\n temp->down=temp2;\n if(j==0)\n temp3=temp;\n temp1=temp;\n }\n if(i!=n-1)\n {\n temp4=temp3;\n while(temp4!=NULL)\n {\n temp4->down=temp2;\n temp4=temp4->right;\n temp2=temp2->right;\n }\n }\n temp2=temp3;\n }\n return temp3;\n}\n" }, { "code": null, "e": 6779, "s": 6777, "text": "0" }, { "code": null, "e": 6808, "s": 6779, "text": "ankitsinha1112005 months ago" }, { "code": null, "e": 6813, "s": 6810, "text": "+1" }, { "code": null, "e": 6836, "s": 6813, "text": "imranwahid6 months ago" }, { "code": null, "e": 6854, "s": 6836, "text": "Easy C++ solution" }, { "code": null, "e": 6856, "s": 6854, "text": "0" }, { "code": null, "e": 6886, "s": 6856, "text": "sushilkumarskp6187 months ago" }, { "code": null, "e": 6958, "s": 6886, "text": "What is wrong with this, error- null pointer error in bold-line below. " }, { "code": null, "e": 7354, "s": 6960, "text": " static Node construct(int arr[][],int n) { Node headnode = new Node(arr[0][0]); Node temp1 = headnode; for(int i = 0; i<n; i++){ Node temp =temp1; for(int j=0; j<n;j++){ temp.data = arr[i][j]; temp = temp.right; } temp1 = temp1.down; } return headnode; }" }, { "code": null, "e": 7500, "s": 7354, "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": 7536, "s": 7500, "text": " Login to access your submissions. " }, { "code": null, "e": 7546, "s": 7536, "text": "\nProblem\n" }, { "code": null, "e": 7556, "s": 7546, "text": "\nContest\n" }, { "code": null, "e": 7619, "s": 7556, "text": "Reset the IDE using the second button on the top right corner." }, { "code": null, "e": 7767, "s": 7619, "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": 7975, "s": 7767, "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": 8081, "s": 7975, "text": "You can access the hints to get an idea about what is expected of you as well as the final solution code." } ]
Java HashSet
A HashSet is a collection of items where every item is unique, and it is found in the java.util package: Create a HashSet object called cars that will store strings: import java.util.HashSet; // Import the HashSet class HashSet<String> cars = new HashSet<String>(); The HashSet class has many useful methods. For example, to add items to it, use the add() method: // Import the HashSet class import java.util.HashSet; public class Main { public static void main(String[] args) { HashSet<String> cars = new HashSet<String>(); cars.add("Volvo"); cars.add("BMW"); cars.add("Ford"); cars.add("BMW"); cars.add("Mazda"); System.out.println(cars); } } Try it Yourself » Note: In the example above, even though BMW is added twice it only appears once in the set because every item in a set has to be unique. To check whether an item exists in a HashSet, use the contains() method: cars.contains("Mazda"); Try it Yourself » To remove an item, use the remove() method: cars.remove("Volvo"); Try it Yourself » To remove all items, use the clear() method: cars.clear(); Try it Yourself » To find out how many items there are, use the size method: cars.size(); Try it Yourself » Loop through the items of an HashSet with a for-each loop: for (String i : cars) { System.out.println(i); } Try it Yourself » Items in an HashSet are actually objects. In the examples above, we created items (objects) of type "String". Remember that a String in Java is an object (not a primitive type). To use other types, such as int, you must specify an equivalent wrapper class: Integer. For other primitive types, use: Boolean for boolean, Character for char, Double for double, etc: Use a HashSet that stores Integer objects: import java.util.HashSet; public class Main { public static void main(String[] args) { // Create a HashSet object called numbers HashSet<Integer> numbers = new HashSet<Integer>(); // Add values to the set numbers.add(4); numbers.add(7); numbers.add(8); // Show which numbers between 1 and 10 are in the set for(int i = 1; i <= 10; i++) { if(numbers.contains(i)) { System.out.println(i + " was found in the set."); } else { System.out.println(i + " was not found in the set."); } } } } Try it Yourself » We just launchedW3Schools videos Get certifiedby completinga course today! If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail: [email protected] Your message has been sent to W3Schools.
[ { "code": null, "e": 106, "s": 0, "text": "A HashSet is a collection of items where every item is unique, and it is found in the java.util \npackage:" }, { "code": null, "e": 167, "s": 106, "text": "Create a HashSet object called cars that will store strings:" }, { "code": null, "e": 269, "s": 167, "text": "import java.util.HashSet; // Import the HashSet class\n\nHashSet<String> cars = new HashSet<String>();\n" }, { "code": null, "e": 368, "s": 269, "text": "The HashSet class has many useful methods. For example, to \nadd items to it, use the add() method:" }, { "code": null, "e": 683, "s": 368, "text": "// Import the HashSet class\nimport java.util.HashSet;\n\npublic class Main {\n public static void main(String[] args) {\n HashSet<String> cars = new HashSet<String>();\n cars.add(\"Volvo\");\n cars.add(\"BMW\");\n cars.add(\"Ford\");\n cars.add(\"BMW\");\n cars.add(\"Mazda\");\n System.out.println(cars);\n }\n}\n" }, { "code": null, "e": 703, "s": 683, "text": "\nTry it Yourself »\n" }, { "code": null, "e": 840, "s": 703, "text": "Note: In the example above, even though BMW is added twice it only appears once in the set\nbecause every item in a set has to be unique." }, { "code": null, "e": 913, "s": 840, "text": "To check whether an item exists in a HashSet, use the contains() method:" }, { "code": null, "e": 938, "s": 913, "text": "cars.contains(\"Mazda\");\n" }, { "code": null, "e": 958, "s": 938, "text": "\nTry it Yourself »\n" }, { "code": null, "e": 1002, "s": 958, "text": "To remove an item, use the remove() method:" }, { "code": null, "e": 1025, "s": 1002, "text": "cars.remove(\"Volvo\");\n" }, { "code": null, "e": 1045, "s": 1025, "text": "\nTry it Yourself »\n" }, { "code": null, "e": 1090, "s": 1045, "text": "To remove all items, use the clear() method:" }, { "code": null, "e": 1105, "s": 1090, "text": "cars.clear();\n" }, { "code": null, "e": 1125, "s": 1105, "text": "\nTry it Yourself »\n" }, { "code": null, "e": 1184, "s": 1125, "text": "To find out how many items there are, use the size method:" }, { "code": null, "e": 1198, "s": 1184, "text": "cars.size();\n" }, { "code": null, "e": 1218, "s": 1198, "text": "\nTry it Yourself »\n" }, { "code": null, "e": 1277, "s": 1218, "text": "Loop through the items of an HashSet with a for-each loop:" }, { "code": null, "e": 1328, "s": 1277, "text": "for (String i : cars) {\n System.out.println(i);\n}" }, { "code": null, "e": 1348, "s": 1328, "text": "\nTry it Yourself »\n" }, { "code": null, "e": 1715, "s": 1348, "text": "Items in an HashSet are actually objects. In the examples above, we created \nitems \n(objects) of type \"String\". Remember that a String in Java is an object (not a primitive type). To use other types, such as int, you must specify an equivalent wrapper class: Integer. For other primitive types, \nuse: Boolean for boolean, Character for char, Double for double, \netc:" }, { "code": null, "e": 1758, "s": 1715, "text": "Use a HashSet that stores Integer objects:" }, { "code": null, "e": 2322, "s": 1758, "text": "import java.util.HashSet;\n\npublic class Main {\n public static void main(String[] args) {\n\n // Create a HashSet object called numbers\n HashSet<Integer> numbers = new HashSet<Integer>();\n\n // Add values to the set\n numbers.add(4);\n numbers.add(7);\n numbers.add(8);\n\n // Show which numbers between 1 and 10 are in the set\n for(int i = 1; i <= 10; i++) {\n if(numbers.contains(i)) {\n System.out.println(i + \" was found in the set.\");\n } else {\n System.out.println(i + \" was not found in the set.\");\n }\n }\n }\n}\n" }, { "code": null, "e": 2342, "s": 2322, "text": "\nTry it Yourself »\n" }, { "code": null, "e": 2375, "s": 2342, "text": "We just launchedW3Schools videos" }, { "code": null, "e": 2417, "s": 2375, "text": "Get certifiedby completinga course today!" }, { "code": null, "e": 2524, "s": 2417, "text": "If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:" }, { "code": null, "e": 2543, "s": 2524, "text": "[email protected]" } ]
Java Program to Convert TimeStamp to Date - GeeksforGeeks
17 Jan, 2022 Date Time class is used to display date and time and manipulate date and time in java and in addition to this it is also used for formatting date and time class in java across time zone associated data. So in order to import this class from a package called java.utils Timestamp class can be converted to Date class in java using the Date class which is present in Java.Util package. The constructor of the Date class receives a long value as an argument. Since the constructor of the Date class requires a long value, we need to convert the Timestamp object into a long value using the getTime() method of the TimeStamp class(present in SQL package). In order to import date class syntax is as follows: import java.util.Date ; After importing this class one can create an object of the Date class in order to print the current date and time. Now in order to print the default date and time simply call the print command using toString() method to get the current date and time Note: In order to print no of milliseconds till now simply use getTime() instead of to String() to get no of milliseconds till the program is being executed. Also, remember 01-01-1970 is the base reference also referred to as Epoch time. Methods: There are 3 ways to do so as listed below: Using constructorsUsing date referenceUsing Calendar class Using constructors Using date reference Using Calendar class Implementation: Describing approaches with the help of java program individually: Method 1: Timestamp to Date Using Date constructor Java // Java program to convert timestamp to Date // Importing java Date librariesimport java.sql.Timestamp;import java.util.Date; class GFG { // Main driver method public static void main(String[] args) { // Getting the current system time and passing it // to constructor of time-stamp class // Using currentTimeMillis Timestamp ts = new Timestamp(System.currentTimeMillis()); // Passing the long value in the Date class // constructor Date date = new Date(ts.getTime()); // Printing the date System.out.println(date); }} Tue Nov 24 00:28:31 UTC 2020 Method 2: Timestamp to Date Using Date Reference The Timestamp class extends the Date class. So, you can directly assign an instance of the Timestamp class to Date. In such a case, the output of the Date object will be like Timestamp ie it would be in the format like date followed by time (to the scale of milliseconds). Java // Java program to convert timestamp to Date// Importing java Date librariesimport java.sql.Timestamp;import java.util.Date; class GFG { // Main driver method public static void main(String[] args) { // Getting the current system time and passing it // to constructor of time-stamp class Timestamp ts = new Timestamp(System.currentTimeMillis()); /* Date class is super class of TimeStamp class*/ // Directly assigning the object of // timestamp class to date class Date date = ts; // Printing the date System.out.println(date); }} 2020-11-24 00:28:30.646 Method 3: Timestamp to Date Using Calendar class We can also use calendar class to get the Date using Timestamp, below is the implementation of the approach to convert timestamp to date. Java // Java program to convert timestamp to Date // Importing java Date librariesimport java.sql.Timestamp;import java.util.Date;import java.util.Calendar; class GFG { // Main driver method public static void main(String[] args) { // Getting the current system time and passing it // to constructor of time-stamp class Timestamp timestamp = new Timestamp(System.currentTimeMillis()); // Getting the calendar class instance Calendar calendar = Calendar.getInstance(); // Passing the long value to calendar class function calendar.setTimeInMillis(timestamp.getTime()); // Getting the time using getTime() function System.out.println(calendar.getTime()); }} Tue Nov 24 00:28:31 UTC 2020 sweetyty Java-Date-Time Picked Technical Scripter 2020 Java Java Programs Technical Scripter Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Functional Interfaces in Java Stream In Java Constructors in Java Different ways of Reading a text file in Java Exceptions in Java Convert a String to Character array in Java Java Programming Examples Convert Double to Integer in Java Implementing a Linked List in Java using Class How to Iterate HashMap in Java?
[ { "code": null, "e": 23557, "s": 23529, "text": "\n17 Jan, 2022" }, { "code": null, "e": 23826, "s": 23557, "text": "Date Time class is used to display date and time and manipulate date and time in java and in addition to this it is also used for formatting date and time class in java across time zone associated data. So in order to import this class from a package called java.utils" }, { "code": null, "e": 24209, "s": 23826, "text": "Timestamp class can be converted to Date class in java using the Date class which is present in Java.Util package. The constructor of the Date class receives a long value as an argument. Since the constructor of the Date class requires a long value, we need to convert the Timestamp object into a long value using the getTime() method of the TimeStamp class(present in SQL package)." }, { "code": null, "e": 24285, "s": 24209, "text": "In order to import date class syntax is as follows: import java.util.Date ;" }, { "code": null, "e": 24536, "s": 24285, "text": "After importing this class one can create an object of the Date class in order to print the current date and time. Now in order to print the default date and time simply call the print command using toString() method to get the current date and time " }, { "code": null, "e": 24774, "s": 24536, "text": "Note: In order to print no of milliseconds till now simply use getTime() instead of to String() to get no of milliseconds till the program is being executed. Also, remember 01-01-1970 is the base reference also referred to as Epoch time." }, { "code": null, "e": 24826, "s": 24774, "text": "Methods: There are 3 ways to do so as listed below:" }, { "code": null, "e": 24885, "s": 24826, "text": "Using constructorsUsing date referenceUsing Calendar class" }, { "code": null, "e": 24904, "s": 24885, "text": "Using constructors" }, { "code": null, "e": 24925, "s": 24904, "text": "Using date reference" }, { "code": null, "e": 24946, "s": 24925, "text": "Using Calendar class" }, { "code": null, "e": 25028, "s": 24946, "text": "Implementation: Describing approaches with the help of java program individually:" }, { "code": null, "e": 25079, "s": 25028, "text": "Method 1: Timestamp to Date Using Date constructor" }, { "code": null, "e": 25084, "s": 25079, "text": "Java" }, { "code": "// Java program to convert timestamp to Date // Importing java Date librariesimport java.sql.Timestamp;import java.util.Date; class GFG { // Main driver method public static void main(String[] args) { // Getting the current system time and passing it // to constructor of time-stamp class // Using currentTimeMillis Timestamp ts = new Timestamp(System.currentTimeMillis()); // Passing the long value in the Date class // constructor Date date = new Date(ts.getTime()); // Printing the date System.out.println(date); }}", "e": 25692, "s": 25084, "text": null }, { "code": null, "e": 25724, "s": 25695, "text": "Tue Nov 24 00:28:31 UTC 2020" }, { "code": null, "e": 25773, "s": 25724, "text": "Method 2: Timestamp to Date Using Date Reference" }, { "code": null, "e": 26048, "s": 25775, "text": "The Timestamp class extends the Date class. So, you can directly assign an instance of the Timestamp class to Date. In such a case, the output of the Date object will be like Timestamp ie it would be in the format like date followed by time (to the scale of milliseconds)." }, { "code": null, "e": 26055, "s": 26050, "text": "Java" }, { "code": "// Java program to convert timestamp to Date// Importing java Date librariesimport java.sql.Timestamp;import java.util.Date; class GFG { // Main driver method public static void main(String[] args) { // Getting the current system time and passing it // to constructor of time-stamp class Timestamp ts = new Timestamp(System.currentTimeMillis()); /* Date class is super class of TimeStamp class*/ // Directly assigning the object of // timestamp class to date class Date date = ts; // Printing the date System.out.println(date); }}", "e": 26677, "s": 26055, "text": null }, { "code": null, "e": 26704, "s": 26680, "text": "2020-11-24 00:28:30.646" }, { "code": null, "e": 26753, "s": 26704, "text": "Method 3: Timestamp to Date Using Calendar class" }, { "code": null, "e": 26893, "s": 26755, "text": "We can also use calendar class to get the Date using Timestamp, below is the implementation of the approach to convert timestamp to date." }, { "code": null, "e": 26900, "s": 26895, "text": "Java" }, { "code": "// Java program to convert timestamp to Date // Importing java Date librariesimport java.sql.Timestamp;import java.util.Date;import java.util.Calendar; class GFG { // Main driver method public static void main(String[] args) { // Getting the current system time and passing it // to constructor of time-stamp class Timestamp timestamp = new Timestamp(System.currentTimeMillis()); // Getting the calendar class instance Calendar calendar = Calendar.getInstance(); // Passing the long value to calendar class function calendar.setTimeInMillis(timestamp.getTime()); // Getting the time using getTime() function System.out.println(calendar.getTime()); }}", "e": 27641, "s": 26900, "text": null }, { "code": null, "e": 27673, "s": 27644, "text": "Tue Nov 24 00:28:31 UTC 2020" }, { "code": null, "e": 27684, "s": 27675, "text": "sweetyty" }, { "code": null, "e": 27699, "s": 27684, "text": "Java-Date-Time" }, { "code": null, "e": 27706, "s": 27699, "text": "Picked" }, { "code": null, "e": 27730, "s": 27706, "text": "Technical Scripter 2020" }, { "code": null, "e": 27735, "s": 27730, "text": "Java" }, { "code": null, "e": 27749, "s": 27735, "text": "Java Programs" }, { "code": null, "e": 27768, "s": 27749, "text": "Technical Scripter" }, { "code": null, "e": 27773, "s": 27768, "text": "Java" }, { "code": null, "e": 27871, "s": 27773, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27880, "s": 27871, "text": "Comments" }, { "code": null, "e": 27893, "s": 27880, "text": "Old Comments" }, { "code": null, "e": 27923, "s": 27893, "text": "Functional Interfaces in Java" }, { "code": null, "e": 27938, "s": 27923, "text": "Stream In Java" }, { "code": null, "e": 27959, "s": 27938, "text": "Constructors in Java" }, { "code": null, "e": 28005, "s": 27959, "text": "Different ways of Reading a text file in Java" }, { "code": null, "e": 28024, "s": 28005, "text": "Exceptions in Java" }, { "code": null, "e": 28068, "s": 28024, "text": "Convert a String to Character array in Java" }, { "code": null, "e": 28094, "s": 28068, "text": "Java Programming Examples" }, { "code": null, "e": 28128, "s": 28094, "text": "Convert Double to Integer in Java" }, { "code": null, "e": 28175, "s": 28128, "text": "Implementing a Linked List in Java using Class" } ]
Feature Selection by Chi-Square | Towards Data Science
In our everyday data science work, we often encounter categorical features. Some people would be confused about how to handle these features, especially when we want to create a prediction model where those models basically an equation that accepting number; not a category. One way is to encode all the category variable using the OneHotEncoding method (encode all the categorical class into numerical values 0 and 1, where 0 mean absent and 1 is present). This method is preferable by many as the information is still present and it is easy to understand the concept. The downfall is when we possess many categorical features with high cardinality, the number of the features after OneHotEncoding process would be massive. Why we do not want a lot of features in our training dataset? it is because of the curse of dimensionality. While adding features could decrease the error in our prediction model, it would only decrease until a certain number of features; after that, the error will increase again. This is the concept of the curse of dimensionality. Many ways to alleviate this problem, but one of my to-go techniques is by doing feature selection via the Chi-Square test of independence. The Chi-Square test of independence is used to determine if there is a significant relationship between two categorical (nominal) variables. It means the Chi-Square Test of Independence is a hypothesis testing test with 2 hypotheses present; the Null Hypothesis and the Alternative Hypothesis. The hypothesis is written below. Null Hypothesis (H0): There is no relationship between the variables Alternative Hypothesis (H1): There is a relationship between variables Just like any statistical testing, we test it against our chosen p-value (often it is 0.05). If the p-value is significant, we can reject the null hypothesis and claim that the findings support the alternative hypothesis. I would not dwell much into the statistic theory, as the purpose of this article is to show how the feature selection using the Chi-Square test is works for practical use. As an example, I would work with a loan dataset from Kaggle for classification problems. Here, the dataset including various numerical, ordinal and nominal variables as stated below (for article purposes, I would drop all the Null values which actually need another analysis). import pandas as pdloan = pd.read_csv('loan_data_set.csv')#Dropping the uninformative featureloan.drop('Loan_ID')#Transform the numerical feature into categorical featureloan['Loan_Amount_Term'] = loan['Loan_Amount_Term'].astype('object')loan['Credit_History'] = loan['Credit_History'].astype('object')#Dropping all the null valueloan.dropna(inplace = True)#Getting all the categorical columns except the targetcategorical_columns = loan.select_dtypes(exclude = 'number').drop('Loan_Status', axis = 1).columnsloan.info() In the Chi-Square test, we display the data in a cross-tabulation (contingency) format with each row representing a level (group) for one variable and each column representing a level (group) for another variable. Let’s try to create a cross-tabulation table between Gender and Loan_Status columns. pd.crosstab(loan['Gender'], loan['Loan_Status']) Now, let’s try to use the Chi-Square test of independence to test the relationship between these 2 features. Luckily python library scipy already contains the test function for us to use. # Import the functionfrom scipy.stats import chi2_contingency#Testing the relationshipchi_res = chi2_contingency(pd.crosstab(loan['Loan_Status'], loan['Gender']))print('Chi2 Statistic: {}, p-value: {}'.format(chi_res[0], chi_res[1])) If we choose our p-value level to 0.05, as the p-value test result is more than 0.05 we fail to reject the Null Hypothesis. This means, there is no relationship between the Gender and Loan_Status feature based on the Chi-Square test of independence. We could try to use this test with all the categorical features present. chi2_check = []for i in categorical_columns: if chi2_contingency(pd.crosstab(loan['Loan_Status'], loan[i]))[1] < 0.05: chi2_check.append('Reject Null Hypothesis') else: chi2_check.append('Fail to Reject Null Hypothesis')res = pd.DataFrame(data = [categorical_columns, chi2_check] ).T res.columns = ['Column', 'Hypothesis']print(res) The Chi-square test of independence is an omnibus test which means it tests the data as a whole. If we have multiple classes within a category, we would not be able to easily tell which class of the features are responsible for the relationship if the Chi-square table is larger than 2×2. To pinpoint which class is responsible, we need a post hoc test. To conduct multiple 2×2 Chi-square test of independence, we need to regroup the features for each test to where it is one category class against the rest. To do this, we could apply OneHotEncoding to each class and create a new cross-tab table against the other feature. For example, let’s try to do a post hoc test to the Property_Area feature. First, we need to done OneHotEncoding to the Property_Area feature. property_dummies = pd.get_dummies(data = loan[['Property_Area', 'Loan_Status']], columns = ['Property_Area']) Next, we create the cross-tab table for each of the Property_Area class against the target Loan_Status. #Examplepd.crosstab(property_dummies['Loan_Status'], property_dummies['Property_Area_Rural']) We then could do a Chi-Square test of independence to this pair. However, there is something to remember. Comparing multiple classes against each other would means that the error rate of a false positive compound with each test. For example, if we choose our first test at p-value level 0.05 means there is a 5% chance of a false positive; if we have multiple classes, the test after that would compounding the error with the chance become 10% of a false positive, and so forth. With each subsequent test, the error rate would increase by 5%. In our case above, we had 3 pairwise comparisons. This means that our Chi-square test would have an error rate of 15%. Meaning our p-value being tested at would equal 0.15, which is quite high. In this case, we could use the Bonferroni-adjusted method for correcting the p-value we use. We adjust our P-value by the number of pairwise comparisons we want to do. The formula is p/N, where p= the p-value of the original test and N= the number of planned pairwise comparisons. For example, in our case, above we have 3 class within the Property_Area feature; which means we would have 3 pairwise comparisons if we test all the class against the Loan_Status feature. Our P-value would be 0.05/3 = 0.0167 Using the adjusted P-value, we could test all the previously significant result to see which class are responsible for creating a significant relationship. check = {}for i in res[res['Hypothesis'] == 'Reject Null Hypothesis']['Column']: dummies = pd.get_dummies(loan[i]) bon_p_value = 0.05/loan[i].nunique() for series in dummies: if chi2_contingency(pd.crosstab(loan['Loan_Status'], dummies[series]))[1] < bon_p_value: check['{}-{}'.format(i, series)] = 'Reject Null Hypothesis' else: check['{}-{}'.format(i, series)] = 'Fail to Reject Null Hypothesis'res_chi_ph = pd.DataFrame(data = [check.keys(), check.values()]).Tres_chi_ph.columns = ['Pair', 'Hypothesis']res_chi_ph Here I also include the binary feature for pairwise comparison. As we can see, many of the classes are not actually significant. Even the Loan_Amount_Term that previously significant before the post hoc test resulted in all the classes are not significant. The aim of this feature selection technique is to see how it impact our prediction model. Let’s use the simplest model; Logistic Regression as a benchmark. First, I would use all the data and see the model performance in the initial phase. Here, I treat all the categorical data as nominal (even the ordinal data). #OneHotEncoding all the categorical variable except the target; Also drop_first = True to avoid multicollinearity for Logistic Regressiondata_log = pd.get_dummies(data = loan, columns = loan.select_dtypes(exclude = 'number').drop('Loan_Status', axis =1).columns, drop_first =True)#Change the class into numerical valuedata_log['Loan_Status'] = data_log['Loan_Status'].apply(lambda x: 0 if x == 'N' else 1)#Splitting the data into Training and Test datafrom sklearn.model_selection import train_test_splitX_train, X_test, y_train, y_test = train_test_split(data_log.drop('Loan_Status', axis =1), data_log['Loan_Status'], test_size = 0.30, random_state = 101)#Creating the prediction modelfrom sklearn.linear_model import LogisticRegressionlog_model = LogisticRegression(max_iter = 1000)log_model.fit(X_train, y_train)#Performance Checkfrom sklearn.metrics import classification_report, confusion_matrix, roc_curve,auc, accuracy_scorepredictions = log_model.predict(X_test)print(accuracy_score(y_test, predictions))Out: 0.7708333333333334print(classification_report(y_test,predictions)) #Creating the ROC-AUC plotpreds = log_model.predict_proba(X_test)[:,1]fpr, tpr, threshold = roc_curve(y_test, preds)roc_auc = auc(fpr, tpr)plt.figure(figsize=(10,8))plt.title('Receiver Operator Characteristic')plt.plot(fpr, tpr, 'b', label = 'AUC = {}'.format(round(roc_auc, 2)))plt.legend(loc = 'lower right')plt.plot([0,1], [0,1], 'r--')plt.xlim([0,1])plt.ylim([0,1])plt.ylabel('True Positive Rate')plt.xlabel('False Positive Rate')plt.show() Above is the model performance if we use all the data, let’s compare it with the data we selecting via the Chi-Square Test of Independence. #Get the list of all the significant pairwisesignificant_chi = []for i in res_chi[res_chi['Hypothesis'] == 'Reject Null Hypothesis']['Pair']: significant_chi.append('{}_{}'.format(i.split('-')[0],i.split('-')[1]))#Drop the data with duplicate informationfor i in ['Married_No', 'Credit_History_0.0']: significant_chi.remove(i)#Including the numerical data, as I have not analyze any of this featurefor i in loan.select_dtypes('number').columns: significant_chi.append(i)print(significant_chi)Out: ['Married_Yes', 'Credit_History_1.0','Property_Area_Semiurban', 'ApplicantIncome','CoapplicantIncome', 'LoanAmount'] Previously, if we use all the data as it is we would end up with 21 independent variables. With feature selection, we only have 6 features to work with. I would not do the train test splitting once more because I want to test the data with the same training data and test data. Let’s see how our model performance is with these selected features. #Training the model only with the significant features and the numerical featureslog_model = LogisticRegression(max_iter = 1000)log_model.fit(X_train[significant_chi], y_train)#Metrics checkpredictions = log_model.predict(X_test[significant_chi])print(accuracy_score(y_test, predictions))Out: 0.7847222222222222print(classification_report(y_test,predictions)) Metrics wise, the model with selected features is doing slightly better than the one trained with all the features. Theoretically speaking, it could happen because we eliminate all the noise in the data and only end up with the most important pattern. Although, we have not yet analyzed the numerical data which could also be important. Overall, I have shown that with the Chi-Square test of independence we could end up only with the most important categorical features. If you are not subscribed as a Medium Member, please consider subscribing through my referral.
[ { "code": null, "e": 447, "s": 172, "text": "In our everyday data science work, we often encounter categorical features. Some people would be confused about how to handle these features, especially when we want to create a prediction model where those models basically an equation that accepting number; not a category." }, { "code": null, "e": 630, "s": 447, "text": "One way is to encode all the category variable using the OneHotEncoding method (encode all the categorical class into numerical values 0 and 1, where 0 mean absent and 1 is present)." }, { "code": null, "e": 1005, "s": 630, "text": "This method is preferable by many as the information is still present and it is easy to understand the concept. The downfall is when we possess many categorical features with high cardinality, the number of the features after OneHotEncoding process would be massive. Why we do not want a lot of features in our training dataset? it is because of the curse of dimensionality." }, { "code": null, "e": 1231, "s": 1005, "text": "While adding features could decrease the error in our prediction model, it would only decrease until a certain number of features; after that, the error will increase again. This is the concept of the curse of dimensionality." }, { "code": null, "e": 1370, "s": 1231, "text": "Many ways to alleviate this problem, but one of my to-go techniques is by doing feature selection via the Chi-Square test of independence." }, { "code": null, "e": 1697, "s": 1370, "text": "The Chi-Square test of independence is used to determine if there is a significant relationship between two categorical (nominal) variables. It means the Chi-Square Test of Independence is a hypothesis testing test with 2 hypotheses present; the Null Hypothesis and the Alternative Hypothesis. The hypothesis is written below." }, { "code": null, "e": 1766, "s": 1697, "text": "Null Hypothesis (H0): There is no relationship between the variables" }, { "code": null, "e": 1837, "s": 1766, "text": "Alternative Hypothesis (H1): There is a relationship between variables" }, { "code": null, "e": 2231, "s": 1837, "text": "Just like any statistical testing, we test it against our chosen p-value (often it is 0.05). If the p-value is significant, we can reject the null hypothesis and claim that the findings support the alternative hypothesis. I would not dwell much into the statistic theory, as the purpose of this article is to show how the feature selection using the Chi-Square test is works for practical use." }, { "code": null, "e": 2508, "s": 2231, "text": "As an example, I would work with a loan dataset from Kaggle for classification problems. Here, the dataset including various numerical, ordinal and nominal variables as stated below (for article purposes, I would drop all the Null values which actually need another analysis)." }, { "code": null, "e": 3029, "s": 2508, "text": "import pandas as pdloan = pd.read_csv('loan_data_set.csv')#Dropping the uninformative featureloan.drop('Loan_ID')#Transform the numerical feature into categorical featureloan['Loan_Amount_Term'] = loan['Loan_Amount_Term'].astype('object')loan['Credit_History'] = loan['Credit_History'].astype('object')#Dropping all the null valueloan.dropna(inplace = True)#Getting all the categorical columns except the targetcategorical_columns = loan.select_dtypes(exclude = 'number').drop('Loan_Status', axis = 1).columnsloan.info()" }, { "code": null, "e": 3328, "s": 3029, "text": "In the Chi-Square test, we display the data in a cross-tabulation (contingency) format with each row representing a level (group) for one variable and each column representing a level (group) for another variable. Let’s try to create a cross-tabulation table between Gender and Loan_Status columns." }, { "code": null, "e": 3377, "s": 3328, "text": "pd.crosstab(loan['Gender'], loan['Loan_Status'])" }, { "code": null, "e": 3565, "s": 3377, "text": "Now, let’s try to use the Chi-Square test of independence to test the relationship between these 2 features. Luckily python library scipy already contains the test function for us to use." }, { "code": null, "e": 3799, "s": 3565, "text": "# Import the functionfrom scipy.stats import chi2_contingency#Testing the relationshipchi_res = chi2_contingency(pd.crosstab(loan['Loan_Status'], loan['Gender']))print('Chi2 Statistic: {}, p-value: {}'.format(chi_res[0], chi_res[1]))" }, { "code": null, "e": 4049, "s": 3799, "text": "If we choose our p-value level to 0.05, as the p-value test result is more than 0.05 we fail to reject the Null Hypothesis. This means, there is no relationship between the Gender and Loan_Status feature based on the Chi-Square test of independence." }, { "code": null, "e": 4122, "s": 4049, "text": "We could try to use this test with all the categorical features present." }, { "code": null, "e": 4488, "s": 4122, "text": "chi2_check = []for i in categorical_columns: if chi2_contingency(pd.crosstab(loan['Loan_Status'], loan[i]))[1] < 0.05: chi2_check.append('Reject Null Hypothesis') else: chi2_check.append('Fail to Reject Null Hypothesis')res = pd.DataFrame(data = [categorical_columns, chi2_check] ).T res.columns = ['Column', 'Hypothesis']print(res)" }, { "code": null, "e": 4842, "s": 4488, "text": "The Chi-square test of independence is an omnibus test which means it tests the data as a whole. If we have multiple classes within a category, we would not be able to easily tell which class of the features are responsible for the relationship if the Chi-square table is larger than 2×2. To pinpoint which class is responsible, we need a post hoc test." }, { "code": null, "e": 5113, "s": 4842, "text": "To conduct multiple 2×2 Chi-square test of independence, we need to regroup the features for each test to where it is one category class against the rest. To do this, we could apply OneHotEncoding to each class and create a new cross-tab table against the other feature." }, { "code": null, "e": 5256, "s": 5113, "text": "For example, let’s try to do a post hoc test to the Property_Area feature. First, we need to done OneHotEncoding to the Property_Area feature." }, { "code": null, "e": 5366, "s": 5256, "text": "property_dummies = pd.get_dummies(data = loan[['Property_Area', 'Loan_Status']], columns = ['Property_Area'])" }, { "code": null, "e": 5470, "s": 5366, "text": "Next, we create the cross-tab table for each of the Property_Area class against the target Loan_Status." }, { "code": null, "e": 5564, "s": 5470, "text": "#Examplepd.crosstab(property_dummies['Loan_Status'], property_dummies['Property_Area_Rural'])" }, { "code": null, "e": 5629, "s": 5564, "text": "We then could do a Chi-Square test of independence to this pair." }, { "code": null, "e": 6301, "s": 5629, "text": "However, there is something to remember. Comparing multiple classes against each other would means that the error rate of a false positive compound with each test. For example, if we choose our first test at p-value level 0.05 means there is a 5% chance of a false positive; if we have multiple classes, the test after that would compounding the error with the chance become 10% of a false positive, and so forth. With each subsequent test, the error rate would increase by 5%. In our case above, we had 3 pairwise comparisons. This means that our Chi-square test would have an error rate of 15%. Meaning our p-value being tested at would equal 0.15, which is quite high." }, { "code": null, "e": 6808, "s": 6301, "text": "In this case, we could use the Bonferroni-adjusted method for correcting the p-value we use. We adjust our P-value by the number of pairwise comparisons we want to do. The formula is p/N, where p= the p-value of the original test and N= the number of planned pairwise comparisons. For example, in our case, above we have 3 class within the Property_Area feature; which means we would have 3 pairwise comparisons if we test all the class against the Loan_Status feature. Our P-value would be 0.05/3 = 0.0167" }, { "code": null, "e": 6964, "s": 6808, "text": "Using the adjusted P-value, we could test all the previously significant result to see which class are responsible for creating a significant relationship." }, { "code": null, "e": 7526, "s": 6964, "text": "check = {}for i in res[res['Hypothesis'] == 'Reject Null Hypothesis']['Column']: dummies = pd.get_dummies(loan[i]) bon_p_value = 0.05/loan[i].nunique() for series in dummies: if chi2_contingency(pd.crosstab(loan['Loan_Status'], dummies[series]))[1] < bon_p_value: check['{}-{}'.format(i, series)] = 'Reject Null Hypothesis' else: check['{}-{}'.format(i, series)] = 'Fail to Reject Null Hypothesis'res_chi_ph = pd.DataFrame(data = [check.keys(), check.values()]).Tres_chi_ph.columns = ['Pair', 'Hypothesis']res_chi_ph" }, { "code": null, "e": 7783, "s": 7526, "text": "Here I also include the binary feature for pairwise comparison. As we can see, many of the classes are not actually significant. Even the Loan_Amount_Term that previously significant before the post hoc test resulted in all the classes are not significant." }, { "code": null, "e": 8098, "s": 7783, "text": "The aim of this feature selection technique is to see how it impact our prediction model. Let’s use the simplest model; Logistic Regression as a benchmark. First, I would use all the data and see the model performance in the initial phase. Here, I treat all the categorical data as nominal (even the ordinal data)." }, { "code": null, "e": 9183, "s": 8098, "text": "#OneHotEncoding all the categorical variable except the target; Also drop_first = True to avoid multicollinearity for Logistic Regressiondata_log = pd.get_dummies(data = loan, columns = loan.select_dtypes(exclude = 'number').drop('Loan_Status', axis =1).columns, drop_first =True)#Change the class into numerical valuedata_log['Loan_Status'] = data_log['Loan_Status'].apply(lambda x: 0 if x == 'N' else 1)#Splitting the data into Training and Test datafrom sklearn.model_selection import train_test_splitX_train, X_test, y_train, y_test = train_test_split(data_log.drop('Loan_Status', axis =1), data_log['Loan_Status'], test_size = 0.30, random_state = 101)#Creating the prediction modelfrom sklearn.linear_model import LogisticRegressionlog_model = LogisticRegression(max_iter = 1000)log_model.fit(X_train, y_train)#Performance Checkfrom sklearn.metrics import classification_report, confusion_matrix, roc_curve,auc, accuracy_scorepredictions = log_model.predict(X_test)print(accuracy_score(y_test, predictions))Out: 0.7708333333333334print(classification_report(y_test,predictions))" }, { "code": null, "e": 9628, "s": 9183, "text": "#Creating the ROC-AUC plotpreds = log_model.predict_proba(X_test)[:,1]fpr, tpr, threshold = roc_curve(y_test, preds)roc_auc = auc(fpr, tpr)plt.figure(figsize=(10,8))plt.title('Receiver Operator Characteristic')plt.plot(fpr, tpr, 'b', label = 'AUC = {}'.format(round(roc_auc, 2)))plt.legend(loc = 'lower right')plt.plot([0,1], [0,1], 'r--')plt.xlim([0,1])plt.ylim([0,1])plt.ylabel('True Positive Rate')plt.xlabel('False Positive Rate')plt.show()" }, { "code": null, "e": 9768, "s": 9628, "text": "Above is the model performance if we use all the data, let’s compare it with the data we selecting via the Chi-Square Test of Independence." }, { "code": null, "e": 10391, "s": 9768, "text": "#Get the list of all the significant pairwisesignificant_chi = []for i in res_chi[res_chi['Hypothesis'] == 'Reject Null Hypothesis']['Pair']: significant_chi.append('{}_{}'.format(i.split('-')[0],i.split('-')[1]))#Drop the data with duplicate informationfor i in ['Married_No', 'Credit_History_0.0']: significant_chi.remove(i)#Including the numerical data, as I have not analyze any of this featurefor i in loan.select_dtypes('number').columns: significant_chi.append(i)print(significant_chi)Out: ['Married_Yes', 'Credit_History_1.0','Property_Area_Semiurban', 'ApplicantIncome','CoapplicantIncome', 'LoanAmount']" }, { "code": null, "e": 10738, "s": 10391, "text": "Previously, if we use all the data as it is we would end up with 21 independent variables. With feature selection, we only have 6 features to work with. I would not do the train test splitting once more because I want to test the data with the same training data and test data. Let’s see how our model performance is with these selected features." }, { "code": null, "e": 11098, "s": 10738, "text": "#Training the model only with the significant features and the numerical featureslog_model = LogisticRegression(max_iter = 1000)log_model.fit(X_train[significant_chi], y_train)#Metrics checkpredictions = log_model.predict(X_test[significant_chi])print(accuracy_score(y_test, predictions))Out: 0.7847222222222222print(classification_report(y_test,predictions))" }, { "code": null, "e": 11570, "s": 11098, "text": "Metrics wise, the model with selected features is doing slightly better than the one trained with all the features. Theoretically speaking, it could happen because we eliminate all the noise in the data and only end up with the most important pattern. Although, we have not yet analyzed the numerical data which could also be important. Overall, I have shown that with the Chi-Square test of independence we could end up only with the most important categorical features." } ]
Detectron2 : The bare basic end to end tutorial | by Yousry Mohamed | Towards Data Science
In 2018, Facebook AI developed an object detection library called Detectron. It was an amazing library but a bit hard to use. An earlier version of myself wrote a blog post on just how to install Detectron and run the sample demos, nothing more. Detectron was a bit hard to install and use and it was powered by Caffe2. Since 2018, there was lots of code changes bringing Caffe2 & PyTorch into a single repository and that adds to the difficulty of using Detectron. It seems there was some constructive feedback from the community and Facebook has come up with a v2. According to GitHub page of Detectron2: Detectron2 is Facebook AI Research’s next generation software system that implements state-of-the-art object detection algorithms. Detectron2 is built using PyTorch which has much more active community now to the extent of competing with TensorFlow itself. Also the setup instructions are much easier plus a very easy to use API to extract scoring results. Other frameworks like YOLO have very obscure format of their scoring results which are delivered as a plain multi dimensional array. Anyone worked with YOLO can imagine the effort needed to parse the scoring result and get it right in the first place. Enough history, in this post I will walk you through an end to end exercise on how to prepare a Detectron2 docker image hosting a web API for object detection and use it from a small web application acting as a service consumer. I will start first with installation. Unfortunately, Windows is not supported but I will bypass that using containers. To be quick, we wouldn’t mind installing a CPU version as the GPU one needs (guess what) a GPU, CUDA and all that lovely stuff from NVIDIA. So using your preferred text editor, create a Dockerfile with the this content. It starts first by picking base image which has a Python version ≥ 3.6 as requested by Detectron2 setup instruction. Next a few prerequisites are installed then a copy of same setup instructions on Detectron2 installation page. The version installed is a CPU version, it won’t be super fast but good enough for a tutorial. Last, Flask is included as this docker image will host a web API website to accept scoring calls from clients. Let’s build the image first. docker build --rm . -t ylashin/detectron2:latest You can use any name/tag you want and adjust accordingly for the next steps. Next, let’s give it a go. docker run -it ylashin/detectron2:latest bin/bash Hopefully all the above works fine and now we have a container up and running with Detectron2 installed. So we need to verify that nothing is broken and we have unicorns and and rainbows. The following test.py script has to be copied into the container using docker CLI or by using nano which is installed on the container. The main tasks involved are: Printing Detectron2 version.Downloading an image for Lionel Messi and a soccer ball.Creating a predictor instance using one of the pre-trained architectures.Scoring the downloaded image using the predictor instance. Printing Detectron2 version. Downloading an image for Lionel Messi and a soccer ball. Creating a predictor instance using one of the pre-trained architectures. Scoring the downloaded image using the predictor instance. Next we will run that test script as shown in the next screenshot. Detectron2 seems to be at version 0.1.1 at the time of writing. Also, scoring is done correctly and the result is not a plain tensor like YOLO. It’s a typed class with easy to use members like bounding boxes and predicted classes. We will come to mapping class codes to human readable names later. What we have here is a couple bounding boxes and a couple high scores plus predicted classes of 0 (person) and 32 (sports ball). P.S. Based on the problem you are solving, you need to pick the correct architecture and see if it was trained against similar dataset or else you might need to do custom training. The next step is to make this scoring functionality accessible from outside the container. A Flask web API needs to be hosted in that container to accept an image and return scoring result. For simplicity, the API will accept an image URL and do the download itself. It will not accept binary payload which would be the natural thing to do but it’s just easy to use the same test script with slight modifications. Also the response will be a dictionary serialized as a JSON object with enough information needed by the caller without any complicated parsing. Now as the container will host a Flask web server, it has to be started with web API port published . So exit the current container and start it again with port publishing. docker run -p 8181:5000 -it ylashin/detectron2:latest bin/bash Flask port 5000 is mapped to host port 8181. Now, create a file inside the container namedweb_api.py and paste the following GitHub gist inside it. This is nearly the same test script used before with the following differences: Some refactoring to have a global predictor instance ready to be used per each request. A function mapped to a web API endpoint is used to receive HTTP request with JSON object which has image URL to be scored. This function does the scoring and also some post-processing to prepare a final response object. To start the web server run: python web_api.py The URL shown has a port of 5000 but that’s because it’s just inside the container. Any tool like Postman, curl or PowerShell can be used to test the API works as expected. For whatever tool you use, please remember to include a request header with key content-type and value application/json . If we scroll down the response in Postman, we will find the expected scoring fields such as bounding boxes, scores and class predictions. Now the web API server seems to be working fine, it’s better to be included as part of the definition of Dockerfile. That would allow us to push the built image to docker hub or any other registry and share it with others or use it without worrying about building it each time. The updated Dockerfile can be found in the repo linked to this post but for the sake of brevity, the delta added to Docker file is: WORKDIR /appCOPY web_api.py web_api.pyENTRYPOINT ["python", "/app/web_api.py"] Once the modified docker image is built, we can start the container once again but this time we don’t need to copy the web API file nor start it ourselves. Actually we can start the container as a daemon. docker run -p 8181:5000 -d ylashin/detectron2:latest The web API could be tested using Postman again for verification but we need to give the container a few seconds to download weights file part of predictor preparation. Once we are happy with the running container, we can shut it down and publish the image. docker push ylashin/detectron2:latest I published the image to my own Docker Hub account so that I can show you later how to use it with Azure container instances. The web app I will use to consume the scoring service will be hosted locally, so it can easily access a local running container. But I prefer to go to next level and host the container somewhere in the cloud to simulate a more realistic implementation. Phew, nearly there. Last stage is to consume that web API from any RESTful client. But first, I will start the container in Azure using Azure CLI and Azure container instances service. If you want to keep using the container locally, you can skip this Azure bit but adjust the web API URL in the web app that will come later. az group create --name detectron2 --location eastusaz container create --resource-group detectron2 --name predictor --image ylashin/detectron2:latest --cpu 2 --memory 4 --dns-name-label detectron2api --ports 5000az container show --resource-group detectron2 --name predictor --query "{FQDN:ipAddress.fqdn,ProvisioningState:provisioningState}" --out table Last command above will show the FQDN of the container which we can use to test the cloud hosted API using Postman. Please note that the port used here is the plain Flask port without any mapping to a different port. We have a web API endpoint up and running in the cloud that can be consumed from any REST client anywhere. I have built a small JavaScript app. The app is pretty simple: It has a text box and a button. Put a public image URL in the text box and click the button. The app will call our API, render the requested image and draw the bounding boxes. To try the app, clone it first and install the required npm packages: git clone https://github.com/ylashin/detectron2-tutorialcd '.\3. client\'npm installnpm install -g browserifynpm install -g watchifywatchify index.js -o bundle.js Open index.html file in a text editor and update the URL of the API inside the function scoreImage to match the URL of your local or cloud hosted API. Then double click index.html file which will open the app in your default browser. Play with different image URLs, but just notice that some websites hosting images have a bit strict CORS policies so not all images will work fine. It’s not related to our web app or API but more about how the web works. The image used in the installation section of this post is tried above. We can see the bounding boxes, scores and labels on Messi and the ball. Developer console pane is shown with the JSON response of the API as well. The main part to consider in this web app is parsing and using the API response which is very simple and straightforward. All the remaining code is plumbing and HTML canvas rendering via an npm package. We barely scratched the surface of Detectron2, it has many more amazing features to explore. Also lots of shortcuts were made to make the post as concise as possible. Al in all, Detectron2 is a very welcome addition to any developer toolbox because of its features but more importantly ease of use. If you happen to create the container in Azure, please remember delete the resource group or stop the container once done experimenting otherwise it will keep burning your credit.
[ { "code": null, "e": 638, "s": 172, "text": "In 2018, Facebook AI developed an object detection library called Detectron. It was an amazing library but a bit hard to use. An earlier version of myself wrote a blog post on just how to install Detectron and run the sample demos, nothing more. Detectron was a bit hard to install and use and it was powered by Caffe2. Since 2018, there was lots of code changes bringing Caffe2 & PyTorch into a single repository and that adds to the difficulty of using Detectron." }, { "code": null, "e": 739, "s": 638, "text": "It seems there was some constructive feedback from the community and Facebook has come up with a v2." }, { "code": null, "e": 779, "s": 739, "text": "According to GitHub page of Detectron2:" }, { "code": null, "e": 910, "s": 779, "text": "Detectron2 is Facebook AI Research’s next generation software system that implements state-of-the-art object detection algorithms." }, { "code": null, "e": 1388, "s": 910, "text": "Detectron2 is built using PyTorch which has much more active community now to the extent of competing with TensorFlow itself. Also the setup instructions are much easier plus a very easy to use API to extract scoring results. Other frameworks like YOLO have very obscure format of their scoring results which are delivered as a plain multi dimensional array. Anyone worked with YOLO can imagine the effort needed to parse the scoring result and get it right in the first place." }, { "code": null, "e": 1617, "s": 1388, "text": "Enough history, in this post I will walk you through an end to end exercise on how to prepare a Detectron2 docker image hosting a web API for object detection and use it from a small web application acting as a service consumer." }, { "code": null, "e": 1876, "s": 1617, "text": "I will start first with installation. Unfortunately, Windows is not supported but I will bypass that using containers. To be quick, we wouldn’t mind installing a CPU version as the GPU one needs (guess what) a GPU, CUDA and all that lovely stuff from NVIDIA." }, { "code": null, "e": 1956, "s": 1876, "text": "So using your preferred text editor, create a Dockerfile with the this content." }, { "code": null, "e": 2390, "s": 1956, "text": "It starts first by picking base image which has a Python version ≥ 3.6 as requested by Detectron2 setup instruction. Next a few prerequisites are installed then a copy of same setup instructions on Detectron2 installation page. The version installed is a CPU version, it won’t be super fast but good enough for a tutorial. Last, Flask is included as this docker image will host a web API website to accept scoring calls from clients." }, { "code": null, "e": 2419, "s": 2390, "text": "Let’s build the image first." }, { "code": null, "e": 2468, "s": 2419, "text": "docker build --rm . -t ylashin/detectron2:latest" }, { "code": null, "e": 2571, "s": 2468, "text": "You can use any name/tag you want and adjust accordingly for the next steps. Next, let’s give it a go." }, { "code": null, "e": 2621, "s": 2571, "text": "docker run -it ylashin/detectron2:latest bin/bash" }, { "code": null, "e": 2809, "s": 2621, "text": "Hopefully all the above works fine and now we have a container up and running with Detectron2 installed. So we need to verify that nothing is broken and we have unicorns and and rainbows." }, { "code": null, "e": 2945, "s": 2809, "text": "The following test.py script has to be copied into the container using docker CLI or by using nano which is installed on the container." }, { "code": null, "e": 2974, "s": 2945, "text": "The main tasks involved are:" }, { "code": null, "e": 3190, "s": 2974, "text": "Printing Detectron2 version.Downloading an image for Lionel Messi and a soccer ball.Creating a predictor instance using one of the pre-trained architectures.Scoring the downloaded image using the predictor instance." }, { "code": null, "e": 3219, "s": 3190, "text": "Printing Detectron2 version." }, { "code": null, "e": 3276, "s": 3219, "text": "Downloading an image for Lionel Messi and a soccer ball." }, { "code": null, "e": 3350, "s": 3276, "text": "Creating a predictor instance using one of the pre-trained architectures." }, { "code": null, "e": 3409, "s": 3350, "text": "Scoring the downloaded image using the predictor instance." }, { "code": null, "e": 3476, "s": 3409, "text": "Next we will run that test script as shown in the next screenshot." }, { "code": null, "e": 3903, "s": 3476, "text": "Detectron2 seems to be at version 0.1.1 at the time of writing. Also, scoring is done correctly and the result is not a plain tensor like YOLO. It’s a typed class with easy to use members like bounding boxes and predicted classes. We will come to mapping class codes to human readable names later. What we have here is a couple bounding boxes and a couple high scores plus predicted classes of 0 (person) and 32 (sports ball)." }, { "code": null, "e": 4084, "s": 3903, "text": "P.S. Based on the problem you are solving, you need to pick the correct architecture and see if it was trained against similar dataset or else you might need to do custom training." }, { "code": null, "e": 4498, "s": 4084, "text": "The next step is to make this scoring functionality accessible from outside the container. A Flask web API needs to be hosted in that container to accept an image and return scoring result. For simplicity, the API will accept an image URL and do the download itself. It will not accept binary payload which would be the natural thing to do but it’s just easy to use the same test script with slight modifications." }, { "code": null, "e": 4643, "s": 4498, "text": "Also the response will be a dictionary serialized as a JSON object with enough information needed by the caller without any complicated parsing." }, { "code": null, "e": 4816, "s": 4643, "text": "Now as the container will host a Flask web server, it has to be started with web API port published . So exit the current container and start it again with port publishing." }, { "code": null, "e": 4879, "s": 4816, "text": "docker run -p 8181:5000 -it ylashin/detectron2:latest bin/bash" }, { "code": null, "e": 4924, "s": 4879, "text": "Flask port 5000 is mapped to host port 8181." }, { "code": null, "e": 5027, "s": 4924, "text": "Now, create a file inside the container namedweb_api.py and paste the following GitHub gist inside it." }, { "code": null, "e": 5107, "s": 5027, "text": "This is nearly the same test script used before with the following differences:" }, { "code": null, "e": 5195, "s": 5107, "text": "Some refactoring to have a global predictor instance ready to be used per each request." }, { "code": null, "e": 5318, "s": 5195, "text": "A function mapped to a web API endpoint is used to receive HTTP request with JSON object which has image URL to be scored." }, { "code": null, "e": 5415, "s": 5318, "text": "This function does the scoring and also some post-processing to prepare a final response object." }, { "code": null, "e": 5444, "s": 5415, "text": "To start the web server run:" }, { "code": null, "e": 5462, "s": 5444, "text": "python web_api.py" }, { "code": null, "e": 5757, "s": 5462, "text": "The URL shown has a port of 5000 but that’s because it’s just inside the container. Any tool like Postman, curl or PowerShell can be used to test the API works as expected. For whatever tool you use, please remember to include a request header with key content-type and value application/json ." }, { "code": null, "e": 5895, "s": 5757, "text": "If we scroll down the response in Postman, we will find the expected scoring fields such as bounding boxes, scores and class predictions." }, { "code": null, "e": 6173, "s": 5895, "text": "Now the web API server seems to be working fine, it’s better to be included as part of the definition of Dockerfile. That would allow us to push the built image to docker hub or any other registry and share it with others or use it without worrying about building it each time." }, { "code": null, "e": 6305, "s": 6173, "text": "The updated Dockerfile can be found in the repo linked to this post but for the sake of brevity, the delta added to Docker file is:" }, { "code": null, "e": 6384, "s": 6305, "text": "WORKDIR /appCOPY web_api.py web_api.pyENTRYPOINT [\"python\", \"/app/web_api.py\"]" }, { "code": null, "e": 6589, "s": 6384, "text": "Once the modified docker image is built, we can start the container once again but this time we don’t need to copy the web API file nor start it ourselves. Actually we can start the container as a daemon." }, { "code": null, "e": 6642, "s": 6589, "text": "docker run -p 8181:5000 -d ylashin/detectron2:latest" }, { "code": null, "e": 6811, "s": 6642, "text": "The web API could be tested using Postman again for verification but we need to give the container a few seconds to download weights file part of predictor preparation." }, { "code": null, "e": 6900, "s": 6811, "text": "Once we are happy with the running container, we can shut it down and publish the image." }, { "code": null, "e": 6938, "s": 6900, "text": "docker push ylashin/detectron2:latest" }, { "code": null, "e": 7317, "s": 6938, "text": "I published the image to my own Docker Hub account so that I can show you later how to use it with Azure container instances. The web app I will use to consume the scoring service will be hosted locally, so it can easily access a local running container. But I prefer to go to next level and host the container somewhere in the cloud to simulate a more realistic implementation." }, { "code": null, "e": 7643, "s": 7317, "text": "Phew, nearly there. Last stage is to consume that web API from any RESTful client. But first, I will start the container in Azure using Azure CLI and Azure container instances service. If you want to keep using the container locally, you can skip this Azure bit but adjust the web API URL in the web app that will come later." }, { "code": null, "e": 7999, "s": 7643, "text": "az group create --name detectron2 --location eastusaz container create --resource-group detectron2 --name predictor --image ylashin/detectron2:latest --cpu 2 --memory 4 --dns-name-label detectron2api --ports 5000az container show --resource-group detectron2 --name predictor --query \"{FQDN:ipAddress.fqdn,ProvisioningState:provisioningState}\" --out table" }, { "code": null, "e": 8216, "s": 7999, "text": "Last command above will show the FQDN of the container which we can use to test the cloud hosted API using Postman. Please note that the port used here is the plain Flask port without any mapping to a different port." }, { "code": null, "e": 8386, "s": 8216, "text": "We have a web API endpoint up and running in the cloud that can be consumed from any REST client anywhere. I have built a small JavaScript app. The app is pretty simple:" }, { "code": null, "e": 8418, "s": 8386, "text": "It has a text box and a button." }, { "code": null, "e": 8479, "s": 8418, "text": "Put a public image URL in the text box and click the button." }, { "code": null, "e": 8562, "s": 8479, "text": "The app will call our API, render the requested image and draw the bounding boxes." }, { "code": null, "e": 8632, "s": 8562, "text": "To try the app, clone it first and install the required npm packages:" }, { "code": null, "e": 8795, "s": 8632, "text": "git clone https://github.com/ylashin/detectron2-tutorialcd '.\\3. client\\'npm installnpm install -g browserifynpm install -g watchifywatchify index.js -o bundle.js" }, { "code": null, "e": 9250, "s": 8795, "text": "Open index.html file in a text editor and update the URL of the API inside the function scoreImage to match the URL of your local or cloud hosted API. Then double click index.html file which will open the app in your default browser. Play with different image URLs, but just notice that some websites hosting images have a bit strict CORS policies so not all images will work fine. It’s not related to our web app or API but more about how the web works." }, { "code": null, "e": 9469, "s": 9250, "text": "The image used in the installation section of this post is tried above. We can see the bounding boxes, scores and labels on Messi and the ball. Developer console pane is shown with the JSON response of the API as well." }, { "code": null, "e": 9591, "s": 9469, "text": "The main part to consider in this web app is parsing and using the API response which is very simple and straightforward." }, { "code": null, "e": 9672, "s": 9591, "text": "All the remaining code is plumbing and HTML canvas rendering via an npm package." }, { "code": null, "e": 9971, "s": 9672, "text": "We barely scratched the surface of Detectron2, it has many more amazing features to explore. Also lots of shortcuts were made to make the post as concise as possible. Al in all, Detectron2 is a very welcome addition to any developer toolbox because of its features but more importantly ease of use." } ]
Amazon Interview Experience for SDE-1 | 7 Months Experienced - GeeksforGeeks
22 Aug, 2021 Online Round: Question-related to the priority queueSimple Ad Hoc question Question-related to the priority queue Simple Ad Hoc question Round 1(Chime Interview): Taken by SDE 2 (1 hour, 15 mins) There are N bubbles in an array. A bubble with a positive value means it’s moving towards the right and has a mass of absolute value of A[i]. Similar to a negative value, it’s moving towards the left with a mass of absolute A[i]. On the collision of any two bubbles, the bubble with lesser mass vanishes. If the mass of colliding bubble is the same, both of them vanish.Given an array, print the resultant array after all the collision happens.Find an element in rotated sorted array.Theoretical questions from OS, OOPS, and Computer Networks.Why do you prefer C++, which is faster, C++ or Java? There are N bubbles in an array. A bubble with a positive value means it’s moving towards the right and has a mass of absolute value of A[i]. Similar to a negative value, it’s moving towards the left with a mass of absolute A[i]. On the collision of any two bubbles, the bubble with lesser mass vanishes. If the mass of colliding bubble is the same, both of them vanish.Given an array, print the resultant array after all the collision happens. Find an element in rotated sorted array. Theoretical questions from OS, OOPS, and Computer Networks. Why do you prefer C++, which is faster, C++ or Java? Round 2(Chime Interview): Taken by SDE 2 (1 hour) Given a string as an input perform Q queries of the following type:1 1 char – Insert char at the front of the string1 2 char – Insert char at the end of the string2 – Reverse the stringHad to print the final string after Q queries.https://practice.geeksforgeeks.org/problems/next-permutation5226/1Discussion about my past projects Given a string as an input perform Q queries of the following type:1 1 char – Insert char at the front of the string1 2 char – Insert char at the end of the string2 – Reverse the stringHad to print the final string after Q queries. https://practice.geeksforgeeks.org/problems/next-permutation5226/1 Discussion about my past projects Round 3(Chime Interview): Taken by Software Manager (1 hour) https://practice.geeksforgeeks.org/problems/generate-all-possible-parentheses/1https://practice.geeksforgeeks.org/problems/length-of-the-longest-substring3036/1Why Amazon, Why leaving current organization in 6 months, What do you bring to the table?Discussion about my projects. https://practice.geeksforgeeks.org/problems/generate-all-possible-parentheses/1 https://practice.geeksforgeeks.org/problems/length-of-the-longest-substring3036/1 Why Amazon, Why leaving current organization in 6 months, What do you bring to the table? Discussion about my projects. Round 4(Chime Interview): Taken by Software Manager (45 mins) Discussion about my projects.Leadership/Behavioral questions.Given N queries of type :C – Create a folder with the smallest missing positive integer starting from 1.D X – Delete a folder having name XExample: Input Output C 1 C 2 C 3 C 4 C 5 D 2 D 4 C 2 C 4 C 6 Discussion about my projects. Leadership/Behavioral questions. Given N queries of type :C – Create a folder with the smallest missing positive integer starting from 1.D X – Delete a folder having name XExample: Input Output C 1 C 2 C 3 C 4 C 5 D 2 D 4 C 2 C 4 C 6 C – Create a folder with the smallest missing positive integer starting from 1. D X – Delete a folder having name X Example: Input Output C 1 C 2 C 3 C 4 C 5 D 2 D 4 C 2 C 4 C 6 While answering any coding question, firstly you need to tell your approach. Support your approach with some test cases so that it’ll be easy to convey.Secondly, they want to code for all questions. Make your code is free from all the bugs, and you have covered all the corner cases. Try to convey what you are writing, why particular Data Structure etc while you write your code. If time permits, dry run your code in your head first then explain it to them.If stuck, don’t be nervous, they will provide you with hints. Verdict: Selected Amazon Marketing Experienced Interview Experiences Amazon Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Amazon Interview Experience for SDE1 (8 Months Experienced) 2022 Infosys Interview Experience for Java Backend Developer (3-5 Years Experienced) Paypal Interview Experience for SSE Amazon Interview Experience for System Development Engineer (Exp - 6 months) Goldman Sachs Interview Experience for Java Developer (3+ Years Experienced) Amazon Interview Questions Microsoft Interview Experience for Internship (Via Engage) Commonly Asked Java Programming Interview Questions | Set 2 Amazon Interview Experience for SDE-1 (On-Campus) Infosys Interview Experience for DSE - System Engineer | On-Campus 2022
[ { "code": null, "e": 25429, "s": 25401, "text": "\n22 Aug, 2021" }, { "code": null, "e": 25443, "s": 25429, "text": "Online Round:" }, { "code": null, "e": 25504, "s": 25443, "text": "Question-related to the priority queueSimple Ad Hoc question" }, { "code": null, "e": 25543, "s": 25504, "text": "Question-related to the priority queue" }, { "code": null, "e": 25566, "s": 25543, "text": "Simple Ad Hoc question" }, { "code": null, "e": 25625, "s": 25566, "text": "Round 1(Chime Interview): Taken by SDE 2 (1 hour, 15 mins)" }, { "code": null, "e": 26221, "s": 25625, "text": "There are N bubbles in an array. A bubble with a positive value means it’s moving towards the right and has a mass of absolute value of A[i]. Similar to a negative value, it’s moving towards the left with a mass of absolute A[i]. On the collision of any two bubbles, the bubble with lesser mass vanishes. If the mass of colliding bubble is the same, both of them vanish.Given an array, print the resultant array after all the collision happens.Find an element in rotated sorted array.Theoretical questions from OS, OOPS, and Computer Networks.Why do you prefer C++, which is faster, C++ or Java?" }, { "code": null, "e": 26666, "s": 26221, "text": "There are N bubbles in an array. A bubble with a positive value means it’s moving towards the right and has a mass of absolute value of A[i]. Similar to a negative value, it’s moving towards the left with a mass of absolute A[i]. On the collision of any two bubbles, the bubble with lesser mass vanishes. If the mass of colliding bubble is the same, both of them vanish.Given an array, print the resultant array after all the collision happens." }, { "code": null, "e": 26707, "s": 26666, "text": "Find an element in rotated sorted array." }, { "code": null, "e": 26767, "s": 26707, "text": "Theoretical questions from OS, OOPS, and Computer Networks." }, { "code": null, "e": 26820, "s": 26767, "text": "Why do you prefer C++, which is faster, C++ or Java?" }, { "code": null, "e": 26870, "s": 26820, "text": "Round 2(Chime Interview): Taken by SDE 2 (1 hour)" }, { "code": null, "e": 27201, "s": 26870, "text": "Given a string as an input perform Q queries of the following type:1 1 char – Insert char at the front of the string1 2 char – Insert char at the end of the string2 – Reverse the stringHad to print the final string after Q queries.https://practice.geeksforgeeks.org/problems/next-permutation5226/1Discussion about my past projects" }, { "code": null, "e": 27433, "s": 27201, "text": "Given a string as an input perform Q queries of the following type:1 1 char – Insert char at the front of the string1 2 char – Insert char at the end of the string2 – Reverse the stringHad to print the final string after Q queries." }, { "code": null, "e": 27500, "s": 27433, "text": "https://practice.geeksforgeeks.org/problems/next-permutation5226/1" }, { "code": null, "e": 27534, "s": 27500, "text": "Discussion about my past projects" }, { "code": null, "e": 27595, "s": 27534, "text": "Round 3(Chime Interview): Taken by Software Manager (1 hour)" }, { "code": null, "e": 27874, "s": 27595, "text": "https://practice.geeksforgeeks.org/problems/generate-all-possible-parentheses/1https://practice.geeksforgeeks.org/problems/length-of-the-longest-substring3036/1Why Amazon, Why leaving current organization in 6 months, What do you bring to the table?Discussion about my projects." }, { "code": null, "e": 27954, "s": 27874, "text": "https://practice.geeksforgeeks.org/problems/generate-all-possible-parentheses/1" }, { "code": null, "e": 28036, "s": 27954, "text": "https://practice.geeksforgeeks.org/problems/length-of-the-longest-substring3036/1" }, { "code": null, "e": 28126, "s": 28036, "text": "Why Amazon, Why leaving current organization in 6 months, What do you bring to the table?" }, { "code": null, "e": 28156, "s": 28126, "text": "Discussion about my projects." }, { "code": null, "e": 28218, "s": 28156, "text": "Round 4(Chime Interview): Taken by Software Manager (45 mins)" }, { "code": null, "e": 28713, "s": 28218, "text": "Discussion about my projects.Leadership/Behavioral questions.Given N queries of type :C – Create a folder with the smallest missing positive integer starting from 1.D X – Delete a folder having name XExample: \nInput Output\nC 1\nC 2\nC 3\nC 4\nC 5\nD 2 \nD 4\nC 2\nC 4\nC 6" }, { "code": null, "e": 28743, "s": 28713, "text": "Discussion about my projects." }, { "code": null, "e": 28776, "s": 28743, "text": "Leadership/Behavioral questions." }, { "code": null, "e": 29210, "s": 28776, "text": "Given N queries of type :C – Create a folder with the smallest missing positive integer starting from 1.D X – Delete a folder having name XExample: \nInput Output\nC 1\nC 2\nC 3\nC 4\nC 5\nD 2 \nD 4\nC 2\nC 4\nC 6" }, { "code": null, "e": 29290, "s": 29210, "text": "C – Create a folder with the smallest missing positive integer starting from 1." }, { "code": null, "e": 29326, "s": 29290, "text": "D X – Delete a folder having name X" }, { "code": null, "e": 29621, "s": 29326, "text": "Example: \nInput Output\nC 1\nC 2\nC 3\nC 4\nC 5\nD 2 \nD 4\nC 2\nC 4\nC 6" }, { "code": null, "e": 30142, "s": 29621, "text": "While answering any coding question, firstly you need to tell your approach. Support your approach with some test cases so that it’ll be easy to convey.Secondly, they want to code for all questions. Make your code is free from all the bugs, and you have covered all the corner cases. Try to convey what you are writing, why particular Data Structure etc while you write your code. If time permits, dry run your code in your head first then explain it to them.If stuck, don’t be nervous, they will provide you with hints." }, { "code": null, "e": 30162, "s": 30142, "text": "Verdict: Selected " }, { "code": null, "e": 30169, "s": 30162, "text": "Amazon" }, { "code": null, "e": 30179, "s": 30169, "text": "Marketing" }, { "code": null, "e": 30191, "s": 30179, "text": "Experienced" }, { "code": null, "e": 30213, "s": 30191, "text": "Interview Experiences" }, { "code": null, "e": 30220, "s": 30213, "text": "Amazon" }, { "code": null, "e": 30318, "s": 30220, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30327, "s": 30318, "text": "Comments" }, { "code": null, "e": 30340, "s": 30327, "text": "Old Comments" }, { "code": null, "e": 30405, "s": 30340, "text": "Amazon Interview Experience for SDE1 (8 Months Experienced) 2022" }, { "code": null, "e": 30485, "s": 30405, "text": "Infosys Interview Experience for Java Backend Developer (3-5 Years Experienced)" }, { "code": null, "e": 30521, "s": 30485, "text": "Paypal Interview Experience for SSE" }, { "code": null, "e": 30598, "s": 30521, "text": "Amazon Interview Experience for System Development Engineer (Exp - 6 months)" }, { "code": null, "e": 30675, "s": 30598, "text": "Goldman Sachs Interview Experience for Java Developer (3+ Years Experienced)" }, { "code": null, "e": 30702, "s": 30675, "text": "Amazon Interview Questions" }, { "code": null, "e": 30761, "s": 30702, "text": "Microsoft Interview Experience for Internship (Via Engage)" }, { "code": null, "e": 30821, "s": 30761, "text": "Commonly Asked Java Programming Interview Questions | Set 2" }, { "code": null, "e": 30871, "s": 30821, "text": "Amazon Interview Experience for SDE-1 (On-Campus)" } ]
Benchmarking and Profiling
In this chapter, we will learn how benchmarking and profiling help in addressing performance issues. Suppose we had written a code and it is giving the desired result too but what if we want to run this code a bit faster because the needs have changed. In this case, we need to find out what parts of our code are slowing down the entire program. In this case, benchmarking and profiling can be useful. Benchmarking aims at evaluating something by comparison with a standard. However, the question that arises here is that what would be the benchmarking and why we need it in case of software programming. Benchmarking the code means how fast the code is executing and where the bottleneck is. One major reason for benchmarking is that it optimizes the code. If we talk about the working of benchmarking, we need to start by benchmarking the whole program as one current state then we can combine micro benchmarks and then decompose a program into smaller programs. In order to find the bottlenecks within our program and optimize it. In other words, we can understand it as breaking the big and hard problem into series of smaller and a bit easier problems for optimizing them. In Python, we have a by default module for benchmarking which is called timeit. With the help of the timeit module, we can measure the performance of small bit of Python code within our main program. In the following Python script, we are importing the timeit module, which further measures the time taken to execute two functions – functionA and functionB − import timeit import time def functionA(): print("Function A starts the execution:") print("Function A completes the execution:") def functionB(): print("Function B starts the execution") print("Function B completes the execution") start_time = timeit.default_timer() functionA() print(timeit.default_timer() - start_time) start_time = timeit.default_timer() functionB() print(timeit.default_timer() - start_time) After running the above script, we will get the execution time of both the functions as shown below. Function A starts the execution: Function A completes the execution: 0.0014599495514175942 Function B starts the execution Function B completes the execution 0.0017024724827479076 In Python, we can create our own timer, which will act just like the timeit module. It can be done with the help of the decorator function. Following is an example of the custom timer − import random import time def timer_func(func): def function_timer(*args, **kwargs): start = time.time() value = func(*args, **kwargs) end = time.time() runtime = end - start msg = "{func} took {time} seconds to complete its execution." print(msg.format(func = func.__name__,time = runtime)) return value return function_timer @timer_func def Myfunction(): for x in range(5): sleep_time = random.choice(range(1,3)) time.sleep(sleep_time) if __name__ == '__main__': Myfunction() The above python script helps in importing random time modules. We have created the timer_func() decorator function. This has the function_timer() function inside it. Now, the nested function will grab the time before calling the passed in function. Then it waits for the function to return and grabs the end time. In this way, we can finally make python script print the execution time. The script will generate the output as shown below. Myfunction took 8.000457763671875 seconds to complete its execution. Sometimes the programmer wants to measure some attributes like the use of memory, time complexity or usage of particular instructions about the programs to measure the real capability of that program. Such kind of measuring about program is called profiling. Profiling uses dynamic program analysis to do such measuring. In the subsequent sections, we will learn about the different Python Modules for Profiling. cProfile is a Python built-in module for profiling. The module is a C-extension with reasonable overhead that makes it suitable for profiling long-running programs. After running it, it logs all the functions and execution times. It is very powerful but sometimes a bit difficult to interpret and act on. In the following example, we are using cProfile on the code below − def increment_global(): global x x += 1 def taskofThread(lock): for _ in range(50000): lock.acquire() increment_global() lock.release() def main(): global x x = 0 lock = threading.Lock() t1 = threading.Thread(target=taskofThread, args=(lock,)) t2 = threading.Thread(target= taskofThread, args=(lock,)) t1.start() t2.start() t1.join() t2.join() if __name__ == "__main__": for i in range(5): main() print("x = {1} after Iteration {0}".format(i,x)) The above code is saved in the thread_increment.py file. Now, execute the code with cProfile on the command line as follows − (base) D:\ProgramData>python -m cProfile thread_increment.py x = 100000 after Iteration 0 x = 100000 after Iteration 1 x = 100000 after Iteration 2 x = 100000 after Iteration 3 x = 100000 after Iteration 4 3577 function calls (3522 primitive calls) in 1.688 seconds Ordered by: standard name ncalls tottime percall cumtime percall filename:lineno(function) 5 0.000 0.000 0.000 0.000 <frozen importlib._bootstrap>:103(release) 5 0.000 0.000 0.000 0.000 <frozen importlib._bootstrap>:143(__init__) 5 0.000 0.000 0.000 0.000 <frozen importlib._bootstrap>:147(__enter__) ... ... ... ... From the above output, it is clear that cProfile prints out all the 3577 functions called, with the time spent in each and the number of times they have been called. Followings are the columns we got in output − ncalls − It is the number of calls made. ncalls − It is the number of calls made. tottime − It is the total time spent in the given function. tottime − It is the total time spent in the given function. percall − It refers to the quotient of tottime divided by ncalls. percall − It refers to the quotient of tottime divided by ncalls. cumtime − It is the cumulative time spent in this and all subfunctions. It is even accurate for recursive functions. cumtime − It is the cumulative time spent in this and all subfunctions. It is even accurate for recursive functions. percall − It is the quotient of cumtime divided by primitive calls. percall − It is the quotient of cumtime divided by primitive calls. filename:lineno(function) − It basically provides the respective data of each function. filename:lineno(function) − It basically provides the respective data of each function. 57 Lectures 8 hours Denis Tishkov Print Add Notes Bookmark this page
[ { "code": null, "e": 2023, "s": 1922, "text": "In this chapter, we will learn how benchmarking and profiling help in addressing performance issues." }, { "code": null, "e": 2325, "s": 2023, "text": "Suppose we had written a code and it is giving the desired result too but what if we want to run this code a bit faster because the needs have changed. In this case, we need to find out what parts of our code are slowing down the entire program. In this case, benchmarking and profiling can be useful." }, { "code": null, "e": 2681, "s": 2325, "text": "Benchmarking aims at evaluating something by comparison with a standard. However, the question that arises here is that what would be the benchmarking and why we need it in case of software programming. Benchmarking the code means how fast the code is executing and where the bottleneck is. One major reason for benchmarking is that it optimizes the code." }, { "code": null, "e": 3101, "s": 2681, "text": "If we talk about the working of benchmarking, we need to start by benchmarking the whole program as one current state then we can combine micro benchmarks and then decompose a program into smaller programs. In order to find the bottlenecks within our program and optimize it. In other words, we can understand it as breaking the big and hard problem into series of smaller and a bit easier problems for optimizing them." }, { "code": null, "e": 3301, "s": 3101, "text": "In Python, we have a by default module for benchmarking which is called timeit. With the help of the timeit module, we can measure the performance of small bit of Python code within our main program." }, { "code": null, "e": 3460, "s": 3301, "text": "In the following Python script, we are importing the timeit module, which further measures the time taken to execute two functions – functionA and functionB −" }, { "code": null, "e": 3886, "s": 3460, "text": "import timeit\nimport time\ndef functionA():\n print(\"Function A starts the execution:\")\n print(\"Function A completes the execution:\")\ndef functionB():\n print(\"Function B starts the execution\")\n print(\"Function B completes the execution\")\nstart_time = timeit.default_timer()\nfunctionA()\nprint(timeit.default_timer() - start_time)\nstart_time = timeit.default_timer()\nfunctionB()\nprint(timeit.default_timer() - start_time)" }, { "code": null, "e": 3987, "s": 3886, "text": "After running the above script, we will get the execution time of both the functions as shown below." }, { "code": null, "e": 4168, "s": 3987, "text": "Function A starts the execution:\nFunction A completes the execution:\n0.0014599495514175942\nFunction B starts the execution\nFunction B completes the execution\n0.0017024724827479076\n" }, { "code": null, "e": 4354, "s": 4168, "text": "In Python, we can create our own timer, which will act just like the timeit module. It can be done with the help of the decorator function. Following is an example of the custom timer −" }, { "code": null, "e": 4878, "s": 4354, "text": "import random\nimport time\n\ndef timer_func(func):\n\n def function_timer(*args, **kwargs):\n start = time.time()\n value = func(*args, **kwargs)\n end = time.time()\n runtime = end - start\n msg = \"{func} took {time} seconds to complete its execution.\"\n print(msg.format(func = func.__name__,time = runtime))\n return value\n return function_timer\n\n@timer_func\ndef Myfunction():\n for x in range(5):\n sleep_time = random.choice(range(1,3))\n time.sleep(sleep_time)\n\nif __name__ == '__main__':\n Myfunction()" }, { "code": null, "e": 5318, "s": 4878, "text": "The above python script helps in importing random time modules. We have created the timer_func() decorator function. This has the function_timer() function inside it. Now, the nested function will grab the time before calling the passed in function. Then it waits for the function to return and grabs the end time. In this way, we can finally make python script print the execution time. The script will generate the output as shown below." }, { "code": null, "e": 5388, "s": 5318, "text": "Myfunction took 8.000457763671875 seconds to complete its execution.\n" }, { "code": null, "e": 5709, "s": 5388, "text": "Sometimes the programmer wants to measure some attributes like the use of memory, time complexity or usage of particular instructions about the programs to measure the real capability of that program. Such kind of measuring about program is called profiling. Profiling uses dynamic program analysis to do such measuring." }, { "code": null, "e": 5801, "s": 5709, "text": "In the subsequent sections, we will learn about the different Python Modules for Profiling." }, { "code": null, "e": 6174, "s": 5801, "text": "cProfile is a Python built-in module for profiling. The module is a C-extension with reasonable overhead that makes it suitable for profiling long-running programs. After running it, it logs all the functions and execution times. It is very powerful but sometimes a bit difficult to interpret and act on. In the following example, we are using cProfile on the code below −" }, { "code": null, "e": 6686, "s": 6174, "text": "def increment_global():\n\n global x\n x += 1\n\ndef taskofThread(lock):\n\n for _ in range(50000):\n lock.acquire()\n increment_global()\n lock.release()\n\ndef main():\n global x\n x = 0\n\n lock = threading.Lock()\n\n t1 = threading.Thread(target=taskofThread, args=(lock,))\n t2 = threading.Thread(target= taskofThread, args=(lock,))\n\n t1.start()\n t2.start()\n\n t1.join()\n t2.join()\n\nif __name__ == \"__main__\":\n for i in range(5):\n main()\n print(\"x = {1} after Iteration {0}\".format(i,x))" }, { "code": null, "e": 6812, "s": 6686, "text": "The above code is saved in the thread_increment.py file. Now, execute the code with cProfile on the command line as follows −" }, { "code": null, "e": 7422, "s": 6812, "text": "(base) D:\\ProgramData>python -m cProfile thread_increment.py\nx = 100000 after Iteration 0\nx = 100000 after Iteration 1\nx = 100000 after Iteration 2\nx = 100000 after Iteration 3\nx = 100000 after Iteration 4\n 3577 function calls (3522 primitive calls) in 1.688 seconds\n\n Ordered by: standard name\n\n ncalls tottime percall cumtime percall filename:lineno(function)\n\n 5 0.000 0.000 0.000 0.000 <frozen importlib._bootstrap>:103(release)\n 5 0.000 0.000 0.000 0.000 <frozen importlib._bootstrap>:143(__init__)\n 5 0.000 0.000 0.000 0.000 <frozen importlib._bootstrap>:147(__enter__)\n ... ... ... ..." }, { "code": null, "e": 7634, "s": 7422, "text": "From the above output, it is clear that cProfile prints out all the 3577 functions called, with the time spent in each and the number of times they have been called. Followings are the columns we got in output −" }, { "code": null, "e": 7675, "s": 7634, "text": "ncalls − It is the number of calls made." }, { "code": null, "e": 7716, "s": 7675, "text": "ncalls − It is the number of calls made." }, { "code": null, "e": 7776, "s": 7716, "text": "tottime − It is the total time spent in the given function." }, { "code": null, "e": 7836, "s": 7776, "text": "tottime − It is the total time spent in the given function." }, { "code": null, "e": 7902, "s": 7836, "text": "percall − It refers to the quotient of tottime divided by ncalls." }, { "code": null, "e": 7968, "s": 7902, "text": "percall − It refers to the quotient of tottime divided by ncalls." }, { "code": null, "e": 8085, "s": 7968, "text": "cumtime − It is the cumulative time spent in this and all subfunctions. It is even accurate for recursive functions." }, { "code": null, "e": 8202, "s": 8085, "text": "cumtime − It is the cumulative time spent in this and all subfunctions. It is even accurate for recursive functions." }, { "code": null, "e": 8270, "s": 8202, "text": "percall − It is the quotient of cumtime divided by primitive calls." }, { "code": null, "e": 8338, "s": 8270, "text": "percall − It is the quotient of cumtime divided by primitive calls." }, { "code": null, "e": 8426, "s": 8338, "text": "filename:lineno(function) − It basically provides the respective data of each function." }, { "code": null, "e": 8514, "s": 8426, "text": "filename:lineno(function) − It basically provides the respective data of each function." }, { "code": null, "e": 8547, "s": 8514, "text": "\n 57 Lectures \n 8 hours \n" }, { "code": null, "e": 8562, "s": 8547, "text": " Denis Tishkov" }, { "code": null, "e": 8569, "s": 8562, "text": " Print" }, { "code": null, "e": 8580, "s": 8569, "text": " Add Notes" } ]
Video Facial Expression and Awareness Detection with Fast.ai and OpenCV | by Joyce Zheng | Towards Data Science
The inspiration behind this? The FBI agent watching me through my webcam, but replaced by deep learning :) The goal of this tutorial? Train a facial expression classification model with the fast.ai library, read facial expressions from your webcam or a video file, and finally, add in facial landmarking to track your eyes to determine awareness! (TL;DR the fully working code is here https://github.com/jy6zheng/FacialExpressionRecognition) The main reason why I wrote this tutorial is that when working on this project, a big challenge was figuring out how to take my trained classifier and make it work on both live videos and video files efficiently. The additional eye landmarking feature was based off this tutorial that I found extremely useful: https://www.pyimagesearch.com/2017/05/08/drowsiness-detection-opencv/ The first step is to train an image classification model with a convolutional neural network. The data I used was from https://www.kaggle.com/jonathanoheix/face-expression-recognition-dataset I used the fast.ai library, built on top of PyTorch to train my classification model. The model was trained with resnet34 pre-trained weights and the training dataset and exported as a .pkl file. For step-by-step instructions, check out the google colab notebook in my repository, which contains all the code to train your model: https://github.com/jy6zheng/FacialExpressionRecognition The greatest challenge was first finding a public dataset and then cleaning the data. Initially, when I used the Kaggle dataset, I was only able to train up to an error rate of 0.328191, which meant it was only correct around 68% of the time (not that great at all). When I plotted images that produced the top losses, I quickly realized that a large amount of the data was incorrectly labeled (the left is the predicted expression by the model, the right is the labeled emotion). After cleaning the data, the error rate decreased by over 16%. Now the classifier has around 84% accuracy meaning it correctly identified 84% of the face images. There are still some incorrect and dirty data, and therefore room for more improvement. Now, it is time to take our classifier and use it on live video streams. First, it is preferable to create a virtual environment so that this project has its own dependencies and does not interfere with any other project. Then, download the required packages and libraries. Create a file called liveVideoFrame.py (or whatever you want to name it) and import the following: from scipy.spatial import distance as distimport numpy as npimport cv2from imutils import face_utilsfrom imutils.video import VideoStreamfrom fastai.vision import *import imutilsimport argparseimport timeimport dlib I wanted the option to save the predictions in a .csv file and save the marked-up video, so I added argument parsing. I also exported the trained classification model and moved it to my working directory. ap = argparse.ArgumentParser()ap.add_argument("--save", dest="save", action = "store_true")ap.add_argument("--no-save", dest="save", action = "store_false")ap.set_defaults(save = False)ap.add_argument("--savedata", dest="savedata", action = "store_true")ap.add_argument("--no-savedata", dest="savedata", action = "store_false")ap.set_defaults(savedata = False)args = vars(ap.parse_args())path = '/Users/joycezheng/FacialRecognitionVideo/' #change this depending on the path of your exported modellearn = load_learner(path, 'export.pkl') Great! Now it is time to start our video stream. I used VideoStream from imutils.video since I found it works faster than cv2.VideoCapture. Note: the source for the video stream is 0 for the built-in webcam, it will be different if you are using a different camera such as a plugin. A haar cascade classifier is used to identify frontal faces in the video frame. We have an array named data to store our predictions. The timer and time_value are used to label the time of each prediction in our data so that the predictions increment by 1s in the.csv file. face_cascade = cv2.CascadeClassifier("haarcascade_frontalface_default.xml") vs = VideoStream(src=0).start()start = time.perf_counter() data = []time_value = 0if args["save"]: out = cv2.VideoWriter(path + "liveoutput.avi", cv2.VideoWriter_fourcc('M','J','P','G'), 10, (450,253)) Now, we will implement a while loop that reads each frame from the video stream: Each Frame is converted to grayscale since the image classifier was trained on grayscale imagesThe cascade classifier is used to find faces in the frame. I set the minneighbors parameter to 5 since I found it worked best on live videos. For recorded video files, I set it to a higher value since a face is guaranteed to be in each frameThe grayscale image is then cropped for the faces with a buffer of 0.3 since our classifier was trained on close-up faces without much backgroundText and bounding boxes are then drawn onto each frame and shownEach frame is then saved to the video writer using out.write(frame) Each Frame is converted to grayscale since the image classifier was trained on grayscale images The cascade classifier is used to find faces in the frame. I set the minneighbors parameter to 5 since I found it worked best on live videos. For recorded video files, I set it to a higher value since a face is guaranteed to be in each frame The grayscale image is then cropped for the faces with a buffer of 0.3 since our classifier was trained on close-up faces without much background Text and bounding boxes are then drawn onto each frame and shown Each frame is then saved to the video writer using out.write(frame) while True: frame = vs.read() frame = imutils.resize(frame, width=450) gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) face_coord = face_cascade.detectMultiScale(gray, 1.1, 5, minSize=(30, 30)) for coords in face_coord: X, Y, w, h = coords H, W, _ = frame.shape X_1, X_2 = (max(0, X - int(w * 0.3)), min(X + int(1.3 * w), W)) Y_1, Y_2 = (max(0, Y - int(0.3 * h)), min(Y + int(1.3 * h), H)) img_cp = gray[Y_1:Y_2, X_1:X_2].copy() prediction, idx, probability = learn.predict(Image(pil2tensor(img_cp, np.float32).div_(225))) cv2.rectangle( img=frame, pt1=(X_1, Y_1), pt2=(X_2, Y_2), color=(128, 128, 0), thickness=2, ) cv2.putText(frame, str(prediction), (10, frame.shape[0] - 25), cv2.FONT_HERSHEY_SIMPLEX, 0.7, (225, 255, 255), 2) cv2.imshow("frame", frame) if args["save"]: out.write(frame) if cv2.waitKey(1) & 0xFF == ord("q"): breakvs.stop()if args["save"]: print("done saving video") out.release()cv2.destroyAllWindows() Now we have our fast.ai learning model working with imutils and OpenCV to predict faces from live videos! Next, it is time to determine the awareness of the face. The function eye_aspect_ratio calculates the eye aspect ratio from the coordinates of the eye. The position and coordinates of each eye are found from the dlib pre-trained facial landmark detector. The function data_time is used to append predictions in the data array every 1-second interval. EYE_AR_THRESH = 0.20EYE_AR_CONSEC_FRAMES = 10COUNTER = 0def eye_aspect_ratio(eye): A = dist.euclidean(eye[1], eye[5]) B = dist.euclidean(eye[2], eye[4]) C = dist.euclidean(eye[0], eye[3]) ear = (A + B) / (2.0 * C) return eardef data_time(time_value, prediction, probability, ear): current_time = int(time.perf_counter()-start) if current_time != time_value: data.append([current_time, prediction, probability, ear]) time_value = current_time return time_valuepredictor = dlib.shape_predictor("shape_predictor_68_face_landmarks.dat")(lStart, lEnd) = face_utils.FACIAL_LANDMARKS_IDXS["left_eye"](rStart, rEnd) = face_utils.FACIAL_LANDMARKS_IDXS["right_eye"] Within the for loop which loops over the face coordinates, add the following block of code. The eye is detected using the dlib face landmark detector and drawn onto the frame. When the average calculated eye aspect ratio between the two eyes is less than the threshold for more than ten consecutive frames (which you can modify to your own liking), then the face is marked as distracted. rect = dlib.rectangle(X, Y, X+w, Y+h) shape = predictor(gray, rect) shape = face_utils.shape_to_np(shape) leftEye = shape[lStart:lEnd] rightEye = shape[rStart:rEnd] leftEAR = eye_aspect_ratio(leftEye) rightEAR = eye_aspect_ratio(rightEye) ear = (leftEAR + rightEAR) / 2.0 leftEyeHull = cv2.convexHull(leftEye) rightEyeHull = cv2.convexHull(rightEye) cv2.drawContours(frame, [leftEyeHull], -1, (0, 255, 0), 1) cv2.drawContours(frame, [rightEyeHull], -1, (0, 255, 0), 1) if ear < EYE_AR_THRESH: COUNTER += 1 if COUNTER >= EYE_AR_CONSEC_FRAMES: cv2.putText(frame, "Distracted", (10, 30), cv2.FONT_HERSHEY_SIMPLEX, 0.7, (0, 0, 255), 2) else: COUNTER = 0 cv2.putText(frame, "Eye Ratio: {:.2f}".format(ear), (250, 30), cv2.FONT_HERSHEY_SIMPLEX, 0.7, (0, 0, 255), 2) time_value = data_time(time_value, prediction, probability, ear) Finally, at the bottom of our code, we can save the data as a data frame and then a .csv file. if args["savedata"]: df = pd.DataFrame(data, columns = ['Time (seconds)', 'Expression', 'Probability', 'EAR']) df.to_csv(path+'/exportlive.csv') print("data saved to exportlive.csv") You can test the code in the command-line by running: python liveVideoFrameRead.py --save --savedata The full code is here: I used a very similar approach to video files compared to live videos. The main difference is that predictions occur every number of frames, which can be modified using the command-line argument — frame-step. The full code is below: And that’s it! You now are able to predict facial expressions from both video files and live webcams. Thank you for reading this :), and let me know if there are any improvements or questions. The fully working code is here: https://github.com/jy6zheng/FacialExpressionRecognition
[ { "code": null, "e": 279, "s": 172, "text": "The inspiration behind this? The FBI agent watching me through my webcam, but replaced by deep learning :)" }, { "code": null, "e": 614, "s": 279, "text": "The goal of this tutorial? Train a facial expression classification model with the fast.ai library, read facial expressions from your webcam or a video file, and finally, add in facial landmarking to track your eyes to determine awareness! (TL;DR the fully working code is here https://github.com/jy6zheng/FacialExpressionRecognition)" }, { "code": null, "e": 995, "s": 614, "text": "The main reason why I wrote this tutorial is that when working on this project, a big challenge was figuring out how to take my trained classifier and make it work on both live videos and video files efficiently. The additional eye landmarking feature was based off this tutorial that I found extremely useful: https://www.pyimagesearch.com/2017/05/08/drowsiness-detection-opencv/" }, { "code": null, "e": 1187, "s": 995, "text": "The first step is to train an image classification model with a convolutional neural network. The data I used was from https://www.kaggle.com/jonathanoheix/face-expression-recognition-dataset" }, { "code": null, "e": 1573, "s": 1187, "text": "I used the fast.ai library, built on top of PyTorch to train my classification model. The model was trained with resnet34 pre-trained weights and the training dataset and exported as a .pkl file. For step-by-step instructions, check out the google colab notebook in my repository, which contains all the code to train your model: https://github.com/jy6zheng/FacialExpressionRecognition" }, { "code": null, "e": 2054, "s": 1573, "text": "The greatest challenge was first finding a public dataset and then cleaning the data. Initially, when I used the Kaggle dataset, I was only able to train up to an error rate of 0.328191, which meant it was only correct around 68% of the time (not that great at all). When I plotted images that produced the top losses, I quickly realized that a large amount of the data was incorrectly labeled (the left is the predicted expression by the model, the right is the labeled emotion)." }, { "code": null, "e": 2304, "s": 2054, "text": "After cleaning the data, the error rate decreased by over 16%. Now the classifier has around 84% accuracy meaning it correctly identified 84% of the face images. There are still some incorrect and dirty data, and therefore room for more improvement." }, { "code": null, "e": 2677, "s": 2304, "text": "Now, it is time to take our classifier and use it on live video streams. First, it is preferable to create a virtual environment so that this project has its own dependencies and does not interfere with any other project. Then, download the required packages and libraries. Create a file called liveVideoFrame.py (or whatever you want to name it) and import the following:" }, { "code": null, "e": 2893, "s": 2677, "text": "from scipy.spatial import distance as distimport numpy as npimport cv2from imutils import face_utilsfrom imutils.video import VideoStreamfrom fastai.vision import *import imutilsimport argparseimport timeimport dlib" }, { "code": null, "e": 3098, "s": 2893, "text": "I wanted the option to save the predictions in a .csv file and save the marked-up video, so I added argument parsing. I also exported the trained classification model and moved it to my working directory." }, { "code": null, "e": 3635, "s": 3098, "text": "ap = argparse.ArgumentParser()ap.add_argument(\"--save\", dest=\"save\", action = \"store_true\")ap.add_argument(\"--no-save\", dest=\"save\", action = \"store_false\")ap.set_defaults(save = False)ap.add_argument(\"--savedata\", dest=\"savedata\", action = \"store_true\")ap.add_argument(\"--no-savedata\", dest=\"savedata\", action = \"store_false\")ap.set_defaults(savedata = False)args = vars(ap.parse_args())path = '/Users/joycezheng/FacialRecognitionVideo/' #change this depending on the path of your exported modellearn = load_learner(path, 'export.pkl')" }, { "code": null, "e": 3918, "s": 3635, "text": "Great! Now it is time to start our video stream. I used VideoStream from imutils.video since I found it works faster than cv2.VideoCapture. Note: the source for the video stream is 0 for the built-in webcam, it will be different if you are using a different camera such as a plugin." }, { "code": null, "e": 4192, "s": 3918, "text": "A haar cascade classifier is used to identify frontal faces in the video frame. We have an array named data to store our predictions. The timer and time_value are used to label the time of each prediction in our data so that the predictions increment by 1s in the.csv file." }, { "code": null, "e": 4477, "s": 4192, "text": "face_cascade = cv2.CascadeClassifier(\"haarcascade_frontalface_default.xml\") vs = VideoStream(src=0).start()start = time.perf_counter() data = []time_value = 0if args[\"save\"]: out = cv2.VideoWriter(path + \"liveoutput.avi\", cv2.VideoWriter_fourcc('M','J','P','G'), 10, (450,253))" }, { "code": null, "e": 4558, "s": 4477, "text": "Now, we will implement a while loop that reads each frame from the video stream:" }, { "code": null, "e": 5171, "s": 4558, "text": "Each Frame is converted to grayscale since the image classifier was trained on grayscale imagesThe cascade classifier is used to find faces in the frame. I set the minneighbors parameter to 5 since I found it worked best on live videos. For recorded video files, I set it to a higher value since a face is guaranteed to be in each frameThe grayscale image is then cropped for the faces with a buffer of 0.3 since our classifier was trained on close-up faces without much backgroundText and bounding boxes are then drawn onto each frame and shownEach frame is then saved to the video writer using out.write(frame)" }, { "code": null, "e": 5267, "s": 5171, "text": "Each Frame is converted to grayscale since the image classifier was trained on grayscale images" }, { "code": null, "e": 5509, "s": 5267, "text": "The cascade classifier is used to find faces in the frame. I set the minneighbors parameter to 5 since I found it worked best on live videos. For recorded video files, I set it to a higher value since a face is guaranteed to be in each frame" }, { "code": null, "e": 5655, "s": 5509, "text": "The grayscale image is then cropped for the faces with a buffer of 0.3 since our classifier was trained on close-up faces without much background" }, { "code": null, "e": 5720, "s": 5655, "text": "Text and bounding boxes are then drawn onto each frame and shown" }, { "code": null, "e": 5788, "s": 5720, "text": "Each frame is then saved to the video writer using out.write(frame)" }, { "code": null, "e": 7041, "s": 5788, "text": "while True: frame = vs.read() frame = imutils.resize(frame, width=450) gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) face_coord = face_cascade.detectMultiScale(gray, 1.1, 5, minSize=(30, 30)) for coords in face_coord: X, Y, w, h = coords H, W, _ = frame.shape X_1, X_2 = (max(0, X - int(w * 0.3)), min(X + int(1.3 * w), W)) Y_1, Y_2 = (max(0, Y - int(0.3 * h)), min(Y + int(1.3 * h), H)) img_cp = gray[Y_1:Y_2, X_1:X_2].copy() prediction, idx, probability = learn.predict(Image(pil2tensor(img_cp, np.float32).div_(225))) cv2.rectangle( img=frame, pt1=(X_1, Y_1), pt2=(X_2, Y_2), color=(128, 128, 0), thickness=2, ) cv2.putText(frame, str(prediction), (10, frame.shape[0] - 25), cv2.FONT_HERSHEY_SIMPLEX, 0.7, (225, 255, 255), 2) cv2.imshow(\"frame\", frame) if args[\"save\"]: out.write(frame) if cv2.waitKey(1) & 0xFF == ord(\"q\"): breakvs.stop()if args[\"save\"]: print(\"done saving video\") out.release()cv2.destroyAllWindows()" }, { "code": null, "e": 7147, "s": 7041, "text": "Now we have our fast.ai learning model working with imutils and OpenCV to predict faces from live videos!" }, { "code": null, "e": 7498, "s": 7147, "text": "Next, it is time to determine the awareness of the face. The function eye_aspect_ratio calculates the eye aspect ratio from the coordinates of the eye. The position and coordinates of each eye are found from the dlib pre-trained facial landmark detector. The function data_time is used to append predictions in the data array every 1-second interval." }, { "code": null, "e": 8192, "s": 7498, "text": "EYE_AR_THRESH = 0.20EYE_AR_CONSEC_FRAMES = 10COUNTER = 0def eye_aspect_ratio(eye): A = dist.euclidean(eye[1], eye[5]) B = dist.euclidean(eye[2], eye[4]) C = dist.euclidean(eye[0], eye[3]) ear = (A + B) / (2.0 * C) return eardef data_time(time_value, prediction, probability, ear): current_time = int(time.perf_counter()-start) if current_time != time_value: data.append([current_time, prediction, probability, ear]) time_value = current_time return time_valuepredictor = dlib.shape_predictor(\"shape_predictor_68_face_landmarks.dat\")(lStart, lEnd) = face_utils.FACIAL_LANDMARKS_IDXS[\"left_eye\"](rStart, rEnd) = face_utils.FACIAL_LANDMARKS_IDXS[\"right_eye\"]" }, { "code": null, "e": 8580, "s": 8192, "text": "Within the for loop which loops over the face coordinates, add the following block of code. The eye is detected using the dlib face landmark detector and drawn onto the frame. When the average calculated eye aspect ratio between the two eyes is less than the threshold for more than ten consecutive frames (which you can modify to your own liking), then the face is marked as distracted." }, { "code": null, "e": 9566, "s": 8580, "text": " rect = dlib.rectangle(X, Y, X+w, Y+h) shape = predictor(gray, rect) shape = face_utils.shape_to_np(shape) leftEye = shape[lStart:lEnd] rightEye = shape[rStart:rEnd] leftEAR = eye_aspect_ratio(leftEye) rightEAR = eye_aspect_ratio(rightEye) ear = (leftEAR + rightEAR) / 2.0 leftEyeHull = cv2.convexHull(leftEye) rightEyeHull = cv2.convexHull(rightEye) cv2.drawContours(frame, [leftEyeHull], -1, (0, 255, 0), 1) cv2.drawContours(frame, [rightEyeHull], -1, (0, 255, 0), 1) if ear < EYE_AR_THRESH: COUNTER += 1 if COUNTER >= EYE_AR_CONSEC_FRAMES: cv2.putText(frame, \"Distracted\", (10, 30), cv2.FONT_HERSHEY_SIMPLEX, 0.7, (0, 0, 255), 2) else: COUNTER = 0 cv2.putText(frame, \"Eye Ratio: {:.2f}\".format(ear), (250, 30), cv2.FONT_HERSHEY_SIMPLEX, 0.7, (0, 0, 255), 2) time_value = data_time(time_value, prediction, probability, ear)" }, { "code": null, "e": 9661, "s": 9566, "text": "Finally, at the bottom of our code, we can save the data as a data frame and then a .csv file." }, { "code": null, "e": 9853, "s": 9661, "text": "if args[\"savedata\"]: df = pd.DataFrame(data, columns = ['Time (seconds)', 'Expression', 'Probability', 'EAR']) df.to_csv(path+'/exportlive.csv') print(\"data saved to exportlive.csv\")" }, { "code": null, "e": 9907, "s": 9853, "text": "You can test the code in the command-line by running:" }, { "code": null, "e": 9954, "s": 9907, "text": "python liveVideoFrameRead.py --save --savedata" }, { "code": null, "e": 9977, "s": 9954, "text": "The full code is here:" }, { "code": null, "e": 10210, "s": 9977, "text": "I used a very similar approach to video files compared to live videos. The main difference is that predictions occur every number of frames, which can be modified using the command-line argument — frame-step. The full code is below:" }, { "code": null, "e": 10312, "s": 10210, "text": "And that’s it! You now are able to predict facial expressions from both video files and live webcams." } ]
XML DOM - Quick Guide
The Document Object Model (DOM) is a W3C standard. It defines a standard for accessing documents like HTML and XML. Definition of DOM as put by the W3C is − DOM defines the objects and properties and methods (interface) to access all XML elements. It is separated into 3 different parts / levels − Core DOM − standard model for any structured document Core DOM − standard model for any structured document XML DOM − standard model for XML documents XML DOM − standard model for XML documents HTML DOM − standard model for HTML documents HTML DOM − standard model for HTML documents XML DOM is a standard object model for XML. XML documents have a hierarchy of informational units called nodes; DOM is a standard programming interface of describing those nodes and the relationships between them. As XML DOM also provides an API that allows a developer to add, edit, move or remove nodes at any point on the tree in order to create an application. Following is the diagram for the DOM structure. The diagram depicts that parser evaluates an XML document as a DOM structure by traversing through each node. The following are the advantages of XML DOM. XML DOM is language and platform independent. XML DOM is language and platform independent. XML DOM is traversable - Information in XML DOM is organized in a hierarchy which allows developer to navigate around the hierarchy looking for specific information. XML DOM is traversable - Information in XML DOM is organized in a hierarchy which allows developer to navigate around the hierarchy looking for specific information. XML DOM is modifiable - It is dynamic in nature providing the developer a scope to add, edit, move or remove nodes at any point on the tree. XML DOM is modifiable - It is dynamic in nature providing the developer a scope to add, edit, move or remove nodes at any point on the tree. It consumes more memory (if the XML structure is large) as program written once remains in memory all the time until and unless removed explicitly. It consumes more memory (if the XML structure is large) as program written once remains in memory all the time until and unless removed explicitly. Due to the extensive usage of memory, its operational speed, compared to SAX is slower. Due to the extensive usage of memory, its operational speed, compared to SAX is slower. Now that we know what DOM means, let's see what a DOM structure is. A DOM document is a collection of nodes or pieces of information, organized in a hierarchy. Some types of nodes may have child nodes of various types and others are leaf nodes that cannot have anything under them in the document structure. Following is a list of the node types, with a list of node types that they may have as children − Document − Element (maximum of one), ProcessingInstruction, Comment, DocumentType (maximum of one) Document − Element (maximum of one), ProcessingInstruction, Comment, DocumentType (maximum of one) DocumentFragment − Element, ProcessingInstruction, Comment, Text, CDATASection, EntityReference DocumentFragment − Element, ProcessingInstruction, Comment, Text, CDATASection, EntityReference EntityReference − Element, ProcessingInstruction, Comment, Text, CDATASection, EntityReference EntityReference − Element, ProcessingInstruction, Comment, Text, CDATASection, EntityReference Element − Element, Text, Comment, ProcessingInstruction, CDATASection, EntityReference Element − Element, Text, Comment, ProcessingInstruction, CDATASection, EntityReference Attr − Text, EntityReference Attr − Text, EntityReference ProcessingInstruction − No children ProcessingInstruction − No children Comment − No children Comment − No children Text − No children Text − No children CDATASection − No children CDATASection − No children Entity − Element, ProcessingInstruction, Comment, Text, CDATASection, EntityReference Entity − Element, ProcessingInstruction, Comment, Text, CDATASection, EntityReference Notation − No children Notation − No children Consider the DOM representation of the following XML document node.xml. <?xml version = "1.0"?> <Company> <Employee category = "technical"> <FirstName>Tanmay</FirstName> <LastName>Patil</LastName> <ContactNo>1234567890</ContactNo> </Employee> <Employee category = "non-technical"> <FirstName>Taniya</FirstName> <LastName>Mishra</LastName> <ContactNo>1234667898</ContactNo> </Employee> </Company> The Document Object Model of the above XML document would be as follows − From the above flowchart, we can infer − Node object can have only one parent node object. This occupies the position above all the nodes. Here it is Company. Node object can have only one parent node object. This occupies the position above all the nodes. Here it is Company. The parent node can have multiple nodes called the child nodes. These child nodes can have additional nodes called the attribute nodes. In the above example, we have two attribute nodes Technical and Non-technical. The attribute node is not actually a child of the element node, but is still associated with it. The parent node can have multiple nodes called the child nodes. These child nodes can have additional nodes called the attribute nodes. In the above example, we have two attribute nodes Technical and Non-technical. The attribute node is not actually a child of the element node, but is still associated with it. These child nodes in turn can have multiple child nodes. The text within the nodes is called the text node. These child nodes in turn can have multiple child nodes. The text within the nodes is called the text node. The node objects at the same level are called as siblings. The node objects at the same level are called as siblings. The DOM identifies − the objects to represent the interface and manipulate the document. the relationship among the objects and interfaces. The DOM identifies − the objects to represent the interface and manipulate the document. the objects to represent the interface and manipulate the document. the relationship among the objects and interfaces. the relationship among the objects and interfaces. In this chapter, we will study about the XML DOM Nodes. Every XML DOM contains the information in hierarchical units called Nodes and the DOM describes these nodes and the relationship between them. The following flowchart shows all the node types − The most common types of nodes in XML are − Document Node − Complete XML document structure is a document node. Document Node − Complete XML document structure is a document node. Element Node − Every XML element is an element node. This is also the only type of node that can have attributes. Element Node − Every XML element is an element node. This is also the only type of node that can have attributes. Attribute Node − Each attribute is considered an attribute node. It contains information about an element node, but is not actually considered to be children of the element. Attribute Node − Each attribute is considered an attribute node. It contains information about an element node, but is not actually considered to be children of the element. Text Node − The document texts are considered as text node. It can consist of more information or just white space. Text Node − The document texts are considered as text node. It can consist of more information or just white space. Some less common types of nodes are − CData Node − This node contains information that should not be analyzed by the parser. Instead, it should just be passed on as plain text. CData Node − This node contains information that should not be analyzed by the parser. Instead, it should just be passed on as plain text. Comment Node − This node includes information about the data, and is usually ignored by the application. Comment Node − This node includes information about the data, and is usually ignored by the application. Processing Instructions Node − This node contains information specifically aimed at the application. Processing Instructions Node − This node contains information specifically aimed at the application. Document Fragments Node Document Fragments Node Entities Node Entities Node Entity reference nodes Entity reference nodes Notations Node Notations Node In this chapter, we will study about the XML DOM Node Tree. In an XML document, the information is maintained in hierarchical structure; this hierarchical structure is referred to as the Node Tree. This hierarchy allows a developer to navigate around the tree looking for specific information, thus nodes are allowed to access. The content of these nodes can then be updated. The structure of the node tree begins with the root element and spreads out to the child elements till the lowest level. Following example demonstrates a simple XML document, whose node tree is structure is shown in the diagram below − <?xml version = "1.0"?> <Company> <Employee category = "Technical"> <FirstName>Tanmay</FirstName> <LastName>Patil</LastName> <ContactNo>1234567890</ContactNo> </Employee> <Employee category = "Non-Technical"> <FirstName>Taniya</FirstName> <LastName>Mishra</LastName> <ContactNo>1234667898</ContactNo> </Employee> </Company> As can be seen in the above example whose pictorial representation (of its DOM) is as shown below − The topmost node of a tree is called the root. The root node is <Company> which in turn contains the two nodes of <Employee>. These nodes are referred to as child nodes. The topmost node of a tree is called the root. The root node is <Company> which in turn contains the two nodes of <Employee>. These nodes are referred to as child nodes. The child node <Employee> of root node <Company>, in turn consists of its own child node (<FirstName>, <LastName>, <ContactNo>). The child node <Employee> of root node <Company>, in turn consists of its own child node (<FirstName>, <LastName>, <ContactNo>). The two child nodes, <Employee> have attribute values Technical and Non-Technical, are referred as attribute nodes. The two child nodes, <Employee> have attribute values Technical and Non-Technical, are referred as attribute nodes. The text within every node is called the text node. The text within every node is called the text node. DOM as an API contains interfaces that represent different types of information that can be found in an XML document, such as elements and text. These interfaces include the methods and properties necessary to work with these objects. Properties define the characteristic of the node whereas methods give the way to manipulate the nodes. Following table lists the DOM classes and interfaces − DOMImplementation It provides a number of methods for performing operations that are independent of any particular instance of the document object model. DocumentFragment It is the "lightweight" or "minimal" document object, and it (as the superclass of Document) anchors the XML/HTML tree in a full-fledged document. Document It represents the XML document's top-level node, which provides access to all the nodes in the document, including the root element. Node It represents XML node. NodeList It represents a read-only list of Node objects. NamedNodeMap It represents collections of nodes that can be accessed by name. Data It extends Node with a set of attributes and methods for accessing character data in the DOM. Attribute It represents an attribute in an Element object. Element It represents the element node. Derives from Node. Text It represents the text node. Derives from CharacterData. Comment It represents the comment node. Derives from CharacterData. ProcessingInstruction It represents a "processing instruction". It is used in XML as a way to keep processor-specific information in the text of the document. CDATA Section It represents the CDATA Section. Derives from Text. Entity It represents an entity. Derives from Node. EntityReference This represent an entity reference in the tree. Derives from Node. In this chapter, we will study about XML Loading and Parsing. In order to describe the interfaces provided by the API, the W3C uses an abstract language called the Interface Definition Language (IDL). The advantage of using IDL is that the developer learns how to use the DOM with his or her favorite language and can switch easily to a different language. The disadvantage is that, since it is abstract, the IDL cannot be used directly by Web developers. Due to the differences between programming languages, they need to have mapping — or binding — between the abstract interfaces and their concrete languages. DOM has been mapped to programming languages such as Javascript, JScript, Java, C, C++, PLSQL, Python, and Perl. A parser is a software application that is designed to analyze a document, in our case XML document and do something specific with the information. Some of the DOM based parsers are listed in the following table − JAXP Sun Microsystem’s Java API for XML Parsing (JAXP) XML4J IBM’s XML Parser for Java (XML4J) msxml Microsoft’s XML parser (msxml) version 2.0 is built-into Internet Explorer 5.5 4DOM 4DOM is a parser for the Python programming language XML::DOM XML::DOM is a Perl module to manipulate XML documents using Perl Xerces Apache’s Xerces Java Parser In a tree-based API like DOM, the parser traverses the XML file and creates the corresponding DOM objects. Then you can traverse the DOM structure back and forth. While loading an XML document, the XML content can come in two forms − Directly as XML file As XML string Following example demonstrates how to load XML (node.xml) data using Ajax and Javascript when the XML content is received as an XML file. Here, the Ajax function gets the content of an xml file and stores it in XML DOM. Once the DOM object is created, it is then parsed. <!DOCTYPE html> <html> <body> <div> <b>FirstName:</b> <span id = "FirstName"></span><br> <b>LastName:</b> <span id = "LastName"></span><br> <b>ContactNo:</b> <span id = "ContactNo"></span><br> <b>Email:</b> <span id = "Email"></span> </div> <script> //if browser supports XMLHttpRequest if (window.XMLHttpRequest) { // Create an instance of XMLHttpRequest object. code for IE7+, Firefox, Chrome, Opera, Safari xmlhttp = new XMLHttpRequest(); } else { // code for IE6, IE5 xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); } // sets and sends the request for calling "node.xml" xmlhttp.open("GET","/dom/node.xml",false); xmlhttp.send(); // sets and returns the content as XML DOM xmlDoc = xmlhttp.responseXML; //parsing the DOM object document.getElementById("FirstName").innerHTML = xmlDoc.getElementsByTagName("FirstName")[0].childNodes[0].nodeValue; document.getElementById("LastName").innerHTML = xmlDoc.getElementsByTagName("LastName")[0].childNodes[0].nodeValue; document.getElementById("ContactNo").innerHTML = xmlDoc.getElementsByTagName("ContactNo")[0].childNodes[0].nodeValue; document.getElementById("Email").innerHTML = xmlDoc.getElementsByTagName("Email")[0].childNodes[0].nodeValue; </script> </body> </html> <Company> <Employee category = "Technical" id = "firstelement"> <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> Most of the details of the code are in the script code. Internet Explorer uses the ActiveXObject("Microsoft.XMLHTTP") to create an instance of XMLHttpRequest object, other browsers use the XMLHttpRequest() method. Internet Explorer uses the ActiveXObject("Microsoft.XMLHTTP") to create an instance of XMLHttpRequest object, other browsers use the XMLHttpRequest() method. the responseXML transforms the XML content directly in XML DOM. the responseXML transforms the XML content directly in XML DOM. Once the XML content is transformed into JavaScript XML DOM, you can access any XML element by using the JS DOM methods and properties. We have used the DOM properties such as childNodes, nodeValue and DOM methods such as getElementsById(ID), getElementsByTagName(tags_name). Once the XML content is transformed into JavaScript XML DOM, you can access any XML element by using the JS DOM methods and properties. We have used the DOM properties such as childNodes, nodeValue and DOM methods such as getElementsById(ID), getElementsByTagName(tags_name). Save this file as loadingexample.html and open it in your browser. You will receive the following output − Following example demonstrates how to load XML data using Ajax and Javascript when XML content is received as XML file. Here, the Ajax function, gets the content of an xml file and stores it in XML DOM. Once the DOM object is created it is then parsed. <!DOCTYPE html> <html> <head> <script> // loads the xml string in a dom object function loadXMLString(t) { // for non IE browsers if (window.DOMParser) { // create an instance for xml dom object parser = new DOMParser(); xmlDoc = parser.parseFromString(t,"text/xml"); } // code for IE else { // create an instance for xml dom object xmlDoc = new ActiveXObject("Microsoft.XMLDOM"); xmlDoc.async = false; xmlDoc.loadXML(t); } return xmlDoc; } </script> </head> <body> <script> // a variable with the string var text = "<Employee>"; text = text+"<FirstName>Tanmay</FirstName>"; text = text+"<LastName>Patil</LastName>"; text = text+"<ContactNo>1234567890</ContactNo>"; text = text+"<Email>[email protected]</Email>"; text = text+"</Employee>"; // calls the loadXMLString() with "text" function and store the xml dom in a variable var xmlDoc = loadXMLString(text); //parsing the DOM object y = xmlDoc.documentElement.childNodes; for (i = 0;i<y.length;i++) { document.write(y[i].childNodes[0].nodeValue); document.write("<br>"); } </script> </body> </html> Most of the details of the code are in the script code. Internet Explorer uses the ActiveXObject("Microsoft.XMLDOM") to load XML data into a DOM object, other browsers use the DOMParser() function and parseFromString(text, 'text/xml') method. Internet Explorer uses the ActiveXObject("Microsoft.XMLDOM") to load XML data into a DOM object, other browsers use the DOMParser() function and parseFromString(text, 'text/xml') method. The variable text shall contain a string with XML content. The variable text shall contain a string with XML content. Once the XML content is transformed into JavaScript XML DOM, you can access any XML element by using JS DOM methods and properties. We have used DOM properties such as childNodes, nodeValue. Once the XML content is transformed into JavaScript XML DOM, you can access any XML element by using JS DOM methods and properties. We have used DOM properties such as childNodes, nodeValue. Save this file as loadingexample.html and open it in your browser. You will see the following output − Now that we saw how the XML content transforms into JavaScript XML DOM, you can now access any XML element by using the XML DOM methods. In this chapter, we will discuss XML DOM Traversing. We studied in the previous chapter how to load XML document and parse the thus obtained DOM object. This parsed DOM object can be traversed. Traversing is a process in which looping is done in a systematic manner by going across each and every element step by step in a node tree. The following example (traverse_example.htm) demonstrates DOM traversing. Here we traverse through each child node of <Employee> element. <!DOCTYPE html> <html> <style> table,th,td { border:1px solid black; border-collapse:collapse } </style> <body> <div id = "ajax_xml"></div> <script> //if browser supports XMLHttpRequest if (window.XMLHttpRequest) {// Create an instance of XMLHttpRequest object. code for IE7+, Firefox, Chrome, Opera, Safari var xmlhttp = new XMLHttpRequest(); } else {// code for IE6, IE5 var xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); } // sets and sends the request for calling "node.xml" xmlhttp.open("GET","/dom/node.xml",false); xmlhttp.send(); // sets and returns the content as XML DOM var xml_dom = xmlhttp.responseXML; // this variable stores the code of the html table var html_tab = '<table id = "id_tabel" align = "center"> <tr> <th>Employee Category</th> <th>FirstName</th> <th>LastName</th> <th>ContactNo</th> <th>Email</th> </tr>'; var arr_employees = xml_dom.getElementsByTagName("Employee"); // traverses the "arr_employees" array for(var i = 0; i<arr_employees.length; i++) { var employee_cat = arr_employees[i].getAttribute('category'); // gets the value of 'category' element of current "Element" tag // gets the value of first child-node of 'FirstName' // element of current "Employee" tag var employee_firstName = arr_employees[i].getElementsByTagName('FirstName')[0].childNodes[0].nodeValue; // gets the value of first child-node of 'LastName' // element of current "Employee" tag var employee_lastName = arr_employees[i].getElementsByTagName('LastName')[0].childNodes[0].nodeValue; // gets the value of first child-node of 'ContactNo' // element of current "Employee" tag var employee_contactno = arr_employees[i].getElementsByTagName('ContactNo')[0].childNodes[0].nodeValue; // gets the value of first child-node of 'Email' // element of current "Employee" tag var employee_email = arr_employees[i].getElementsByTagName('Email')[0].childNodes[0].nodeValue; // adds the values in the html table html_tab += '<tr> <td>'+ employee_cat+ '</td> <td>'+ employee_firstName+ '</td> <td>'+ employee_lastName+ '</td> <td>'+ employee_contactno+ '</td> <td>'+ employee_email+ '</td> </tr>'; } html_tab += '</table>'; // adds the html table in a html tag, with id = "ajax_xml" document.getElementById('ajax_xml').innerHTML = html_tab; </script> </body> </html> This code loads node.xml. This code loads node.xml. The XML content is transformed into JavaScript XML DOM object. The XML content is transformed into JavaScript XML DOM object. The array of elements (with tag Element) using the method getElementsByTagName() is obtained. The array of elements (with tag Element) using the method getElementsByTagName() is obtained. Next, we traverse through this array and display the child node values in a table. Next, we traverse through this array and display the child node values in a table. Save this file as traverse_example.html on the server path (this file and node.xml should be on the same path in your server). You will receive the following output − Until now we studied DOM structure, how to load and parse XML DOM object and traverse through the DOM objects. Here we will see how we can navigate between nodes in a DOM object. The XML DOM consist of various properties of the nodes which help us navigate through the nodes, such as − parentNode childNodes firstChild lastChild nextSibling previousSibling Following is a diagram of a node tree showing its relationship with the other nodes. This property specifies the parent node as a node object. The following example (navigate_example.htm) parses an XML document (node.xml) into an XML DOM object. Then the DOM object is navigated to the parent node through the child node − <!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; var y = xmlDoc.getElementsByTagName("Employee")[0]; document.write(y.parentNode.nodeName); </script> </body> </html> As you can see in the above example, the child node Employee navigates to its parent node. Save this file as navigate_example.html on the server path (this file and node.xml should be on the same path in your server). In the output, we get the parent node of Employee, i.e, Company. This property is of type Node and represents the first child name present in the NodeList. The following example (first_node_example.htm) parses an XML document (node.xml) into an XML DOM object, then navigates to the first child node present in the DOM object. <!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; function get_firstChild(p) { a = p.firstChild; while (a.nodeType != 1) { a = a.nextSibling; } return a; } var firstchild = get_firstChild(xmlDoc.getElementsByTagName("Employee")[0]); document.write(firstchild.nodeName); </script> </body> </html> Function get_firstChild(p) is used to avoid the empty nodes. It helps to get the firstChild element from the node list. Function get_firstChild(p) is used to avoid the empty nodes. It helps to get the firstChild element from the node list. x = get_firstChild(xmlDoc.getElementsByTagName("Employee")[0]) fetches the first child node for the tag name Employee. x = get_firstChild(xmlDoc.getElementsByTagName("Employee")[0]) fetches the first child node for the tag name Employee. Save this file as first_node_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 first child node of Employee i.e. FirstName. This property is of type Node and represents the last child name present in the NodeList. The following example (last_node_example.htm) parses an XML document (node.xml) into an XML DOM object, then navigates to the last child node present in the xml DOM object. <!DOCTYPE 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; function get_lastChild(p) { a = p.lastChild; while (a.nodeType != 1){ a = a.previousSibling; } return a; } var lastchild = get_lastChild(xmlDoc.getElementsByTagName("Employee")[0]); document.write(lastchild.nodeName); </script> </body> </html> Save this file as last_node_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 last child node of Employee, i.e, Email. This property is of type Node and represents the next child, i.e, the next sibling of the specified child element present in the NodeList. The following example (nextSibling_example.htm) parses an XML document (node.xml) into an XML DOM object which navigates immediately to the next node present in the xml document. <!DOCTYPE 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; function get_nextSibling(p) { a = p.nextSibling; while (a.nodeType != 1) { a = a.nextSibling; } return a; } var nextsibling = get_nextSibling(xmlDoc.getElementsByTagName("FirstName")[0]); document.write(nextsibling.nodeName); </script> </body> </html> Save this file as nextSibling_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 next sibling node of FirstName, i.e, LastName. This property is of type Node and represents the previous child, i.e, the previous sibling of the specified child element present in the NodeList. The following example (previoussibling_example.htm) parses an XML document (node.xml) into an XML DOM object, then navigates the before node of the last child node present in the xml document. <!DOCTYPE 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; function get_previousSibling(p) { a = p.previousSibling; while (a.nodeType != 1) { a = a.previousSibling; } return a; } prevsibling = get_previousSibling(xmlDoc.getElementsByTagName("Email")[0]); document.write(prevsibling.nodeName); </script> </body> </html> Save this file as previoussibling_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 previous sibling node of Email, i.e, ContactNo. In this chapter, we will study about how to access the XML DOM nodes which are considered as the informational units of the XML document. The node structure of the XML DOM allows the developer to navigate around the tree looking for specific information and simultaneously access the information. Following are the three ways in which you can access the nodes − By using the getElementsByTagName () method By using the getElementsByTagName () method By looping through or traversing through nodes tree By looping through or traversing through nodes tree By navigating the node tree, using the node relationships By navigating the node tree, using the node relationships This method allows accessing the information of a node by specifying the node name. It also allows accessing the information of the Node List and Node List Length. The getElementByTagName() method has the following syntax − node.getElementByTagName("tagname"); Where, node − is the document node. node − is the document node. tagname − holds the name of the node whose value you want to get. tagname − holds the name of the node whose value you want to get. Following is a simple program which illustrates the usage of method getElementByTagName. <!DOCTYPE html> <html> <body> <div> <b>FirstName:</b> <span id = "FirstName"></span><br> <b>LastName:</b> <span id = "LastName"></span><br> <b>Category:</b> <span id = "Employee"></span><br> </div> <script> if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari xmlhttp = new XMLHttpRequest(); } else {// code for IE6, IE5 xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); } xmlhttp.open("GET","/dom/node.xml",false); xmlhttp.send(); xmlDoc = xmlhttp.responseXML; document.getElementById("FirstName").innerHTML = xmlDoc.getElementsByTagName("FirstName")[0].childNodes[0].nodeValue; document.getElementById("LastName").innerHTML = xmlDoc.getElementsByTagName("LastName")[0].childNodes[0].nodeValue; document.getElementById("Employee").innerHTML = xmlDoc.getElementsByTagName("Employee")[0].attributes[0].nodeValue; </script> </body> </html> In the above example, we are accessing the information of the nodes FirstName, LastName and Employee. In the above example, we are accessing the information of the nodes FirstName, LastName and Employee. xmlDoc.getElementsByTagName("FirstName")[0].childNodes[0].nodeValue; This line accesses the value for the child node FirstName using the getElementByTagName() method. xmlDoc.getElementsByTagName("FirstName")[0].childNodes[0].nodeValue; This line accesses the value for the child node FirstName using the getElementByTagName() method. xmlDoc.getElementsByTagName("Employee")[0].attributes[0].nodeValue; This line accesses the attribute value of the node Employee getElementByTagName() method. xmlDoc.getElementsByTagName("Employee")[0].attributes[0].nodeValue; This line accesses the attribute value of the node Employee getElementByTagName() method. This is covered in the chapter DOM Traversing with examples. This is covered in the chapter DOM Navigation with examples. 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. In this chapter, we will study about how to change the values of nodes in an XML DOM object. Node value can be changed as follows − var value = node.nodeValue; If node is an Attribute then the value variable will be the value of the attribute; if node is a Text node it will be the text content; if node is an Element it will be null. Following sections will demonstrate the node value setting for each node type (attribute, text node and element). 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> When we, say the change value of Node element we mean to edit the text content of an element (which is also called the text node). Following example demonstrates how to change the text node of an element. The following example (set_text_node_example.htm) parses an XML document (node.xml) into an XML DOM object and change the value of an element's text node. In this case, Email of each Employee to [email protected] and print the values. <!DOCTYPE html> <html> <head> <script> function loadXMLDoc(filename) { if (window.XMLHttpRequest) { xhttp = new XMLHttpRequest(); } else // code for IE5 and IE6 { xhttp = new ActiveXObject("Microsoft.XMLHTTP"); } xhttp.open("GET",filename,false); xhttp.send(); return xhttp.responseXML; } </script> </head> <body> <script> xmlDoc = loadXMLDoc("/dom/node.xml"); x = xmlDoc.getElementsByTagName("Email"); for(i = 0;i<x.length;i++) { x[i].childNodes[0].nodeValue = "[email protected]"; document.write(i+'); document.write(x[i].childNodes[0].nodeValue); document.write('<br>'); } </script> </body> </html> Save this file as set_text_node_example.htm on the server path (this file and node.xml should be on the same path in your server). You will receive the following output − 0) [email protected] 1) [email protected] 2) [email protected] The following example demonstrates how to change the attribute node of an element. The following example (set_attribute_example.htm) parses an XML document (node.xml) into an XML DOM object and changes the value of an element's attribute node. In this case, the Category of each Employee to admin-0, admin-1, admin-2 respectively and print the values. <!DOCTYPE html> <html> <head> <script> function loadXMLDoc(filename) { if (window.XMLHttpRequest) { xhttp = new XMLHttpRequest(); } else // code for IE5 and IE6 { xhttp = new ActiveXObject("Microsoft.XMLHTTP"); } xhttp.open("GET",filename,false); xhttp.send(); return xhttp.responseXML; } </script> </head> <body> <script> xmlDoc = loadXMLDoc("/dom/node.xml"); x = xmlDoc.getElementsByTagName("Employee"); for(i = 0 ;i<x.length;i++){ newcategory = x[i].getAttributeNode('category'); newcategory.nodeValue = "admin-"+i; document.write(i+'); document.write(x[i].getAttributeNode('category').nodeValue); document.write('<br>'); } </script> </body> </html> Save this file as set_node_attribute_example.htm on the server path (this file and node.xml should be on the same path in your server). The result would be as below − 0) admin-0 1) admin-1 2) admin-2 In this chapter, we will discuss how to create new nodes using a couple of methods of the document object. These methods provide a scope to create new element node, text node, comment node, CDATA section node and attribute node. If the newly created node already exists in the element object, it is replaced by the new one. Following sections demonstrate this with examples. The method createElement() creates a new element node. If the newly created element node exists in the element object, it is replaced by the new one. Syntax to use the createElement() method is as follows − var_name = xmldoc.createElement("tagname"); Where, var_name − is the user-defined variable name which holds the name of new element. var_name − is the user-defined variable name which holds the name of new element. ("tagname") − is the name of new element node to be created. ("tagname") − is the name of new element node to be created. The following example (createnewelement_example.htm) parses an XML document (node.xml) into an XML DOM object and creates a new element node PhoneNo in the XML document. <!DOCTYPE html> <html> <head> <script> function loadXMLDoc(filename) { if (window.XMLHttpRequest) { xhttp = new XMLHttpRequest(); } else // code for IE5 and IE6 { xhttp = new ActiveXObject("Microsoft.XMLHTTP"); } xhttp.open("GET",filename,false); xhttp.send(); return xhttp.responseXML; } </script> </head> <body> <script> xmlDoc = loadXMLDoc("/dom/node.xml"); new_element = xmlDoc.createElement("PhoneNo"); x = xmlDoc.getElementsByTagName("FirstName")[0]; x.appendChild(new_element); document.write(x.getElementsByTagName("PhoneNo")[0].nodeName); </script> </body> </html> new_element = xmlDoc.createElement("PhoneNo"); creates the new element node <PhoneNo> new_element = xmlDoc.createElement("PhoneNo"); creates the new element node <PhoneNo> x.appendChild(new_element); x holds the name of the specified child node <FirstName> to which the new element node is appended. x.appendChild(new_element); x holds the name of the specified child node <FirstName> to which the new element node is appended. Save this file as createnewelement_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 PhoneNo. The method createTextNode() creates a new text node. Syntax to use createTextNode() is as follows − var_name = xmldoc.createTextNode("tagname"); Where, var_name − it is the user-defined variable name which holds the name of new text node. var_name − it is the user-defined variable name which holds the name of new text node. ("tagname") − within the parenthesis is the name of new text node to be created. ("tagname") − within the parenthesis is the name of new text node to be created. The following example (createtextnode_example.htm) parses an XML document (node.xml) into an XML DOM object and creates a new text node Im new text node in the XML document. <!DOCTYPE html> <html> <head> <script> function loadXMLDoc(filename) { if (window.XMLHttpRequest) { xhttp = new XMLHttpRequest(); } else // code for IE5 and IE6 { xhttp = new ActiveXObject("Microsoft.XMLHTTP"); } xhttp.open("GET",filename,false); xhttp.send(); return xhttp.responseXML; } </script> </head> <body> <script> xmlDoc = loadXMLDoc("/dom/node.xml"); create_e = xmlDoc.createElement("PhoneNo"); create_t = xmlDoc.createTextNode("Im new text node"); create_e.appendChild(create_t); x = xmlDoc.getElementsByTagName("Employee")[0]; x.appendChild(create_e); document.write(" PhoneNO: "); document.write(x.getElementsByTagName("PhoneNo")[0].childNodes[0].nodeValue); </script> </body> </html> Details of the above code are as below − create_e = xmlDoc.createElement("PhoneNo"); creates a new element <PhoneNo>. create_e = xmlDoc.createElement("PhoneNo"); creates a new element <PhoneNo>. create_t = xmlDoc.createTextNode("Im new text node"); creates a new text node "Im new text node". create_t = xmlDoc.createTextNode("Im new text node"); creates a new text node "Im new text node". x.appendChild(create_e); the text node, "Im new text node" is appended to the element, <PhoneNo>. x.appendChild(create_e); the text node, "Im new text node" is appended to the element, <PhoneNo>. document.write(x.getElementsByTagName("PhoneNo")[0].childNodes[0].nodeValue); writes the new text node value to the element <PhoneNo>. document.write(x.getElementsByTagName("PhoneNo")[0].childNodes[0].nodeValue); writes the new text node value to the element <PhoneNo>. Save this file as createtextnode_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 i.e. PhoneNO: Im new text node. The method createComment() creates a new comment node. Comment node is included in the program for the easy understanding of the code functionality. Syntax to use createComment() is as follows − var_name = xmldoc.createComment("tagname"); Where, var_name − is the user-defined variable name which holds the name of new comment node. var_name − is the user-defined variable name which holds the name of new comment node. ("tagname") − is the name of the new comment node to be created. ("tagname") − is the name of the new comment node to be created. The following example (createcommentnode_example.htm) parses an XML document (node.xml) into an XML DOM object and creates a new comment node, "Company is the parent node" in the XML document. <!DOCTYPE html> <html> <head> <script> function loadXMLDoc(filename) { if (window.XMLHttpRequest) { xhttp = new XMLHttpRequest(); } else // code for IE5 and IE6 { xhttp = new ActiveXObject("Microsoft.XMLHTTP"); } xhttp.open("GET",filename,false); xhttp.send(); return xhttp.responseXML; } </script> </head> <body> <script> xmlDoc = loadXMLDoc("/dom/node.xml"); create_comment = xmlDoc.createComment("Company is the parent node"); x = xmlDoc.getElementsByTagName("Company")[0]; x.appendChild(create_comment); document.write(x.lastChild.nodeValue); </script> </body> </html> In the above example − create_comment = xmlDoc.createComment("Company is the parent node") creates a specified comment line. create_comment = xmlDoc.createComment("Company is the parent node") creates a specified comment line. x.appendChild(create_comment) In this line, 'x' holds the name of the element <Company> to which the comment line is appended. x.appendChild(create_comment) In this line, 'x' holds the name of the element <Company> to which the comment line is appended. Save this file as createcommentnode_example.htm on the server path (this file and the node.xml should be on the same path in your server). In the output, we get the attribute value as Company is the parent node . The method createCDATASection() creates a new CDATA section node. If the newly created CDATA section node exists in the element object, it is replaced by the new one. Syntax to use createCDATASection() is as follows − var_name = xmldoc.createCDATASection("tagname"); Where, var_name − is the user-defined variable name which holds the name of new the CDATA section node. var_name − is the user-defined variable name which holds the name of new the CDATA section node. ("tagname") − is the name of new CDATA section node to be created. ("tagname") − is the name of new CDATA section node to be created. The following example (createcdatanode_example.htm) parses an XML document (node.xml) into an XML DOM object and creates a new CDATA section node, "Create CDATA Example" in the XML document. <!DOCTYPE html> <html> <head> <script> function loadXMLDoc(filename) { if (window.XMLHttpRequest) { xhttp = new XMLHttpRequest(); } else // code for IE5 and IE6 { xhttp = new ActiveXObject("Microsoft.XMLHTTP"); } xhttp.open("GET",filename,false); xhttp.send(); return xhttp.responseXML; } </script> </head> <body> <script> xmlDoc = loadXMLDoc("/dom/node.xml"); create_CDATA = xmlDoc.createCDATASection("Create CDATA Example"); x = xmlDoc.getElementsByTagName("Employee")[0]; x.appendChild(create_CDATA); document.write(x.lastChild.nodeValue); </script> </body> </html> In the above example − create_CDATA = xmlDoc.createCDATASection("Create CDATA Example") creates a new CDATA section node, "Create CDATA Example" create_CDATA = xmlDoc.createCDATASection("Create CDATA Example") creates a new CDATA section node, "Create CDATA Example" x.appendChild(create_CDATA) here, x holds the specified element <Employee> indexed at 0 to which the CDATA node value is appended. x.appendChild(create_CDATA) here, x holds the specified element <Employee> indexed at 0 to which the CDATA node value is appended. Save this file as createcdatanode_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 Create CDATA Example. To create a new attribute node, the method setAttributeNode() is used. If the newly created attribute node exists in the element object, it is replaced by the new one. Syntax to use the createElement() method is as follows − var_name = xmldoc.createAttribute("tagname"); Where, var_name − is the user-defined variable name which holds the name of new attribute node. var_name − is the user-defined variable name which holds the name of new attribute node. ("tagname") − is the name of new attribute node to be created. ("tagname") − is the name of new attribute node to be created. The following example (createattributenode_example.htm) parses an XML document (node.xml) into an XML DOM object and creates a new attribute node section in the XML document. <!DOCTYPE html> <html> <head> <script> function loadXMLDoc(filename) { if (window.XMLHttpRequest) { xhttp = new XMLHttpRequest(); } else // code for IE5 and IE6 { xhttp = new ActiveXObject("Microsoft.XMLHTTP"); } xhttp.open("GET",filename,false); xhttp.send(); return xhttp.responseXML; } </script> </head> <body> <script> xmlDoc = loadXMLDoc("/dom/node.xml"); create_a = xmlDoc.createAttribute("section"); create_a.nodeValue = "A"; x = xmlDoc.getElementsByTagName("Employee"); x[0].setAttributeNode(create_a); document.write("New Attribute: "); document.write(x[0].getAttribute("section")); </script> </body> </html> In the above example − create_a=xmlDoc.createAttribute("Category") creates an attribute with the name <section>. create_a=xmlDoc.createAttribute("Category") creates an attribute with the name <section>. create_a.nodeValue="Management" creates the value "A" for the attribute <section>. create_a.nodeValue="Management" creates the value "A" for the attribute <section>. x[0].setAttributeNode(create_a) this attribute value is set to the node element <Employee> indexed at 0. x[0].setAttributeNode(create_a) this attribute value is set to the node element <Employee> indexed at 0. In this chapter, we will discuss the nodes to the existing element. It provides a means to − append new child nodes before or after the existing child nodes append new child nodes before or after the existing child nodes insert data within the text node insert data within the text node add attribute node add attribute node Following methods can be used to add/append the nodes to an element in a DOM − appendChild() insertBefore() insertData() The method appendChild() adds the new child node after the existing child node. Syntax of appendChild() method is as follows − Node appendChild(Node newChild) throws DOMException Where, newChild − Is the node to add newChild − Is the node to add This method returns the Node added. This method returns the Node added. The following example (appendchildnode_example.htm) parses an XML document (node.xml) into an XML DOM object and appends new child PhoneNo to the element <FirstName>. <!DOCTYPE html> <html> <head> <script> function loadXMLDoc(filename) { if (window.XMLHttpRequest) { xhttp = new XMLHttpRequest(); } else // code for IE5 and IE6 { xhttp = new ActiveXObject("Microsoft.XMLHTTP"); } xhttp.open("GET",filename,false); xhttp.send(); return xhttp.responseXML; } </script> </head> <body> <script> xmlDoc = loadXMLDoc("/dom/node.xml"); create_e = xmlDoc.createElement("PhoneNo"); x = xmlDoc.getElementsByTagName("FirstName")[0]; x.appendChild(create_e); document.write(x.getElementsByTagName("PhoneNo")[0].nodeName); </script> </body> </html> In the above example − using the method createElement(), a new element PhoneNo is created. using the method createElement(), a new element PhoneNo is created. The new element PhoneNo is added to the element FirstName using the method appendChild(). The new element PhoneNo is added to the element FirstName using the method appendChild(). Save this file as appendchildnode_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 PhoneNo. The method insertBefore(), inserts the new child nodes before the specified child nodes. Syntax of insertBefore() method is as follows − Node insertBefore(Node newChild, Node refChild) throws DOMException Where, newChild − Is the node to insert newChild − Is the node to insert refChild − Is the reference node, i.e., the node before which the new node must be inserted. refChild − Is the reference node, i.e., the node before which the new node must be inserted. This method returns the Node being inserted. This method returns the Node being inserted. The following example (insertnodebefore_example.htm) parses an XML document (node.xml) into an XML DOM object and inserts new child Email before the specified element <Email>. <!DOCTYPE html> <html> <head> <script> function loadXMLDoc(filename) { if (window.XMLHttpRequest) { xhttp = new XMLHttpRequest(); } else // code for IE5 and IE6 { xhttp = new ActiveXObject("Microsoft.XMLHTTP"); } xhttp.open("GET",filename,false); xhttp.send(); return xhttp.responseXML; } </script> </head> <body> <script> xmlDoc = loadXMLDoc("/dom/node.xml"); create_e = xmlDoc.createElement("Email"); x = xmlDoc.documentElement; y = xmlDoc.getElementsByTagName("Email"); document.write("No of Email elements before inserting was: " + y.length); document.write("<br>"); x.insertBefore(create_e,y[3]); y=xmlDoc.getElementsByTagName("Email"); document.write("No of Email elements after inserting is: " + y.length); </script> </body> </html> In the above example − using the method createElement(), a new element Email is created. using the method createElement(), a new element Email is created. The new element Email is added before the element Email using the method insertBefore(). The new element Email is added before the element Email using the method insertBefore(). y.length gives the total number of elements added before and after the new element. y.length gives the total number of elements added before and after the new element. Save this file as insertnodebefore_example.htm on the server path (this file and node.xml should be on the same path in your server). We will receive the following output − No of Email elements before inserting was: 3 No of Email elements after inserting is: 4 The method insertData(), inserts a string at the specified 16-bit unit offset. The insertData() has the following syntax − void insertData(int offset, java.lang.String arg) throws DOMException Where, offset − is the character offset at which to insert. offset − is the character offset at which to insert. arg − is the key word to insert the data. It encloses the two parameters offset and string within the parenthesis separated by comma. arg − is the key word to insert the data. It encloses the two parameters offset and string within the parenthesis separated by comma. The following example (addtext_example.htm) parses an XML document ("node.xml") into an XML DOM object and inserts new data MiddleName at the specified position to the element <FirstName>. <!DOCTYPE html> <html> <head> <script> function loadXMLDoc(filename) { if (window.XMLHttpRequest) { xhttp = new XMLHttpRequest(); } else // code for IE5 and IE6 { xhttp = new ActiveXObject("Microsoft.XMLHTTP"); } xhttp.open("GET",filename,false); xhttp.send(); return xhttp.responseXML; } </script> </head> <body> <script> xmlDoc = loadXMLDoc("/dom/node.xml"); x = xmlDoc.getElementsByTagName("FirstName")[0].childNodes[0]; document.write(x.nodeValue); x.insertData(6,"MiddleName"); document.write("<br>"); document.write(x.nodeValue); </script> </body> </html> x.insertData(6,"MiddleName"); − Here, x holds the name of the specified child name, i.e, <FirstName>. We then insert to this text node the data "MiddleName" starting from position 6. x.insertData(6,"MiddleName"); − Here, x holds the name of the specified child name, i.e, <FirstName>. We then insert to this text node the data "MiddleName" starting from position 6. Save this file as addtext_example.htm on the server path (this file and node.xml should be on the same path in your server). We will receive the following in the output − Tanmay TanmayMiddleName In this chapter, we will study about the replace node operation in an XML DOM object. As we know everything in the DOM is maintained in a hierarchical informational unit known as node and the replacing node provides another way to update these specified nodes or a text node. Following are the two methods to replace the nodes. replaceChild() replaceData() The method replaceChild() replaces the specified node with the new node. The insertData() has the following syntax − Node replaceChild(Node newChild, Node oldChild) throws DOMException Where, newChild − is the new node to put in the child list. newChild − is the new node to put in the child list. oldChild − is the node being replaced in the list. oldChild − is the node being replaced in the list. This method returns the node replaced. This method returns the node replaced. The following example (replacenode_example.htm) parses an XML document (node.xml) into an XML DOM object and replaces the specified node <FirstName> with the new node <Name>. <!DOCTYPE html> <html> <head> <script> function loadXMLDoc(filename) { if (window.XMLHttpRequest) { xhttp = new XMLHttpRequest(); } else // code for IE5 and IE6 { xhttp = new ActiveXObject("Microsoft.XMLHTTP"); } xhttp.open("GET",filename,false); xhttp.send(); return xhttp.responseXML; } </script> </head> <body> <script> xmlDoc = loadXMLDoc("/dom/node.xml"); x = xmlDoc.documentElement; z = xmlDoc.getElementsByTagName("FirstName"); document.write("<b>Content of FirstName element before replace operation</b><br>"); for (i=0;i<z.length;i++) { document.write(z[i].childNodes[0].nodeValue); document.write("<br>"); } //create a Employee element, FirstName element and a text node newNode = xmlDoc.createElement("Employee"); newTitle = xmlDoc.createElement("Name"); newText = xmlDoc.createTextNode("MS Dhoni"); //add the text node to the title node, newTitle.appendChild(newText); //add the title node to the book node newNode.appendChild(newTitle); y = xmlDoc.getElementsByTagName("Employee")[0] //replace the first book node with the new node x.replaceChild(newNode,y); z = xmlDoc.getElementsByTagName("FirstName"); document.write("<b>Content of FirstName element after replace operation</b><br>"); for (i = 0;i<z.length;i++) { document.write(z[i].childNodes[0].nodeValue); document.write("<br>"); } </script> </body> </html> Save this file as replacenode_example.htm on the server path (this file and node.xml should be on the same path in your server). We will get the output as shown below − Content of FirstName element before replace operation Tanmay Taniya Tanisha Content of FirstName element after replace operation Taniya Tanisha The method replaceData() replaces the characters starting at the specified 16-bit unit offset with the specified string. The replaceData() has the following syntax − void replaceData(int offset, int count, java.lang.String arg) throws DOMException Where offset − is the offset from which to start replacing. offset − is the offset from which to start replacing. count − is the number of 16-bit units to replace. If the sum of offset and count exceeds length, then all the 16-bit units to the end of the data are replaced. count − is the number of 16-bit units to replace. If the sum of offset and count exceeds length, then all the 16-bit units to the end of the data are replaced. arg − the DOMString with which the range must be replaced. arg − the DOMString with which the range must be replaced. The following example (replacedata_example.htm) parses an XML document (node.xml) into an XML DOM object and replaces it. <!DOCTYPE html> <html> <head> <script> function loadXMLDoc(filename) { if (window.XMLHttpRequest) { xhttp = new XMLHttpRequest(); } else // code for IE5 and IE6 { xhttp = new ActiveXObject("Microsoft.XMLHTTP"); } xhttp.open("GET",filename,false); xhttp.send(); return xhttp.responseXML; } </script> </head> <body> <script> xmlDoc = loadXMLDoc("/dom/node.xml"); x = xmlDoc.getElementsByTagName("ContactNo")[0].childNodes[0]; document.write("<b>ContactNo before replace operation:</b> "+x.nodeValue); x.replaceData(1,5,"9999999"); document.write("<br>"); document.write("<b>ContactNo after replace operation:</b> "+x.nodeValue); </script> </body> </html> In the above example − x.replaceData(2,3,"999"); − Here x holds the text of the specified element <ContactNo> whose text is replaced by the new text "9999999", starting from the position 1 till the length of 5. x.replaceData(2,3,"999"); − Here x holds the text of the specified element <ContactNo> whose text is replaced by the new text "9999999", starting from the position 1 till the length of 5. Save this file as replacedata_example.htm on the server path (this file and node.xml should be on the same path in your server). We will get the output as shown below − ContactNo before replace operation: 1234567890 ContactNo after replace operation: 199999997890 In this chapter, we will study about the XML DOM Remove Node operation. The remove node operation removes the specified node from the document. This operation can be implemented to remove the nodes like text node, element node or an attribute node. Following are the methods that are used for remove node operation − removeChild() removeChild() removeAttribute() removeAttribute() The method removeChild() removes the child node indicated by oldChild from the list of children, and returns it. Removing a child node is equivalent to removing a text node. Hence, removing a child node removes the text node associated with it. The syntax to use removeChild() is as follows − Node removeChild(Node oldChild) throws DOMException Where, oldChild − is the node being removed. oldChild − is the node being removed. This method returns the node removed. This method returns the node removed. The following example (removecurrentnode_example.htm) parses an XML document (node.xml) into an XML DOM object and removes the specified node <ContactNo> from the parent node. <!DOCTYPE html> <html> <head> <script> function loadXMLDoc(filename) { if (window.XMLHttpRequest) { xhttp = new XMLHttpRequest(); } else // code for IE5 and IE6 { xhttp = new ActiveXObject("Microsoft.XMLHTTP"); } xhttp.open("GET",filename,false); xhttp.send(); return xhttp.responseXML; } </script> </head> <body> <script> xmlDoc = loadXMLDoc("/dom/node.xml"); document.write("<b>Before remove operation, total ContactNo elements: </b>"); document.write(xmlDoc.getElementsByTagName("ContactNo").length); document.write("<br>"); x = xmlDoc.getElementsByTagName("ContactNo")[0]; x.parentNode.removeChild(x); document.write("<b>After remove operation, total ContactNo elements: </b>"); document.write(xmlDoc.getElementsByTagName("ContactNo").length); </script> </body> </html> In the above example − x = xmlDoc.getElementsByTagName("ContactNo")[0] gets the element <ContactNo> indexed at 0. x = xmlDoc.getElementsByTagName("ContactNo")[0] gets the element <ContactNo> indexed at 0. x.parentNode.removeChild(x); removes the element <ContactNo> indexed at 0 from the parent node. x.parentNode.removeChild(x); removes the element <ContactNo> indexed at 0 from the parent node. Save this file as removecurrentnode_example.htm on the server path (this file and node.xml should be on the same path in your server). We get the following result − Before remove operation, total ContactNo elements: 3 After remove operation, total ContactNo elements: 2 The following example (removetextNode_example.htm) parses an XML document (node.xml) into an XML DOM object and removes the specified child node <FirstName>. <!DOCTYPE html> <html> <head> <script> function loadXMLDoc(filename) { if (window.XMLHttpRequest) { xhttp = new XMLHttpRequest(); } else // code for IE5 and IE6 { xhttp = new ActiveXObject("Microsoft.XMLHTTP"); } xhttp.open("GET",filename,false); xhttp.send(); return xhttp.responseXML; } </script> </head> <body> <script> xmlDoc = loadXMLDoc("/dom/node.xml"); x = xmlDoc.getElementsByTagName("FirstName")[0]; document.write("<b>Text node of child node before removal is:</b> "); document.write(x.childNodes.length); document.write("<br>"); y = x.childNodes[0]; x.removeChild(y); document.write("<b>Text node of child node after removal is:</b> "); document.write(x.childNodes.length); </script> </body> </html> In the above example − x = xmlDoc.getElementsByTagName("FirstName")[0]; − gets the first element <FirstName> to the x indexed at 0. x = xmlDoc.getElementsByTagName("FirstName")[0]; − gets the first element <FirstName> to the x indexed at 0. y = x.childNodes[0]; − in this line y holds the child node to be remove. y = x.childNodes[0]; − in this line y holds the child node to be remove. x.removeChild(y); − removes the specified child node. x.removeChild(y); − removes the specified child node. Save this file as removetextNode_example.htm on the server path (this file and node.xml should be on the same path in your server). We get the following result − Text node of child node before removal is: 1 Text node of child node after removal is: 0 The method removeAttribute() removes an attribute of an element by name. Syntax to use removeAttribute() is as follows − void removeAttribute(java.lang.String name) throws DOMException Where, name − is the name of the attribute to remove. name − is the name of the attribute to remove. The following example (removeelementattribute_example.htm) parses an XML document (node.xml) into an XML DOM object and removes the specified attribute node. <!DOCTYPE html> <html> <head> <script> function loadXMLDoc(filename) { if (window.XMLHttpRequest) { xhttp = new XMLHttpRequest(); } else // code for IE5 and IE6 { xhttp = new ActiveXObject("Microsoft.XMLHTTP"); } xhttp.open("GET",filename,false); xhttp.send(); return xhttp.responseXML; } </script> </head> <body> <script> xmlDoc = loadXMLDoc("/dom/node.xml"); x = xmlDoc.getElementsByTagName('Employee'); document.write(x[1].getAttribute('category')); document.write("<br>"); x[1].removeAttribute('category'); document.write(x[1].getAttribute('category')); </script> </body> </html> In the above example − document.write(x[1].getAttribute('category')); − value of attribute category indexed at 1st position is invoked. document.write(x[1].getAttribute('category')); − value of attribute category indexed at 1st position is invoked. x[1].removeAttribute('category'); − removes the attribute value. x[1].removeAttribute('category'); − removes the attribute value. Save this file as removeelementattribute_example.htm on the server path (this file and node.xml should be on the same path in your server). We get the following result − Non-Technical null In this chapter, we will discucss the Clone Node operation on XML DOM object. Clone node operation is used to create a duplicate copy of the specified node. cloneNode() is used for this operation. This method returns a duplicate of this node, i.e., serves as a generic copy constructor for nodes. The duplicate node has no parent ( parentNode is null) and no user data. The cloneNode() method has the following syntax − Node cloneNode(boolean deep) deep − If true, recursively clones the subtree under the specified node; if false, clone only the node itself (and its attributes, if it is an Element). deep − If true, recursively clones the subtree under the specified node; if false, clone only the node itself (and its attributes, if it is an Element). This method returns the duplicate node. This method returns the duplicate node. The following example (clonenode_example.htm) parses an XML document (node.xml) into an XML DOM object and creates a deep copy of the first Employee element. <!DOCTYPE html> <html> <head> <script> function loadXMLDoc(filename) { if (window.XMLHttpRequest) { xhttp = new XMLHttpRequest(); } else // code for IE5 and IE6 { xhttp = new ActiveXObject("Microsoft.XMLHTTP"); } xhttp.open("GET",filename,false); xhttp.send(); return xhttp.responseXML; } </script> </head> <body> <script> xmlDoc = loadXMLDoc("/dom/node.xml"); x = xmlDoc.getElementsByTagName('Employee')[0]; clone_node = x.cloneNode(true); xmlDoc.documentElement.appendChild(clone_node); firstname = xmlDoc.getElementsByTagName("FirstName"); lastname = xmlDoc.getElementsByTagName("LastName"); contact = xmlDoc.getElementsByTagName("ContactNo"); email = xmlDoc.getElementsByTagName("Email"); for (i = 0;i < firstname.length;i++) { document.write(firstname[i].childNodes[0].nodeValue+' '+lastname[i].childNodes[0].nodeValue+', '+contact[i].childNodes[0].nodeValue+', '+email[i].childNodes[0].nodeValue); document.write("<br>"); } </script> </body> </html> As you can see in the above example, we have set the cloneNode() param to true. Hence each of the child element under the Employee element is copied or cloned. Save this file as clonenode_example.htm on the server path (this file and node.xml should be on the same path in your server). We will get the output as shown below − Tanmay Patil, 1234567890, [email protected] Taniya Mishra, 1234667898, [email protected] Tanisha Sharma, 1234562350, [email protected] Tanmay Patil, 1234567890, [email protected] You will notice that the first Employee element is cloned completely. Node interface is the primary datatype for the entire Document Object Model. The node is used to represent a single XML element in the entire document tree. A node can be any type that is an attribute node, a text node or any other node. The attributes nodeName, nodeValue and attributes are included as a mechanism to get at node information without casting down to the specific derived interface. The following table lists the attributes of the Node object − We have listed the node types as below − ELEMENT_NODE ATTRIBUTE_NODE ENTITY_NODE ENTITY_REFERENCE_NODE DOCUMENT_FRAGMENT_NODE TEXT_NODE CDATA_SECTION_NODE COMMENT_NODE PROCESSING_INSTRUCTION_NODE DOCUMENT_NODE DOCUMENT_TYPE_NODE NOTATION_NODE Below table lists the different Node Object methods − This method adds a node after the last child node of the specified element node. It returns the added node. This method is used to create a duplicate node, when overridden in a derived class. It returns the duplicated node. This method is used to compare the position of the current node against a specified node according to the document order. Returns unsigned short, how the node is positioned relatively to the reference node. getFeature(DOMString feature, DOMString version) Returns the DOM Object which implements the specialized APIs of the specified feature and version, if any, or null if there is no object. This has been removed. Refer specs. getUserData(DOMString key) Retrieves the object associated to a key on this node. The object must first have been set to this node by calling the setUserData with the same key. Returns the DOMUserData associated to the given key on this node, or null if there was none. This has been removed. Refer specs. hasAttributes() Returns whether this node (if it is an element) has any attributes or not. Returns true if any attribute is present in the specified node else returns false. This has been removed. Refer specs. Returns whether this node has any children. This method returns true if the current node has child nodes otherwise false. This method is used to insert a new node as a child of this node, directly before an existing child of this node. It returns the node being inserted. This method accepts a namespace URI as an argument and returns a Boolean with a value of true if the namespace is the default namespace on the given node or false if not. This method tests whether two nodes are equal. Returns true if the nodes are equal, false otherwise. isSameNode(Node other) This method returns whether current node is the same node as the given one. Returns true if the nodes are the same, false otherwise. This has been removed. Refer specs. isSupported(DOMString feature, DOMString version) This method returns whether the specified DOM module is supported by the current node. Returns true if the specified feature is supported on this node, false otherwise. This has been removed. Refer specs. This method gets the URI of the namespace associated with the namespace prefix. This method returns the closest prefix defined in the current namespace for the namespace URI. Returns an associated namespace prefix if found or null if none is found. Normalization adds all the text nodes including attribute nodes which define a normal form where structure of the nodes which contain elements, comments, processing instructions, CDATA sections, and entity references separates the text nodes, i.e, neither adjacent Text nodes nor empty Text nodes. This method is used to remove a specified child node from the current node. This returns the node removed. This method is used to replace the old child node with a new node. This returns the node replaced. setUserData(DOMString key, DOMUserData data, UserDataHandler handler) This method associates an object to a key on this node. The object can later be retrieved from this node by calling getUserData with the same key. This returns the DOMUserData previously associated to the given key on this node. This has been removed. Refer specs. The NodeList object specifies the abstraction of an ordered collection of nodes. The items in the NodeList are accessible via an integral index, starting from 0. The following table lists the attributes of the NodeList object − The following is the only method of the NodeList object. It returns the indexth item in the collection. If index is greater than or equal to the number of nodes in the list, this returns null. The NamedNodeMap object is used to represent collections of nodes that can be accessed by name. The following table lists the Property of the NamedNodeMap Object. The following table lists the methods of the NamedNodeMap object. Retrieves the node specified by name. Retrieves a node specified by local name and namespace URI. Returns the indexth item in the map. If index is greater than or equal to the number of nodes in this map, this returns null. Removes a node specified by name. Removes a node specified by local name and namespace URI. Adds a node using its nodeName attribute. If a node with that name is already present in this map, it is replaced by the new one. Adds a node using its namespaceURI and localName. If a node with that namespace URI and that local name is already present in this map, it is replaced by the new one. Replacing a node by itself has no effect. The DOMImplementation object provides a number of methods for performing operations that are independent of any particular instance of the document object model. Following table lists the methods of the DOMImplementation object − It creates a DOM Document object of the specified type with its document element. It creates an empty DocumentType node. getFeature(feature, version) This method returns a specialized object which implements the specialized APIs of the specified feature and version. This has been removed. Refer specs. This method tests if the DOM implementation implements a specific feature and version. The DocumentType objects are the key to access the document's data and in the document, the doctype attribute can have either the null value or the DocumentType Object value. These DocumentType objects act as an interface to the entities described for an XML document. The following table lists the attributes of the DocumentType object − DocumentType inherits methods from its parent, Node, and implements the ChildNode interface. ProcessingInstruction gives that application-specific information which is generally included in the prolog section of the XML document. Processing instructions (PIs) can be used to pass information to applications. PIs can appear anywhere in the document outside the markup. They can appear in the prolog, including the document type definition (DTD), in textual content, or after the document. A PI starts with a special tag <? and ends with ?>. Processing of the contents ends immediately after the string ?> is encountered. The following table lists the attributes of the ProcessingInstruction object − Entity interface represents a known entity, either parsed or unparsed, in an XML document. The nodeName attribute that is inherited from Node contains the name of the entity. An Entity object does not have any parent node, and all its successor nodes are read-only. The following table lists the attributes of the Entity object − The EntityReference objects are the general entity references which are inserted into the XML document providing scope to replace the text. The EntityReference Object does not work for the pre-defined entities since they are considered to be expanded by the HTML or the XML processor. This interface does not have properties or methods of its own but inherits from Node. In this chapter, we will study about the XML DOM Notation object. The notation object property provides a scope to recognize the format of elements with a notation attribute, a particular processing instruction or a non-XML data. The Node Object properties and methods can be performed on the Notation Object since that is also considered as a Node. This object inherits methods and properties from Node. Its nodeName is the notation name. Has no parent. The following table lists the attributes of the Notation object − The XML elements can be defined as building blocks of XML. Elements can behave as containers to hold text, elements, attributes, media objects or all of these. Whenever parser parses an XML document against the well-formedness, parser navigates through an element node. An element node contains the text within it which is called as the text node. Element object inherits the properties and the methods of the Node object as element object is also considered as a Node. Other than the node object properties and methods it has the following properties and methods. The following table lists the attributes of the Element object − Below table lists the Element Object methods − Attr interface represents an attribute in an Element object. Typically, the allowable values for the attribute are defined in a schema associated with the document. Attr objects are not considered as part of the document tree since they are not actually child nodes of the element they describe. Thus for the child nodes parentNode, previousSibling and nextSibling the attribute value is null. The following table lists the attributes of the Attribute object − In this chapter, we will study about the XML DOM CDATASection Object. The text present within an XML document is parsed or unparsed depending on what it is declared. If the text is declared as Parse Character Data (PCDATA), it is parsed by the parser to convert an XML document into an XML DOM Object. On the other hand, if the text is declared as the unparsed Character Data (CDATA) the text within is not parsed by the XML parser. These are not considered as the markup and will not expand the entities. The purpose of using the CDATASection object is to escape the blocks of text containing characters that would otherwise be regarded as markup. "]]>", this is the only delimiter recognized in a CDATA section that ends the CDATA section. The CharacterData.data attribute holds the text that is contained by the CDATA section. This interface inherits the CharatcterData interface through the Text interface. In this chapter, we will study about the Comment object. Comments are added as a notes or the lines for understanding the purpose of an XML code. Comments can be used to include related links, information and terms. These may appear anywhere in the XML code. The comment interface inherits the CharacterData interface representing the content of the comment. XML comment has the following syntax − <!-------Your comment-----> A comment starts with <!-- and ends with -->. You can add textual notes as comments between the characters. You must not nest one comment inside the other. XMLHttpRequest object establishes a medium between a web page's client-side and server-side that can be used by the many scripting languages like JavaScript, JScript, VBScript and other web browser to transfer and manipulate the XML data. With the XMLHttpRequest object it is possible to update the part of a web page without reloading the whole page, request and receive the data from a server after the page has been loaded and send the data to the server. An XMLHttpRequest object can be instatiated as follows − xmlhttp = new XMLHttpRequest(); To handle all browsers, including IE5 and IE6, check if the browser supports the XMLHttpRequest object as below − if(window.XMLHttpRequest) // for Firefox, IE7+, Opera, Safari, ... { xmlHttp = new XMLHttpRequest(); } else if(window.ActiveXObject) // for Internet Explorer 5 or 6 { xmlHttp = new ActiveXObject("Microsoft.XMLHTTP"); } Examples to load an XML file using the XMLHttpRequest object can be referred here The following table lists the methods of the XMLHttpRequest object − abort() Terminates the current request made. getAllResponseHeaders() Returns all the response headers as a string, or null if no response has been received. getResponseHeader() Returns the string containing the text of the specified header, or null if either the response has not yet been received or the header doesn't exist in the response. open(method,url,async,uname,pswd) It is used in conjugation with the Send method to send the request to the server. The open method specifies the following parameters − method − specifies the type of request i.e. Get or Post. method − specifies the type of request i.e. Get or Post. url − it is the location of the file. url − it is the location of the file. async − indicates how the request should be handled. It is boolean value. where, 'true' means the request is processed asynchronously without waiting for a Http response. 'false' means the request is processed synchronously after receiving the Http response. async − indicates how the request should be handled. It is boolean value. where, 'true' means the request is processed asynchronously without waiting for a Http response. 'true' means the request is processed asynchronously without waiting for a Http response. 'false' means the request is processed synchronously after receiving the Http response. 'false' means the request is processed synchronously after receiving the Http response. uname − is the username. uname − is the username. pswd − is the password. pswd − is the password. send(string) It is used to send the request working in conjugation with the Open method. setRequestHeader() Header contains the label/value pair to which the request is sent. The following table lists the attributes of the XMLHttpRequest object − onreadystatechange It is an event based property which is set on at every state change. readyState This describes the present state of the XMLHttpRequest object. There are five possible states of the readyState property − readyState = 0 − means request is yet to initialize. readyState = 0 − means request is yet to initialize. readyState = 1 − request is set. readyState = 1 − request is set. readyState = 2 − request is sent. readyState = 2 − request is sent. readyState = 3 − request is processing. readyState = 3 − request is processing. readyState = 4 − request is completed. readyState = 4 − request is completed. responseText This property is used when the response from the server is a text file. responseXML This property is used when the response from the server is an XML file. status statusText Gives the status of the Http request object as a string. For example, "Not Found" or "OK". node.xml contents are as below − <?xml version = "1.0"?> <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> Following example demonstrates how to retrive specific information of a resource file using the method getResponseHeader() and the property readState. <!DOCTYPE html> <html> <head> <meta http-equiv = "content-type" content = "text/html; charset = iso-8859-2" /> <script> function loadXMLDoc() { var xmlHttp = null; if(window.XMLHttpRequest) // for Firefox, IE7+, Opera, Safari, ... { xmlHttp = new XMLHttpRequest(); } else if(window.ActiveXObject) // for Internet Explorer 5 or 6 { xmlHttp = new ActiveXObject("Microsoft.XMLHTTP"); } return xmlHttp; } function makerequest(serverPage, myDiv) { var request = loadXMLDoc(); request.open("GET", serverPage); request.send(null); request.onreadystatechange = function() { if (request.readyState == 4) { document.getElementById(myDiv).innerHTML = request.getResponseHeader("Content-length"); } } } </script> </head> <body> <button type = "button" onclick="makerequest('/dom/node.xml', 'ID')">Click me to get the specific ResponseHeader</button> <div id = "ID">Specific header information is returned.</div> </body> </html> Save this file as elementattribute_removeAttributeNS.htm on the server path (this file and node_ns.xml should be on the same path in your server). We will get the output as shown below − Before removing the attributeNS: en After removing the attributeNS: null Following example demonstrates how to retrieve the header information of a resource file, using the method getAllResponseHeaders() using the property readyState. <!DOCTYPE html> <html> <head> <meta http-equiv="content-type" content="text/html; charset=iso-8859-2" /> <script> function loadXMLDoc() { var xmlHttp = null; if(window.XMLHttpRequest) // for Firefox, IE7+, Opera, Safari, ... { xmlHttp = new XMLHttpRequest(); } else if(window.ActiveXObject) // for Internet Explorer 5 or 6 { xmlHttp = new ActiveXObject("Microsoft.XMLHTTP"); } return xmlHttp; } function makerequest(serverPage, myDiv) { var request = loadXMLDoc(); request.open("GET", serverPage); request.send(null); request.onreadystatechange = function() { if (request.readyState == 4) { document.getElementById(myDiv).innerHTML = request.getAllResponseHeaders(); } } } </script> </head> <body> <button type = "button" onclick = "makerequest('/dom/node.xml', 'ID')"> Click me to load the AllResponseHeaders</button> <div id = "ID"></div> </body> </html> Save this file as http_allheader.html on the server path (this file and node.xml should be on the same path in your server). We will get the output as shown below (depends on the browser) − Date: Sat, 27 Sep 2014 07:48:07 GMT Server: Apache Last-Modified: Wed, 03 Sep 2014 06:35:30 GMT Etag: "464bf9-2af-50223713b8a60" Accept-Ranges: bytes Vary: Accept-Encoding,User-Agent Content-Encoding: gzip Content-Length: 256 Content-Type: text/xml The DOMException represents an abnormal event happening when a method or a property is used. Below table lists the properties of the DOMException object name Returns a DOMString that contains one of the string associated with an error constant (as seen the table below). IndexSizeError The index is not in the allowed range. For example, this can be thrown by the Range object. (Legacy code value: 1 and legacy constant name: INDEX_SIZE_ERR) HierarchyRequestError The node tree hierarchy is not correct. (Legacy code value: 3 and legacy constant name: HIERARCHY_REQUEST_ERR) WrongDocumentError The object is in the wrong document. (Legacy code value: 4 and legacy constant name: WRONG_DOCUMENT_ERR) InvalidCharacterError The string contains invalid characters. (Legacy code value: 5 and legacy constant name: INVALID_CHARACTER_ERR) NoModificationAllowedError The object cannot be modified. (Legacy code value: 7 and legacy constant name: NO_MODIFICATION_ALLOWED_ERR) NotFoundError The object cannot be found here. (Legacy code value: 8 and legacy constant name: NOT_FOUND_ERR) NotSupportedError The operation is not supported. (Legacy code value: 9 and legacy constant name: NOT_SUPPORTED_ERR) InvalidStateError The object is in an invalid state. (Legacy code value: 11 and legacy constant name: INVALID_STATE_ERR) SyntaxError The string did not match the expected pattern. (Legacy code value: 12 and legacy constant name: SYNTAX_ERR) InvalidModificationError The object cannot be modified in this way. (Legacy code value: 13 and legacy constant name: INVALID_MODIFICATION_ERR) NamespaceError The operation is not allowed by Namespaces in XML. (Legacy code value: 14 and legacy constant name: NAMESPACE_ERR) InvalidAccessError The object does not support the operation or argument. (Legacy code value: 15 and legacy constant name: INVALID_ACCESS_ERR) TypeMismatchError The type of the object does not match the expected type. (Legacy code value: 17 and legacy constant name: TYPE_MISMATCH_ERR) This value is deprecated, the JavaScript TypeError exception is now raised instead of a DOMException with this value. SecurityError The operation is insecure. (Legacy code value: 18 and legacy constant name: SECURITY_ERR) NetworkError A network error occurred. (Legacy code value: 19 and legacy constant name: NETWORK_ERR) AbortError The operation was aborted. (Legacy code value: 20 and legacy constant name: ABORT_ERR) URLMismatchError The given URL does not match another URL. (Legacy code value: 21 and legacy constant name: URL_MISMATCH_ERR) QuotaExceededError The quota has been exceeded. (Legacy code value: 22 and legacy constant name: QUOTA_EXCEEDED_ERR) TimeoutError The operation timed out. (Legacy code value: 23 and legacy constant name: TIMEOUT_ERR) InvalidNodeTypeError The node is incorrect or has an incorrect ancestor for this operation. (Legacy code value: 24 and legacy constant name: INVALID_NODE_TYPE_ERR) DataCloneError The object cannot be cloned. (Legacy code value: 25 and legacy constant name: DATA_CLONE_ERR) EncodingError The encoding operation, being an encoding or a decoding one, failed (No legacy code value and constant name). NotReadableError The input/output read operation failed (No legacy code value and constant name). Following example demonstrates how using a not well-formed XML document causes a DOMException. error.xml contents are as below − <?xml version = "1.0" encoding = "UTF-8" standalone = "no" ?> <Company id = "companyid"> <Employee category = "Technical" id = "firstelement" type = "text/html"> <FirstName>Tanmay</first> <LastName>Patil</LastName> <ContactNo>1234567890</ContactNo> <Email>[email protected]</Email> </Employee> </Company> Following example demonstrates the usage of the name attribute − <html> <head> <script> function loadXMLDoc(filename) { if (window.XMLHttpRequest) { xhttp = new XMLHttpRequest(); } else // code for IE5 and IE6 { xhttp = new ActiveXObject("Microsoft.XMLHTTP"); } xhttp.open("GET",filename,false); xhttp.send(); return xhttp.responseXML; } </script> </head> <body> <script> try { xmlDoc = loadXMLDoc("/dom/error.xml"); var node = xmlDoc.getElementsByTagName("to").item(0); var refnode = node.nextSibling; var newnode = xmlDoc.createTextNode('That is why you fail.'); node.insertBefore(newnode, refnode); } catch(err) { document.write(err.name); } </script> </body> </html> Save this file as domexcption_name.html on the server path (this file and error.xml should be on the same path in your server). We will get the output as shown below − TypeError 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": 2404, "s": 2288, "text": "The Document Object Model (DOM) is a W3C standard. It defines a standard for accessing documents like HTML and XML." }, { "code": null, "e": 2445, "s": 2404, "text": "Definition of DOM as put by the W3C is −" }, { "code": null, "e": 2586, "s": 2445, "text": "DOM defines the objects and properties and methods (interface) to access all XML elements. It is separated into 3 different parts / levels −" }, { "code": null, "e": 2640, "s": 2586, "text": "Core DOM − standard model for any structured document" }, { "code": null, "e": 2694, "s": 2640, "text": "Core DOM − standard model for any structured document" }, { "code": null, "e": 2737, "s": 2694, "text": "XML DOM − standard model for XML documents" }, { "code": null, "e": 2780, "s": 2737, "text": "XML DOM − standard model for XML documents" }, { "code": null, "e": 2825, "s": 2780, "text": "HTML DOM − standard model for HTML documents" }, { "code": null, "e": 2870, "s": 2825, "text": "HTML DOM − standard model for HTML documents" }, { "code": null, "e": 3084, "s": 2870, "text": "XML DOM is a standard object model for XML. XML documents have a hierarchy of informational units called nodes; DOM is a standard programming interface of describing those nodes and the relationships between them." }, { "code": null, "e": 3235, "s": 3084, "text": "As XML DOM also provides an API that allows a developer to add, edit, move or remove nodes at any point on the tree in order to create an application." }, { "code": null, "e": 3393, "s": 3235, "text": "Following is the diagram for the DOM structure. The diagram depicts that parser evaluates an XML document as a DOM structure by traversing through each node." }, { "code": null, "e": 3438, "s": 3393, "text": "The following are the advantages of XML DOM." }, { "code": null, "e": 3484, "s": 3438, "text": "XML DOM is language and platform independent." }, { "code": null, "e": 3530, "s": 3484, "text": "XML DOM is language and platform independent." }, { "code": null, "e": 3696, "s": 3530, "text": "XML DOM is traversable - Information in XML DOM is organized in a hierarchy which allows developer to navigate around the hierarchy looking for specific information." }, { "code": null, "e": 3862, "s": 3696, "text": "XML DOM is traversable - Information in XML DOM is organized in a hierarchy which allows developer to navigate around the hierarchy looking for specific information." }, { "code": null, "e": 4003, "s": 3862, "text": "XML DOM is modifiable - It is dynamic in nature providing the developer a scope to add, edit, move or remove nodes at any point on the tree." }, { "code": null, "e": 4144, "s": 4003, "text": "XML DOM is modifiable - It is dynamic in nature providing the developer a scope to add, edit, move or remove nodes at any point on the tree." }, { "code": null, "e": 4292, "s": 4144, "text": "It consumes more memory (if the XML structure is large) as program written once remains in memory all the time until and unless removed explicitly." }, { "code": null, "e": 4440, "s": 4292, "text": "It consumes more memory (if the XML structure is large) as program written once remains in memory all the time until and unless removed explicitly." }, { "code": null, "e": 4528, "s": 4440, "text": "Due to the extensive usage of memory, its operational speed, compared to SAX is slower." }, { "code": null, "e": 4616, "s": 4528, "text": "Due to the extensive usage of memory, its operational speed, compared to SAX is slower." }, { "code": null, "e": 5022, "s": 4616, "text": "Now that we know what DOM means, let's see what a DOM structure is. A DOM document is a collection of nodes or pieces of information, organized in a hierarchy. Some types of nodes may have child nodes of various types and others are leaf nodes that cannot have anything under them in the document structure. Following is a list of the node types, with a list of node types that they may have as children −" }, { "code": null, "e": 5121, "s": 5022, "text": "Document − Element (maximum of one), ProcessingInstruction, Comment, DocumentType (maximum of one)" }, { "code": null, "e": 5220, "s": 5121, "text": "Document − Element (maximum of one), ProcessingInstruction, Comment, DocumentType (maximum of one)" }, { "code": null, "e": 5316, "s": 5220, "text": "DocumentFragment − Element, ProcessingInstruction, Comment, Text, CDATASection, EntityReference" }, { "code": null, "e": 5412, "s": 5316, "text": "DocumentFragment − Element, ProcessingInstruction, Comment, Text, CDATASection, EntityReference" }, { "code": null, "e": 5507, "s": 5412, "text": "EntityReference − Element, ProcessingInstruction, Comment, Text, CDATASection, EntityReference" }, { "code": null, "e": 5602, "s": 5507, "text": "EntityReference − Element, ProcessingInstruction, Comment, Text, CDATASection, EntityReference" }, { "code": null, "e": 5689, "s": 5602, "text": "Element − Element, Text, Comment, ProcessingInstruction, CDATASection, EntityReference" }, { "code": null, "e": 5776, "s": 5689, "text": "Element − Element, Text, Comment, ProcessingInstruction, CDATASection, EntityReference" }, { "code": null, "e": 5805, "s": 5776, "text": "Attr − Text, EntityReference" }, { "code": null, "e": 5834, "s": 5805, "text": "Attr − Text, EntityReference" }, { "code": null, "e": 5870, "s": 5834, "text": "ProcessingInstruction − No children" }, { "code": null, "e": 5906, "s": 5870, "text": "ProcessingInstruction − No children" }, { "code": null, "e": 5928, "s": 5906, "text": "Comment − No children" }, { "code": null, "e": 5950, "s": 5928, "text": "Comment − No children" }, { "code": null, "e": 5969, "s": 5950, "text": "Text − No children" }, { "code": null, "e": 5988, "s": 5969, "text": "Text − No children" }, { "code": null, "e": 6015, "s": 5988, "text": "CDATASection − No children" }, { "code": null, "e": 6042, "s": 6015, "text": "CDATASection − No children" }, { "code": null, "e": 6128, "s": 6042, "text": "Entity − Element, ProcessingInstruction, Comment, Text, CDATASection, EntityReference" }, { "code": null, "e": 6214, "s": 6128, "text": "Entity − Element, ProcessingInstruction, Comment, Text, CDATASection, EntityReference" }, { "code": null, "e": 6237, "s": 6214, "text": "Notation − No children" }, { "code": null, "e": 6260, "s": 6237, "text": "Notation − No children" }, { "code": null, "e": 6332, "s": 6260, "text": "Consider the DOM representation of the following XML document node.xml." }, { "code": null, "e": 6708, "s": 6332, "text": "<?xml version = \"1.0\"?>\n<Company>\n <Employee category = \"technical\">\n <FirstName>Tanmay</FirstName>\n <LastName>Patil</LastName>\n <ContactNo>1234567890</ContactNo>\n </Employee>\n \n <Employee category = \"non-technical\">\n <FirstName>Taniya</FirstName>\n <LastName>Mishra</LastName>\n <ContactNo>1234667898</ContactNo>\n </Employee>\n</Company>" }, { "code": null, "e": 6782, "s": 6708, "text": "The Document Object Model of the above XML document would be as follows −" }, { "code": null, "e": 6823, "s": 6782, "text": "From the above flowchart, we can infer −" }, { "code": null, "e": 6941, "s": 6823, "text": "Node object can have only one parent node object. This occupies the position above all the nodes. Here it is Company." }, { "code": null, "e": 7059, "s": 6941, "text": "Node object can have only one parent node object. This occupies the position above all the nodes. Here it is Company." }, { "code": null, "e": 7371, "s": 7059, "text": "The parent node can have multiple nodes called the child nodes. These child nodes can have additional nodes called the attribute nodes. In the above example, we have two attribute nodes Technical and Non-technical. The attribute node is not actually a child of the element node, but is still associated with it." }, { "code": null, "e": 7683, "s": 7371, "text": "The parent node can have multiple nodes called the child nodes. These child nodes can have additional nodes called the attribute nodes. In the above example, we have two attribute nodes Technical and Non-technical. The attribute node is not actually a child of the element node, but is still associated with it." }, { "code": null, "e": 7791, "s": 7683, "text": "These child nodes in turn can have multiple child nodes. The text within the nodes is called the text node." }, { "code": null, "e": 7899, "s": 7791, "text": "These child nodes in turn can have multiple child nodes. The text within the nodes is called the text node." }, { "code": null, "e": 7958, "s": 7899, "text": "The node objects at the same level are called as siblings." }, { "code": null, "e": 8017, "s": 7958, "text": "The node objects at the same level are called as siblings." }, { "code": null, "e": 8160, "s": 8017, "text": "The DOM identifies −\n\nthe objects to represent the interface and manipulate the document.\nthe relationship among the objects and interfaces.\n\n" }, { "code": null, "e": 8181, "s": 8160, "text": "The DOM identifies −" }, { "code": null, "e": 8249, "s": 8181, "text": "the objects to represent the interface and manipulate the document." }, { "code": null, "e": 8317, "s": 8249, "text": "the objects to represent the interface and manipulate the document." }, { "code": null, "e": 8368, "s": 8317, "text": "the relationship among the objects and interfaces." }, { "code": null, "e": 8419, "s": 8368, "text": "the relationship among the objects and interfaces." }, { "code": null, "e": 8618, "s": 8419, "text": "In this chapter, we will study about the XML DOM Nodes. Every XML DOM contains the information in hierarchical units called Nodes and the DOM describes these nodes and the relationship between them." }, { "code": null, "e": 8669, "s": 8618, "text": "The following flowchart shows all the node types −" }, { "code": null, "e": 8713, "s": 8669, "text": "The most common types of nodes in XML are −" }, { "code": null, "e": 8781, "s": 8713, "text": "Document Node − Complete XML document structure is a document node." }, { "code": null, "e": 8849, "s": 8781, "text": "Document Node − Complete XML document structure is a document node." }, { "code": null, "e": 8963, "s": 8849, "text": "Element Node − Every XML element is an element node. This is also the only type of node that can have attributes." }, { "code": null, "e": 9077, "s": 8963, "text": "Element Node − Every XML element is an element node. This is also the only type of node that can have attributes." }, { "code": null, "e": 9251, "s": 9077, "text": "Attribute Node − Each attribute is considered an attribute node. It contains information about an element node, but is not actually considered to be children of the element." }, { "code": null, "e": 9425, "s": 9251, "text": "Attribute Node − Each attribute is considered an attribute node. It contains information about an element node, but is not actually considered to be children of the element." }, { "code": null, "e": 9541, "s": 9425, "text": "Text Node − The document texts are considered as text node. It can consist of more information or just white space." }, { "code": null, "e": 9657, "s": 9541, "text": "Text Node − The document texts are considered as text node. It can consist of more information or just white space." }, { "code": null, "e": 9695, "s": 9657, "text": "Some less common types of nodes are −" }, { "code": null, "e": 9834, "s": 9695, "text": "CData Node − This node contains information that should not be analyzed by the parser. Instead, it should just be passed on as plain text." }, { "code": null, "e": 9973, "s": 9834, "text": "CData Node − This node contains information that should not be analyzed by the parser. Instead, it should just be passed on as plain text." }, { "code": null, "e": 10078, "s": 9973, "text": "Comment Node − This node includes information about the data, and is usually ignored by the application." }, { "code": null, "e": 10183, "s": 10078, "text": "Comment Node − This node includes information about the data, and is usually ignored by the application." }, { "code": null, "e": 10284, "s": 10183, "text": "Processing Instructions Node − This node contains information specifically aimed at the application." }, { "code": null, "e": 10385, "s": 10284, "text": "Processing Instructions Node − This node contains information specifically aimed at the application." }, { "code": null, "e": 10409, "s": 10385, "text": "Document Fragments Node" }, { "code": null, "e": 10433, "s": 10409, "text": "Document Fragments Node" }, { "code": null, "e": 10447, "s": 10433, "text": "Entities Node" }, { "code": null, "e": 10461, "s": 10447, "text": "Entities Node" }, { "code": null, "e": 10484, "s": 10461, "text": "Entity reference nodes" }, { "code": null, "e": 10507, "s": 10484, "text": "Entity reference nodes" }, { "code": null, "e": 10522, "s": 10507, "text": "Notations Node" }, { "code": null, "e": 10537, "s": 10522, "text": "Notations Node" }, { "code": null, "e": 10913, "s": 10537, "text": "In this chapter, we will study about the XML DOM Node Tree. In an XML document, the information is maintained in hierarchical structure; this hierarchical structure is referred to as the Node Tree. This hierarchy allows a developer to navigate around the tree looking for specific information, thus nodes are allowed to access. The content of these nodes can then be updated." }, { "code": null, "e": 11034, "s": 10913, "text": "The structure of the node tree begins with the root element and spreads out to the child elements till the lowest level." }, { "code": null, "e": 11149, "s": 11034, "text": "Following example demonstrates a simple XML document, whose node tree is structure is shown in the diagram below −" }, { "code": null, "e": 11521, "s": 11149, "text": "<?xml version = \"1.0\"?>\n<Company>\n <Employee category = \"Technical\">\n <FirstName>Tanmay</FirstName>\n <LastName>Patil</LastName>\n <ContactNo>1234567890</ContactNo>\n </Employee>\n <Employee category = \"Non-Technical\">\n <FirstName>Taniya</FirstName>\n <LastName>Mishra</LastName>\n <ContactNo>1234667898</ContactNo>\n </Employee>\n</Company>" }, { "code": null, "e": 11621, "s": 11521, "text": "As can be seen in the above example whose pictorial representation (of its DOM) is as shown below −" }, { "code": null, "e": 11794, "s": 11624, "text": "The topmost node of a tree is called the root. The root node is <Company> which in turn contains the two nodes of <Employee>. These nodes are referred to as child nodes." }, { "code": null, "e": 11964, "s": 11794, "text": "The topmost node of a tree is called the root. The root node is <Company> which in turn contains the two nodes of <Employee>. These nodes are referred to as child nodes." }, { "code": null, "e": 12093, "s": 11964, "text": "The child node <Employee> of root node <Company>, in turn consists of its own child node (<FirstName>, <LastName>, <ContactNo>)." }, { "code": null, "e": 12222, "s": 12093, "text": "The child node <Employee> of root node <Company>, in turn consists of its own child node (<FirstName>, <LastName>, <ContactNo>)." }, { "code": null, "e": 12338, "s": 12222, "text": "The two child nodes, <Employee> have attribute values Technical and Non-Technical, are referred as attribute nodes." }, { "code": null, "e": 12454, "s": 12338, "text": "The two child nodes, <Employee> have attribute values Technical and Non-Technical, are referred as attribute nodes." }, { "code": null, "e": 12506, "s": 12454, "text": "The text within every node is called the text node." }, { "code": null, "e": 12558, "s": 12506, "text": "The text within every node is called the text node." }, { "code": null, "e": 12896, "s": 12558, "text": "DOM as an API contains interfaces that represent different types of information that can be found in an XML document, such as elements and text. These interfaces include the methods and properties necessary to work with these objects. Properties define the characteristic of the node whereas methods give the way to manipulate the nodes." }, { "code": null, "e": 12951, "s": 12896, "text": "Following table lists the DOM classes and interfaces −" }, { "code": null, "e": 12969, "s": 12951, "text": "DOMImplementation" }, { "code": null, "e": 13105, "s": 12969, "text": "It provides a number of methods for performing operations that are independent of any particular instance of the document object model." }, { "code": null, "e": 13122, "s": 13105, "text": "DocumentFragment" }, { "code": null, "e": 13269, "s": 13122, "text": "It is the \"lightweight\" or \"minimal\" document object, and it (as the superclass of Document) anchors the XML/HTML tree in a full-fledged document." }, { "code": null, "e": 13278, "s": 13269, "text": "Document" }, { "code": null, "e": 13411, "s": 13278, "text": "It represents the XML document's top-level node, which provides access to all the nodes in the document, including the root element." }, { "code": null, "e": 13416, "s": 13411, "text": "Node" }, { "code": null, "e": 13440, "s": 13416, "text": "It represents XML node." }, { "code": null, "e": 13449, "s": 13440, "text": "NodeList" }, { "code": null, "e": 13497, "s": 13449, "text": "It represents a read-only list of Node objects." }, { "code": null, "e": 13510, "s": 13497, "text": "NamedNodeMap" }, { "code": null, "e": 13575, "s": 13510, "text": "It represents collections of nodes that can be accessed by name." }, { "code": null, "e": 13580, "s": 13575, "text": "Data" }, { "code": null, "e": 13674, "s": 13580, "text": "It extends Node with a set of attributes and methods for accessing character data in the DOM." }, { "code": null, "e": 13684, "s": 13674, "text": "Attribute" }, { "code": null, "e": 13733, "s": 13684, "text": "It represents an attribute in an Element object." }, { "code": null, "e": 13741, "s": 13733, "text": "Element" }, { "code": null, "e": 13792, "s": 13741, "text": "It represents the element node. Derives from Node." }, { "code": null, "e": 13797, "s": 13792, "text": "Text" }, { "code": null, "e": 13854, "s": 13797, "text": "It represents the text node. Derives from CharacterData." }, { "code": null, "e": 13862, "s": 13854, "text": "Comment" }, { "code": null, "e": 13922, "s": 13862, "text": "It represents the comment node. Derives from CharacterData." }, { "code": null, "e": 13944, "s": 13922, "text": "ProcessingInstruction" }, { "code": null, "e": 14081, "s": 13944, "text": "It represents a \"processing instruction\". It is used in XML as a way to keep processor-specific information in the text of the document." }, { "code": null, "e": 14095, "s": 14081, "text": "CDATA Section" }, { "code": null, "e": 14147, "s": 14095, "text": "It represents the CDATA Section. Derives from Text." }, { "code": null, "e": 14154, "s": 14147, "text": "Entity" }, { "code": null, "e": 14198, "s": 14154, "text": "It represents an entity. Derives from Node." }, { "code": null, "e": 14214, "s": 14198, "text": "EntityReference" }, { "code": null, "e": 14281, "s": 14214, "text": "This represent an entity reference in the tree. Derives from Node." }, { "code": null, "e": 14343, "s": 14281, "text": "In this chapter, we will study about XML Loading and Parsing." }, { "code": null, "e": 14638, "s": 14343, "text": "In order to describe the interfaces provided by the API, the W3C uses an abstract language called the Interface Definition Language (IDL). The advantage of using IDL is that the developer learns how to use the DOM with his or her favorite language and can switch easily to a different language." }, { "code": null, "e": 15007, "s": 14638, "text": "The disadvantage is that, since it is abstract, the IDL cannot be used directly by Web developers. Due to the differences between programming languages, they need to have mapping — or binding — between the abstract interfaces and their concrete languages. DOM has been mapped to programming languages such as Javascript, JScript, Java, C, C++, PLSQL, Python, and Perl." }, { "code": null, "e": 15221, "s": 15007, "text": "A parser is a software application that is designed to analyze a document, in our case XML document and do something specific with the information. Some of the DOM based parsers are listed in the following table −" }, { "code": null, "e": 15226, "s": 15221, "text": "JAXP" }, { "code": null, "e": 15276, "s": 15226, "text": "Sun Microsystem’s Java API for XML Parsing (JAXP)" }, { "code": null, "e": 15282, "s": 15276, "text": "XML4J" }, { "code": null, "e": 15316, "s": 15282, "text": "IBM’s XML Parser for Java (XML4J)" }, { "code": null, "e": 15322, "s": 15316, "text": "msxml" }, { "code": null, "e": 15401, "s": 15322, "text": "Microsoft’s XML parser (msxml) version 2.0 is built-into Internet Explorer 5.5" }, { "code": null, "e": 15406, "s": 15401, "text": "4DOM" }, { "code": null, "e": 15459, "s": 15406, "text": "4DOM is a parser for the Python programming language" }, { "code": null, "e": 15468, "s": 15459, "text": "XML::DOM" }, { "code": null, "e": 15533, "s": 15468, "text": "XML::DOM is a Perl module to manipulate XML documents using Perl" }, { "code": null, "e": 15540, "s": 15533, "text": "Xerces" }, { "code": null, "e": 15568, "s": 15540, "text": "Apache’s Xerces Java Parser" }, { "code": null, "e": 15731, "s": 15568, "text": "In a tree-based API like DOM, the parser traverses the XML file and creates the corresponding DOM objects. Then you can traverse the DOM structure back and forth." }, { "code": null, "e": 15802, "s": 15731, "text": "While loading an XML document, the XML content can come in two forms −" }, { "code": null, "e": 15823, "s": 15802, "text": "Directly as XML file" }, { "code": null, "e": 15837, "s": 15823, "text": "As XML string" }, { "code": null, "e": 16108, "s": 15837, "text": "Following example demonstrates how to load XML (node.xml) data using Ajax and Javascript when the XML content is received as an XML file. Here, the Ajax function gets the content of an xml file and stores it in XML DOM. Once the DOM object is created, it is then parsed." }, { "code": null, "e": 17671, "s": 16108, "text": "<!DOCTYPE html>\n<html>\n <body>\n <div>\n <b>FirstName:</b> <span id = \"FirstName\"></span><br>\n <b>LastName:</b> <span id = \"LastName\"></span><br>\n <b>ContactNo:</b> <span id = \"ContactNo\"></span><br>\n <b>Email:</b> <span id = \"Email\"></span>\n </div>\n <script>\n //if browser supports XMLHttpRequest\n \n if (window.XMLHttpRequest) { // Create an instance of XMLHttpRequest object. \n code for IE7+, Firefox, Chrome, Opera, Safari xmlhttp = new XMLHttpRequest();\n } else { // code for IE6, IE5 \n xmlhttp = new ActiveXObject(\"Microsoft.XMLHTTP\");\n }\n \n // sets and sends the request for calling \"node.xml\"\n xmlhttp.open(\"GET\",\"/dom/node.xml\",false);\n xmlhttp.send();\n\n // sets and returns the content as XML DOM\n xmlDoc = xmlhttp.responseXML;\n\n //parsing the DOM object\n document.getElementById(\"FirstName\").innerHTML = \n xmlDoc.getElementsByTagName(\"FirstName\")[0].childNodes[0].nodeValue;\n document.getElementById(\"LastName\").innerHTML = \n xmlDoc.getElementsByTagName(\"LastName\")[0].childNodes[0].nodeValue;\n document.getElementById(\"ContactNo\").innerHTML = \n xmlDoc.getElementsByTagName(\"ContactNo\")[0].childNodes[0].nodeValue;\n document.getElementById(\"Email\").innerHTML = \n xmlDoc.getElementsByTagName(\"Email\")[0].childNodes[0].nodeValue;\n </script>\n </body>\n</html>" }, { "code": null, "e": 18359, "s": 17671, "text": "<Company> \n <Employee category = \"Technical\" id = \"firstelement\"> \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": 18415, "s": 18359, "text": "Most of the details of the code are in the script code." }, { "code": null, "e": 18573, "s": 18415, "text": "Internet Explorer uses the ActiveXObject(\"Microsoft.XMLHTTP\") to create an instance of XMLHttpRequest object, other browsers use the XMLHttpRequest() method." }, { "code": null, "e": 18731, "s": 18573, "text": "Internet Explorer uses the ActiveXObject(\"Microsoft.XMLHTTP\") to create an instance of XMLHttpRequest object, other browsers use the XMLHttpRequest() method." }, { "code": null, "e": 18795, "s": 18731, "text": "the responseXML transforms the XML content directly in XML DOM." }, { "code": null, "e": 18859, "s": 18795, "text": "the responseXML transforms the XML content directly in XML DOM." }, { "code": null, "e": 19135, "s": 18859, "text": "Once the XML content is transformed into JavaScript XML DOM, you can access any XML element by using the JS DOM methods and properties. We have used the DOM properties such as childNodes, nodeValue and DOM methods such as getElementsById(ID), getElementsByTagName(tags_name)." }, { "code": null, "e": 19411, "s": 19135, "text": "Once the XML content is transformed into JavaScript XML DOM, you can access any XML element by using the JS DOM methods and properties. We have used the DOM properties such as childNodes, nodeValue and DOM methods such as getElementsById(ID), getElementsByTagName(tags_name)." }, { "code": null, "e": 19518, "s": 19411, "text": "Save this file as loadingexample.html and open it in your browser. You will receive the following output −" }, { "code": null, "e": 19771, "s": 19518, "text": "Following example demonstrates how to load XML data using Ajax and Javascript when XML content is received as XML file. Here, the Ajax function, gets the content of an xml file and stores it in XML DOM. Once the DOM object is created it is then parsed." }, { "code": null, "e": 21235, "s": 19771, "text": "<!DOCTYPE html>\n<html>\n <head>\n <script>\n \n // loads the xml string in a dom object\n function loadXMLString(t) { // for non IE browsers\n if (window.DOMParser) {\n // create an instance for xml dom object parser = new DOMParser();\n xmlDoc = parser.parseFromString(t,\"text/xml\");\n }\n // code for IE\n else { // create an instance for xml dom object\n xmlDoc = new ActiveXObject(\"Microsoft.XMLDOM\");\n xmlDoc.async = false;\n xmlDoc.loadXML(t);\n }\n return xmlDoc;\n }\n </script>\n </head>\n <body>\n <script>\n \n // a variable with the string\n var text = \"<Employee>\";\n text = text+\"<FirstName>Tanmay</FirstName>\";\n text = text+\"<LastName>Patil</LastName>\";\n text = text+\"<ContactNo>1234567890</ContactNo>\";\n text = text+\"<Email>[email protected]</Email>\";\n text = text+\"</Employee>\";\n\n // calls the loadXMLString() with \"text\" function and store the xml dom in a variable\n var xmlDoc = loadXMLString(text);\n\t\n //parsing the DOM object\n y = xmlDoc.documentElement.childNodes;\n for (i = 0;i<y.length;i++) {\n document.write(y[i].childNodes[0].nodeValue);\n document.write(\"<br>\");\n }\n </script>\n </body>\n</html>" }, { "code": null, "e": 21291, "s": 21235, "text": "Most of the details of the code are in the script code." }, { "code": null, "e": 21478, "s": 21291, "text": "Internet Explorer uses the ActiveXObject(\"Microsoft.XMLDOM\") to load XML data into a DOM object, other browsers use the DOMParser() function and parseFromString(text, 'text/xml') method." }, { "code": null, "e": 21665, "s": 21478, "text": "Internet Explorer uses the ActiveXObject(\"Microsoft.XMLDOM\") to load XML data into a DOM object, other browsers use the DOMParser() function and parseFromString(text, 'text/xml') method." }, { "code": null, "e": 21724, "s": 21665, "text": "The variable text shall contain a string with XML content." }, { "code": null, "e": 21783, "s": 21724, "text": "The variable text shall contain a string with XML content." }, { "code": null, "e": 21974, "s": 21783, "text": "Once the XML content is transformed into JavaScript XML DOM, you can access any XML element by using JS DOM methods and properties. We have used DOM properties such as childNodes, nodeValue." }, { "code": null, "e": 22165, "s": 21974, "text": "Once the XML content is transformed into JavaScript XML DOM, you can access any XML element by using JS DOM methods and properties. We have used DOM properties such as childNodes, nodeValue." }, { "code": null, "e": 22268, "s": 22165, "text": "Save this file as loadingexample.html and open it in your browser. You will see the following output −" }, { "code": null, "e": 22406, "s": 22268, "text": "Now that we saw how the XML content transforms into JavaScript XML DOM, you can now access any XML element by using the XML DOM methods." }, { "code": null, "e": 22740, "s": 22406, "text": "In this chapter, we will discuss XML DOM Traversing. We studied in the previous chapter how to load XML document and parse the thus obtained DOM object. This parsed DOM object can be traversed. Traversing is a process in which looping is done in a systematic manner by going across each and every element step by step in a node tree." }, { "code": null, "e": 22878, "s": 22740, "text": "The following example (traverse_example.htm) demonstrates DOM traversing. Here we traverse through each child node of <Employee> element." }, { "code": null, "e": 25982, "s": 22878, "text": "<!DOCTYPE html>\n<html>\n <style>\n table,th,td {\n border:1px solid black;\n border-collapse:collapse\n }\n </style>\n <body>\n <div id = \"ajax_xml\"></div>\n <script>\n //if browser supports XMLHttpRequest\n if (window.XMLHttpRequest) {// Create an instance of XMLHttpRequest object. \n code for IE7+, Firefox, Chrome, Opera, Safari\n var xmlhttp = new XMLHttpRequest();\n } else {// code for IE6, IE5\n var xmlhttp = new ActiveXObject(\"Microsoft.XMLHTTP\");\n }\n // sets and sends the request for calling \"node.xml\"\n xmlhttp.open(\"GET\",\"/dom/node.xml\",false);\n xmlhttp.send();\n\n // sets and returns the content as XML DOM\n var xml_dom = xmlhttp.responseXML;\n\t\n // this variable stores the code of the html table\n var html_tab = '<table id = \"id_tabel\" align = \"center\">\n <tr>\n <th>Employee Category</th>\n <th>FirstName</th>\n <th>LastName</th>\n <th>ContactNo</th>\n <th>Email</th>\n </tr>';\n var arr_employees = xml_dom.getElementsByTagName(\"Employee\");\n // traverses the \"arr_employees\" array\n for(var i = 0; i<arr_employees.length; i++) {\n var employee_cat = arr_employees[i].getAttribute('category');\n \n // gets the value of 'category' element of current \"Element\" tag\n\n // gets the value of first child-node of 'FirstName' \n // element of current \"Employee\" tag\n var employee_firstName =\n arr_employees[i].getElementsByTagName('FirstName')[0].childNodes[0].nodeValue;\n\n // gets the value of first child-node of 'LastName' \n // element of current \"Employee\" tag\n var employee_lastName =\n arr_employees[i].getElementsByTagName('LastName')[0].childNodes[0].nodeValue;\n\n // gets the value of first child-node of 'ContactNo' \n // element of current \"Employee\" tag\n var employee_contactno = \n arr_employees[i].getElementsByTagName('ContactNo')[0].childNodes[0].nodeValue;\n\n // gets the value of first child-node of 'Email' \n // element of current \"Employee\" tag\n var employee_email = \n arr_employees[i].getElementsByTagName('Email')[0].childNodes[0].nodeValue;\n\n // adds the values in the html table\n html_tab += '<tr>\n <td>'+ employee_cat+ '</td>\n <td>'+ employee_firstName+ '</td>\n <td>'+ employee_lastName+ '</td>\n <td>'+ employee_contactno+ '</td>\n <td>'+ employee_email+ '</td>\n </tr>';\n }\n html_tab += '</table>'; \n // adds the html table in a html tag, with id = \"ajax_xml\"\n document.getElementById('ajax_xml').innerHTML = html_tab; \n </script>\n </body>\n</html>" }, { "code": null, "e": 26008, "s": 25982, "text": "This code loads node.xml." }, { "code": null, "e": 26034, "s": 26008, "text": "This code loads node.xml." }, { "code": null, "e": 26097, "s": 26034, "text": "The XML content is transformed into JavaScript XML DOM object." }, { "code": null, "e": 26160, "s": 26097, "text": "The XML content is transformed into JavaScript XML DOM object." }, { "code": null, "e": 26254, "s": 26160, "text": "The array of elements (with tag Element) using the method getElementsByTagName() is obtained." }, { "code": null, "e": 26348, "s": 26254, "text": "The array of elements (with tag Element) using the method getElementsByTagName() is obtained." }, { "code": null, "e": 26431, "s": 26348, "text": "Next, we traverse through this array and display the child node values in a table." }, { "code": null, "e": 26514, "s": 26431, "text": "Next, we traverse through this array and display the child node values in a table." }, { "code": null, "e": 26681, "s": 26514, "text": "Save this file as traverse_example.html on the server path (this file and node.xml should be on the same path in your server). You will receive the following output −" }, { "code": null, "e": 26967, "s": 26681, "text": "Until now we studied DOM structure, how to load and parse XML DOM object and traverse through the DOM objects. Here we will see how we can navigate between nodes in a DOM object. The XML DOM consist of various properties of the nodes which help us navigate through the nodes, such as −" }, { "code": null, "e": 26978, "s": 26967, "text": "parentNode" }, { "code": null, "e": 26989, "s": 26978, "text": "childNodes" }, { "code": null, "e": 27000, "s": 26989, "text": "firstChild" }, { "code": null, "e": 27010, "s": 27000, "text": "lastChild" }, { "code": null, "e": 27022, "s": 27010, "text": "nextSibling" }, { "code": null, "e": 27038, "s": 27022, "text": "previousSibling" }, { "code": null, "e": 27123, "s": 27038, "text": "Following is a diagram of a node tree showing its relationship with the other nodes." }, { "code": null, "e": 27181, "s": 27123, "text": "This property specifies the parent node as a node object." }, { "code": null, "e": 27361, "s": 27181, "text": "The following example (navigate_example.htm) parses an XML document (node.xml) into an XML DOM object. Then the DOM object is navigated to the parent node through the child node −" }, { "code": null, "e": 27843, "s": 27361, "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 var y = xmlDoc.getElementsByTagName(\"Employee\")[0];\n document.write(y.parentNode.nodeName);\n </script>\n </body>\n</html>" }, { "code": null, "e": 27934, "s": 27843, "text": "As you can see in the above example, the child node Employee navigates to its parent node." }, { "code": null, "e": 28126, "s": 27934, "text": "Save this file as navigate_example.html on the server path (this file and node.xml should be on the same path in your server). In the output, we get the parent node of Employee, i.e, Company." }, { "code": null, "e": 28217, "s": 28126, "text": "This property is of type Node and represents the first child name present in the NodeList." }, { "code": null, "e": 28388, "s": 28217, "text": "The following example (first_node_example.htm) parses an XML document (node.xml) into an XML DOM object, then navigates to the first child node present in the DOM object." }, { "code": null, "e": 29081, "s": 28388, "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 function get_firstChild(p) {\n a = p.firstChild;\n\n while (a.nodeType != 1) {\n a = a.nextSibling;\n }\n return a;\n }\n var firstchild = get_firstChild(xmlDoc.getElementsByTagName(\"Employee\")[0]);\n document.write(firstchild.nodeName);\n </script>\n </body>\n</html>" }, { "code": null, "e": 29201, "s": 29081, "text": "Function get_firstChild(p) is used to avoid the empty nodes. It helps to get the firstChild element from the node list." }, { "code": null, "e": 29321, "s": 29201, "text": "Function get_firstChild(p) is used to avoid the empty nodes. It helps to get the firstChild element from the node list." }, { "code": null, "e": 29440, "s": 29321, "text": "x = get_firstChild(xmlDoc.getElementsByTagName(\"Employee\")[0]) fetches the first child node for the tag name Employee." }, { "code": null, "e": 29559, "s": 29440, "text": "x = get_firstChild(xmlDoc.getElementsByTagName(\"Employee\")[0]) fetches the first child node for the tag name Employee." }, { "code": null, "e": 29759, "s": 29559, "text": "Save this file as first_node_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 first child node of Employee i.e. FirstName." }, { "code": null, "e": 29849, "s": 29759, "text": "This property is of type Node and represents the last child name present in the NodeList." }, { "code": null, "e": 30022, "s": 29849, "text": "The following example (last_node_example.htm) parses an XML document (node.xml) into an XML DOM object, then navigates to the last child node present in the xml DOM object." }, { "code": null, "e": 30705, "s": 30022, "text": "<!DOCTYPE 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 function get_lastChild(p) {\n a = p.lastChild;\n\n while (a.nodeType != 1){\n a = a.previousSibling;\n }\n return a;\n }\n var lastchild = get_lastChild(xmlDoc.getElementsByTagName(\"Employee\")[0]);\n document.write(lastchild.nodeName);\n </script>\n </body>\n</html>" }, { "code": null, "e": 30899, "s": 30705, "text": "Save this file as last_node_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 last child node of Employee, i.e, Email." }, { "code": null, "e": 31038, "s": 30899, "text": "This property is of type Node and represents the next child, i.e, the next sibling of the specified child element present in the NodeList." }, { "code": null, "e": 31217, "s": 31038, "text": "The following example (nextSibling_example.htm) parses an XML document (node.xml) into an XML DOM object which navigates immediately to the next node present in the xml document." }, { "code": null, "e": 31918, "s": 31217, "text": "<!DOCTYPE html>\n <body>\n <script>\n if (window.XMLHttpRequest) {\n xmlhttp = new XMLHttpRequest();\n }\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 function get_nextSibling(p) {\n a = p.nextSibling;\n\n while (a.nodeType != 1) {\n a = a.nextSibling;\n }\n return a;\n }\n var nextsibling = get_nextSibling(xmlDoc.getElementsByTagName(\"FirstName\")[0]);\n document.write(nextsibling.nodeName);\n </script>\n </body>\n</html>" }, { "code": null, "e": 32120, "s": 31918, "text": "Save this file as nextSibling_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 next sibling node of FirstName, i.e, LastName." }, { "code": null, "e": 32267, "s": 32120, "text": "This property is of type Node and represents the previous child, i.e, the previous sibling of the specified child element present in the NodeList." }, { "code": null, "e": 32460, "s": 32267, "text": "The following example (previoussibling_example.htm) parses an XML document (node.xml) into an XML DOM object, then navigates the before node of the last child node present in the xml document." }, { "code": null, "e": 33170, "s": 32460, "text": "<!DOCTYPE html>\n <body>\n <script>\n if (window.XMLHttpRequest)\n {\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 function get_previousSibling(p) {\n a = p.previousSibling;\n\n while (a.nodeType != 1) {\n a = a.previousSibling;\n }\n return a;\n }\n\n prevsibling = get_previousSibling(xmlDoc.getElementsByTagName(\"Email\")[0]);\n document.write(prevsibling.nodeName);\n </script>\n </body>\n</html>" }, { "code": null, "e": 33377, "s": 33170, "text": "Save this file as previoussibling_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 previous sibling node of Email, i.e, ContactNo." }, { "code": null, "e": 33674, "s": 33377, "text": "In this chapter, we will study about how to access the XML DOM nodes which are considered as the informational units of the XML document. The node structure of the XML DOM allows the developer to navigate around the tree looking for specific information and simultaneously access the information." }, { "code": null, "e": 33739, "s": 33674, "text": "Following are the three ways in which you can access the nodes −" }, { "code": null, "e": 33783, "s": 33739, "text": "By using the getElementsByTagName () method" }, { "code": null, "e": 33827, "s": 33783, "text": "By using the getElementsByTagName () method" }, { "code": null, "e": 33879, "s": 33827, "text": "By looping through or traversing through nodes tree" }, { "code": null, "e": 33931, "s": 33879, "text": "By looping through or traversing through nodes tree" }, { "code": null, "e": 33989, "s": 33931, "text": "By navigating the node tree, using the node relationships" }, { "code": null, "e": 34047, "s": 33989, "text": "By navigating the node tree, using the node relationships" }, { "code": null, "e": 34211, "s": 34047, "text": "This method allows accessing the information of a node by specifying the node name. It also allows accessing the information of the Node List and Node List Length." }, { "code": null, "e": 34271, "s": 34211, "text": "The getElementByTagName() method has the following syntax −" }, { "code": null, "e": 34309, "s": 34271, "text": "node.getElementByTagName(\"tagname\");\n" }, { "code": null, "e": 34316, "s": 34309, "text": "Where," }, { "code": null, "e": 34345, "s": 34316, "text": "node − is the document node." }, { "code": null, "e": 34374, "s": 34345, "text": "node − is the document node." }, { "code": null, "e": 34440, "s": 34374, "text": "tagname − holds the name of the node whose value you want to get." }, { "code": null, "e": 34506, "s": 34440, "text": "tagname − holds the name of the node whose value you want to get." }, { "code": null, "e": 34595, "s": 34506, "text": "Following is a simple program which illustrates the usage of method getElementByTagName." }, { "code": null, "e": 35650, "s": 34595, "text": "<!DOCTYPE html>\n<html>\n <body>\n <div>\n <b>FirstName:</b> <span id = \"FirstName\"></span><br>\n <b>LastName:</b> <span id = \"LastName\"></span><br>\n <b>Category:</b> <span id = \"Employee\"></span><br>\n </div>\n <script>\n if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari\n xmlhttp = new XMLHttpRequest();\n } else {// code for IE6, IE5\n xmlhttp = new ActiveXObject(\"Microsoft.XMLHTTP\");\n }\n xmlhttp.open(\"GET\",\"/dom/node.xml\",false);\n xmlhttp.send();\n xmlDoc = xmlhttp.responseXML;\n\n document.getElementById(\"FirstName\").innerHTML = \n xmlDoc.getElementsByTagName(\"FirstName\")[0].childNodes[0].nodeValue;\n document.getElementById(\"LastName\").innerHTML = \n xmlDoc.getElementsByTagName(\"LastName\")[0].childNodes[0].nodeValue;\n document.getElementById(\"Employee\").innerHTML = \n xmlDoc.getElementsByTagName(\"Employee\")[0].attributes[0].nodeValue;\n </script>\n </body>\n</html>" }, { "code": null, "e": 35752, "s": 35650, "text": "In the above example, we are accessing the information of the nodes FirstName,\nLastName and Employee." }, { "code": null, "e": 35854, "s": 35752, "text": "In the above example, we are accessing the information of the nodes FirstName,\nLastName and Employee." }, { "code": null, "e": 36021, "s": 35854, "text": "xmlDoc.getElementsByTagName(\"FirstName\")[0].childNodes[0].nodeValue; This line accesses the value for the child node FirstName using the getElementByTagName() method." }, { "code": null, "e": 36188, "s": 36021, "text": "xmlDoc.getElementsByTagName(\"FirstName\")[0].childNodes[0].nodeValue; This line accesses the value for the child node FirstName using the getElementByTagName() method." }, { "code": null, "e": 36346, "s": 36188, "text": "xmlDoc.getElementsByTagName(\"Employee\")[0].attributes[0].nodeValue; This line accesses the attribute value of the node Employee getElementByTagName() method." }, { "code": null, "e": 36504, "s": 36346, "text": "xmlDoc.getElementsByTagName(\"Employee\")[0].attributes[0].nodeValue; This line accesses the attribute value of the node Employee getElementByTagName() method." }, { "code": null, "e": 36566, "s": 36504, "text": "This is covered in the chapter DOM Traversing with examples." }, { "code": null, "e": 36628, "s": 36566, "text": "This is covered in the chapter DOM Navigation with examples." }, { "code": null, "e": 36858, "s": 36628, "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": 36903, "s": 36858, "text": "In the following sections, we will discuss −" }, { "code": null, "e": 36936, "s": 36903, "text": "Getting node value of an element" }, { "code": null, "e": 36969, "s": 36936, "text": "Getting node value of an element" }, { "code": null, "e": 37003, "s": 36969, "text": "Getting attribute value of a node" }, { "code": null, "e": 37037, "s": 37003, "text": "Getting attribute value of a node" }, { "code": null, "e": 37099, "s": 37037, "text": "The node.xml used in all the following examples is as below −" }, { "code": null, "e": 37745, "s": 37099, "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": 37859, "s": 37745, "text": "The method getElementsByTagName() returns a NodeList of all the Elements in document order with a given tag name." }, { "code": null, "e": 38031, "s": 37859, "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": 38528, "s": 38031, "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": 38701, "s": 38528, "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": 39026, "s": 38701, "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": 39098, "s": 39026, "text": "The getAttribute() method retrieves an attribute value by element name." }, { "code": null, "e": 39278, "s": 39098, "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": 39761, "s": 39278, "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": 39949, "s": 39761, "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": 40081, "s": 39949, "text": "In this chapter, we will study about how to change the values of nodes in an XML DOM object. Node value can be changed as follows −" }, { "code": null, "e": 40110, "s": 40081, "text": "var value = node.nodeValue;\n" }, { "code": null, "e": 40285, "s": 40110, "text": "If node is an Attribute then the value variable will be the value of the attribute; if node is a Text node it will be the text content; if node is an Element it will be null." }, { "code": null, "e": 40399, "s": 40285, "text": "Following sections will demonstrate the node value setting for each node type (attribute, text node and element)." }, { "code": null, "e": 40461, "s": 40399, "text": "The node.xml used in all the following examples is as below −" }, { "code": null, "e": 41107, "s": 40461, "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": 41312, "s": 41107, "text": "When we, say the change value of Node element we mean to edit the text content of an element (which is also called the text node). Following example demonstrates how to change the text node of an element." }, { "code": null, "e": 41545, "s": 41312, "text": "The following example (set_text_node_example.htm) parses an XML document (node.xml) into an XML DOM object and change the value of an element's text node. In this case, Email of each Employee to [email protected] and print the values." }, { "code": null, "e": 42392, "s": 41545, "text": "<!DOCTYPE html>\n<html>\n <head>\n <script>\n function loadXMLDoc(filename) {\n if (window.XMLHttpRequest) {\n xhttp = new XMLHttpRequest();\n } else // code for IE5 and IE6 {\n xhttp = new ActiveXObject(\"Microsoft.XMLHTTP\");\n }\n xhttp.open(\"GET\",filename,false);\n xhttp.send();\n return xhttp.responseXML;\n }\n </script>\n </head>\n <body>\n <script>\n xmlDoc = loadXMLDoc(\"/dom/node.xml\");\n\n x = xmlDoc.getElementsByTagName(\"Email\");\n for(i = 0;i<x.length;i++) {\t\n\t\n x[i].childNodes[0].nodeValue = \"[email protected]\";\n document.write(i+');\n document.write(x[i].childNodes[0].nodeValue);\n document.write('<br>');\n }\n\t\n </script>\n </body>\n</html>" }, { "code": null, "e": 42563, "s": 42392, "text": "Save this file as set_text_node_example.htm on the server path (this file and node.xml should be on the same path in your server). You will receive the following output −" }, { "code": null, "e": 42621, "s": 42563, "text": "0) [email protected]\n1) [email protected]\n2) [email protected]\n" }, { "code": null, "e": 42704, "s": 42621, "text": "The following example demonstrates how to change the attribute node of an element." }, { "code": null, "e": 42973, "s": 42704, "text": "The following example (set_attribute_example.htm) parses an XML document (node.xml) into an XML DOM object and changes the value of an element's attribute node. In this case, the Category of each Employee to admin-0, admin-1, admin-2 respectively and print the values." }, { "code": null, "e": 43886, "s": 42973, "text": "<!DOCTYPE html>\n<html>\n <head>\n <script>\n function loadXMLDoc(filename) {\n if (window.XMLHttpRequest) {\n xhttp = new XMLHttpRequest();\n } else // code for IE5 and IE6 {\n xhttp = new ActiveXObject(\"Microsoft.XMLHTTP\");\n }\n xhttp.open(\"GET\",filename,false);\n xhttp.send();\n return xhttp.responseXML;\n }\n </script>\n </head>\n <body>\n <script>\n xmlDoc = loadXMLDoc(\"/dom/node.xml\");\n\n x = xmlDoc.getElementsByTagName(\"Employee\");\n for(i = 0 ;i<x.length;i++){\t\n\t\n newcategory = x[i].getAttributeNode('category');\n newcategory.nodeValue = \"admin-\"+i;\n document.write(i+');\n document.write(x[i].getAttributeNode('category').nodeValue);\n document.write('<br>');\n }\n\t\n </script>\n </body>\n</html>" }, { "code": null, "e": 44053, "s": 43886, "text": "Save this file as set_node_attribute_example.htm on the server path (this file and node.xml should be on the same path in your server). The result would be as below −" }, { "code": null, "e": 44087, "s": 44053, "text": "0) admin-0\n1) admin-1\n2) admin-2\n" }, { "code": null, "e": 44462, "s": 44087, "text": "In this chapter, we will discuss how to create new nodes using a couple of methods of the document object. These methods provide a scope to create new element node, text node, comment node, CDATA section node and attribute node. If the newly created node already exists in the element object, it is replaced by the new one. Following sections demonstrate this with examples." }, { "code": null, "e": 44612, "s": 44462, "text": "The method createElement() creates a new element node. If the newly created element node exists in the element object, it is replaced by the new one." }, { "code": null, "e": 44669, "s": 44612, "text": "Syntax to use the createElement() method is as follows −" }, { "code": null, "e": 44714, "s": 44669, "text": "var_name = xmldoc.createElement(\"tagname\");\n" }, { "code": null, "e": 44721, "s": 44714, "text": "Where," }, { "code": null, "e": 44803, "s": 44721, "text": "var_name − is the user-defined variable name which holds the name of new element." }, { "code": null, "e": 44885, "s": 44803, "text": "var_name − is the user-defined variable name which holds the name of new element." }, { "code": null, "e": 44946, "s": 44885, "text": "(\"tagname\") − is the name of new element node to be created." }, { "code": null, "e": 45007, "s": 44946, "text": "(\"tagname\") − is the name of new element node to be created." }, { "code": null, "e": 45177, "s": 45007, "text": "The following example (createnewelement_example.htm) parses an XML document (node.xml) into an XML DOM object and creates a new element node PhoneNo in the XML document." }, { "code": null, "e": 45955, "s": 45177, "text": "<!DOCTYPE html>\n<html>\n <head>\n <script>\n function loadXMLDoc(filename) {\n if (window.XMLHttpRequest) {\n xhttp = new XMLHttpRequest();\n } else // code for IE5 and IE6 {\n xhttp = new ActiveXObject(\"Microsoft.XMLHTTP\");\n }\n xhttp.open(\"GET\",filename,false);\n xhttp.send();\n return xhttp.responseXML;\n }\n </script>\n </head>\n <body>\n <script>\n xmlDoc = loadXMLDoc(\"/dom/node.xml\");\n\n new_element = xmlDoc.createElement(\"PhoneNo\");\n\n x = xmlDoc.getElementsByTagName(\"FirstName\")[0];\n x.appendChild(new_element);\n\n document.write(x.getElementsByTagName(\"PhoneNo\")[0].nodeName);\n </script>\n </body>\n</html>" }, { "code": null, "e": 46041, "s": 45955, "text": "new_element = xmlDoc.createElement(\"PhoneNo\"); creates the new element node <PhoneNo>" }, { "code": null, "e": 46127, "s": 46041, "text": "new_element = xmlDoc.createElement(\"PhoneNo\"); creates the new element node <PhoneNo>" }, { "code": null, "e": 46255, "s": 46127, "text": "x.appendChild(new_element); x holds the name of the specified child node <FirstName> to which the new element node is appended." }, { "code": null, "e": 46383, "s": 46255, "text": "x.appendChild(new_element); x holds the name of the specified child node <FirstName> to which the new element node is appended." }, { "code": null, "e": 46570, "s": 46383, "text": "Save this file as createnewelement_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 PhoneNo." }, { "code": null, "e": 46623, "s": 46570, "text": "The method createTextNode() creates a new text node." }, { "code": null, "e": 46670, "s": 46623, "text": "Syntax to use createTextNode() is as follows −" }, { "code": null, "e": 46716, "s": 46670, "text": "var_name = xmldoc.createTextNode(\"tagname\");\n" }, { "code": null, "e": 46723, "s": 46716, "text": "Where," }, { "code": null, "e": 46810, "s": 46723, "text": "var_name − it is the user-defined variable name which holds the name of new text node." }, { "code": null, "e": 46897, "s": 46810, "text": "var_name − it is the user-defined variable name which holds the name of new text node." }, { "code": null, "e": 46978, "s": 46897, "text": "(\"tagname\") − within the parenthesis is the name of new text node to be created." }, { "code": null, "e": 47059, "s": 46978, "text": "(\"tagname\") − within the parenthesis is the name of new text node to be created." }, { "code": null, "e": 47233, "s": 47059, "text": "The following example (createtextnode_example.htm) parses an XML document (node.xml) into an XML DOM object and creates a new text node Im new text node in the XML document." }, { "code": null, "e": 48164, "s": 47233, "text": "<!DOCTYPE html>\n<html>\n <head>\n <script>\n function loadXMLDoc(filename) {\n if (window.XMLHttpRequest) {\n xhttp = new XMLHttpRequest();\n } else // code for IE5 and IE6 {\n xhttp = new ActiveXObject(\"Microsoft.XMLHTTP\");\n }\n xhttp.open(\"GET\",filename,false);\n xhttp.send();\n return xhttp.responseXML;\n }\n </script>\n </head>\n <body>\n <script>\n xmlDoc = loadXMLDoc(\"/dom/node.xml\");\n\n create_e = xmlDoc.createElement(\"PhoneNo\");\n create_t = xmlDoc.createTextNode(\"Im new text node\");\n create_e.appendChild(create_t);\n\n x = xmlDoc.getElementsByTagName(\"Employee\")[0];\n x.appendChild(create_e);\n\n\n document.write(\" PhoneNO: \");\n document.write(x.getElementsByTagName(\"PhoneNo\")[0].childNodes[0].nodeValue);\n </script>\n </body>\n</html>" }, { "code": null, "e": 48205, "s": 48164, "text": "Details of the above code are as below −" }, { "code": null, "e": 48282, "s": 48205, "text": "create_e = xmlDoc.createElement(\"PhoneNo\"); creates a new element <PhoneNo>." }, { "code": null, "e": 48359, "s": 48282, "text": "create_e = xmlDoc.createElement(\"PhoneNo\"); creates a new element <PhoneNo>." }, { "code": null, "e": 48457, "s": 48359, "text": "create_t = xmlDoc.createTextNode(\"Im new text node\"); creates a new text node \"Im new text node\"." }, { "code": null, "e": 48555, "s": 48457, "text": "create_t = xmlDoc.createTextNode(\"Im new text node\"); creates a new text node \"Im new text node\"." }, { "code": null, "e": 48655, "s": 48555, "text": " x.appendChild(create_e); the text node, \"Im new text node\" is appended to the element, <PhoneNo>. " }, { "code": null, "e": 48754, "s": 48655, "text": " x.appendChild(create_e); the text node, \"Im new text node\" is appended to the element, <PhoneNo>." }, { "code": null, "e": 48889, "s": 48754, "text": "document.write(x.getElementsByTagName(\"PhoneNo\")[0].childNodes[0].nodeValue); writes the new text node value to the element <PhoneNo>." }, { "code": null, "e": 49024, "s": 48889, "text": "document.write(x.getElementsByTagName(\"PhoneNo\")[0].childNodes[0].nodeValue); writes the new text node value to the element <PhoneNo>." }, { "code": null, "e": 49233, "s": 49024, "text": "Save this file as createtextnode_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 i.e. PhoneNO: Im new text node." }, { "code": null, "e": 49382, "s": 49233, "text": "The method createComment() creates a new comment node. Comment node is included in the program for the easy understanding of the code functionality." }, { "code": null, "e": 49428, "s": 49382, "text": "Syntax to use createComment() is as follows −" }, { "code": null, "e": 49473, "s": 49428, "text": "var_name = xmldoc.createComment(\"tagname\");\n" }, { "code": null, "e": 49480, "s": 49473, "text": "Where," }, { "code": null, "e": 49567, "s": 49480, "text": "var_name − is the user-defined variable name which holds the name of new comment node." }, { "code": null, "e": 49654, "s": 49567, "text": "var_name − is the user-defined variable name which holds the name of new comment node." }, { "code": null, "e": 49719, "s": 49654, "text": "(\"tagname\") − is the name of the new comment node to be created." }, { "code": null, "e": 49784, "s": 49719, "text": "(\"tagname\") − is the name of the new comment node to be created." }, { "code": null, "e": 49977, "s": 49784, "text": "The following example (createcommentnode_example.htm) parses an XML document (node.xml) into an XML DOM object and creates a new comment node, \"Company is the parent node\" in the XML document." }, { "code": null, "e": 50767, "s": 49977, "text": "<!DOCTYPE html>\n<html>\n <head>\n <script>\n function loadXMLDoc(filename) {\n if (window.XMLHttpRequest) {\n xhttp = new XMLHttpRequest();\n }\n else // code for IE5 and IE6 {\n xhttp = new ActiveXObject(\"Microsoft.XMLHTTP\");\n }\n xhttp.open(\"GET\",filename,false);\n xhttp.send();\n return xhttp.responseXML;\n }\n </script>\n </head>\n <body>\n <script>\n xmlDoc = loadXMLDoc(\"/dom/node.xml\");\n\n create_comment = xmlDoc.createComment(\"Company is the parent node\");\n\n x = xmlDoc.getElementsByTagName(\"Company\")[0];\n\n x.appendChild(create_comment);\n\n document.write(x.lastChild.nodeValue);\n </script>\n </body>\n</html>" }, { "code": null, "e": 50790, "s": 50767, "text": "In the above example −" }, { "code": null, "e": 50892, "s": 50790, "text": "create_comment = xmlDoc.createComment(\"Company is the parent node\") creates a specified comment line." }, { "code": null, "e": 50994, "s": 50892, "text": "create_comment = xmlDoc.createComment(\"Company is the parent node\") creates a specified comment line." }, { "code": null, "e": 51122, "s": 50994, "text": " x.appendChild(create_comment) In this line, 'x' holds the name of the element <Company> to which the comment line is appended." }, { "code": null, "e": 51250, "s": 51122, "text": " x.appendChild(create_comment) In this line, 'x' holds the name of the element <Company> to which the comment line is appended." }, { "code": null, "e": 51463, "s": 51250, "text": "Save this file as createcommentnode_example.htm on the server path (this file and the node.xml should be on the same path in your server). In the output, we get the attribute value as Company is the parent node ." }, { "code": null, "e": 51630, "s": 51463, "text": "The method createCDATASection() creates a new CDATA section node. If the newly created CDATA section node exists in the element object, it is replaced by the new one." }, { "code": null, "e": 51681, "s": 51630, "text": "Syntax to use createCDATASection() is as follows −" }, { "code": null, "e": 51731, "s": 51681, "text": "var_name = xmldoc.createCDATASection(\"tagname\");\n" }, { "code": null, "e": 51738, "s": 51731, "text": "Where," }, { "code": null, "e": 51835, "s": 51738, "text": "var_name − is the user-defined variable name which holds the name of new the CDATA section node." }, { "code": null, "e": 51932, "s": 51835, "text": "var_name − is the user-defined variable name which holds the name of new the CDATA section node." }, { "code": null, "e": 51999, "s": 51932, "text": "(\"tagname\") − is the name of new CDATA section node to be created." }, { "code": null, "e": 52066, "s": 51999, "text": "(\"tagname\") − is the name of new CDATA section node to be created." }, { "code": null, "e": 52257, "s": 52066, "text": "The following example (createcdatanode_example.htm) parses an XML document (node.xml) into an XML DOM object and creates a new CDATA section node, \"Create CDATA Example\" in the XML document." }, { "code": null, "e": 53041, "s": 52257, "text": "<!DOCTYPE html>\n<html>\n <head>\n <script>\n function loadXMLDoc(filename) {\n if (window.XMLHttpRequest) {\n xhttp = new XMLHttpRequest();\n }\n else // code for IE5 and IE6 {\n xhttp = new ActiveXObject(\"Microsoft.XMLHTTP\");\n }\n xhttp.open(\"GET\",filename,false);\n xhttp.send();\n return xhttp.responseXML;\n }\n </script>\n </head>\n <body>\n <script>\n xmlDoc = loadXMLDoc(\"/dom/node.xml\");\n\n create_CDATA = xmlDoc.createCDATASection(\"Create CDATA Example\");\n\n x = xmlDoc.getElementsByTagName(\"Employee\")[0];\n x.appendChild(create_CDATA);\n document.write(x.lastChild.nodeValue);\n </script>\n </body>\n</html>" }, { "code": null, "e": 53064, "s": 53041, "text": "In the above example −" }, { "code": null, "e": 53186, "s": 53064, "text": "create_CDATA = xmlDoc.createCDATASection(\"Create CDATA Example\") creates a new CDATA section node, \"Create CDATA Example\"" }, { "code": null, "e": 53308, "s": 53186, "text": "create_CDATA = xmlDoc.createCDATASection(\"Create CDATA Example\") creates a new CDATA section node, \"Create CDATA Example\"" }, { "code": null, "e": 53439, "s": 53308, "text": "x.appendChild(create_CDATA) here, x holds the specified element <Employee> indexed at 0 to which the CDATA node value is appended." }, { "code": null, "e": 53570, "s": 53439, "text": "x.appendChild(create_CDATA) here, x holds the specified element <Employee> indexed at 0 to which the CDATA node value is appended." }, { "code": null, "e": 53770, "s": 53570, "text": "Save this file as createcdatanode_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 Create CDATA Example." }, { "code": null, "e": 53938, "s": 53770, "text": "To create a new attribute node, the method setAttributeNode() is used. If the newly created attribute node exists in the element object, it is replaced by the new one." }, { "code": null, "e": 53995, "s": 53938, "text": "Syntax to use the createElement() method is as follows −" }, { "code": null, "e": 54042, "s": 53995, "text": "var_name = xmldoc.createAttribute(\"tagname\");\n" }, { "code": null, "e": 54049, "s": 54042, "text": "Where," }, { "code": null, "e": 54138, "s": 54049, "text": "var_name − is the user-defined variable name which holds the name of new attribute node." }, { "code": null, "e": 54227, "s": 54138, "text": "var_name − is the user-defined variable name which holds the name of new attribute node." }, { "code": null, "e": 54290, "s": 54227, "text": "(\"tagname\") − is the name of new attribute node to be created." }, { "code": null, "e": 54353, "s": 54290, "text": "(\"tagname\") − is the name of new attribute node to be created." }, { "code": null, "e": 54528, "s": 54353, "text": "The following example (createattributenode_example.htm) parses an XML document (node.xml) into an XML DOM object and creates a new attribute node section in the XML document." }, { "code": null, "e": 55368, "s": 54528, "text": "<!DOCTYPE html>\n<html>\n <head>\n <script>\n function loadXMLDoc(filename) {\n if (window.XMLHttpRequest) {\n xhttp = new XMLHttpRequest();\n } else // code for IE5 and IE6 {\n xhttp = new ActiveXObject(\"Microsoft.XMLHTTP\");\n }\n xhttp.open(\"GET\",filename,false);\n xhttp.send();\n return xhttp.responseXML;\n }\n </script>\n </head>\n <body>\n <script>\n xmlDoc = loadXMLDoc(\"/dom/node.xml\");\n\n create_a = xmlDoc.createAttribute(\"section\");\n create_a.nodeValue = \"A\";\n\n x = xmlDoc.getElementsByTagName(\"Employee\");\n x[0].setAttributeNode(create_a);\n document.write(\"New Attribute: \");\n document.write(x[0].getAttribute(\"section\"));\n\n </script>\n </body>\n</html>" }, { "code": null, "e": 55391, "s": 55368, "text": "In the above example −" }, { "code": null, "e": 55481, "s": 55391, "text": "create_a=xmlDoc.createAttribute(\"Category\") creates an attribute with the name <section>." }, { "code": null, "e": 55571, "s": 55481, "text": "create_a=xmlDoc.createAttribute(\"Category\") creates an attribute with the name <section>." }, { "code": null, "e": 55654, "s": 55571, "text": "create_a.nodeValue=\"Management\" creates the value \"A\" for the attribute <section>." }, { "code": null, "e": 55737, "s": 55654, "text": "create_a.nodeValue=\"Management\" creates the value \"A\" for the attribute <section>." }, { "code": null, "e": 55842, "s": 55737, "text": "x[0].setAttributeNode(create_a) this attribute value is set to the node element <Employee> indexed at 0." }, { "code": null, "e": 55947, "s": 55842, "text": "x[0].setAttributeNode(create_a) this attribute value is set to the node element <Employee> indexed at 0." }, { "code": null, "e": 56040, "s": 55947, "text": "In this chapter, we will discuss the nodes to the existing element. It provides a means to −" }, { "code": null, "e": 56104, "s": 56040, "text": "append new child nodes before or after the existing child nodes" }, { "code": null, "e": 56168, "s": 56104, "text": "append new child nodes before or after the existing child nodes" }, { "code": null, "e": 56201, "s": 56168, "text": "insert data within the text node" }, { "code": null, "e": 56234, "s": 56201, "text": "insert data within the text node" }, { "code": null, "e": 56253, "s": 56234, "text": "add attribute node" }, { "code": null, "e": 56272, "s": 56253, "text": "add attribute node" }, { "code": null, "e": 56351, "s": 56272, "text": "Following methods can be used to add/append the nodes to an element in a DOM −" }, { "code": null, "e": 56365, "s": 56351, "text": "appendChild()" }, { "code": null, "e": 56380, "s": 56365, "text": "insertBefore()" }, { "code": null, "e": 56393, "s": 56380, "text": "insertData()" }, { "code": null, "e": 56473, "s": 56393, "text": "The method appendChild() adds the new child node after the existing child node." }, { "code": null, "e": 56520, "s": 56473, "text": "Syntax of appendChild() method is as follows −" }, { "code": null, "e": 56573, "s": 56520, "text": "Node appendChild(Node newChild) throws DOMException\n" }, { "code": null, "e": 56580, "s": 56573, "text": "Where," }, { "code": null, "e": 56610, "s": 56580, "text": "newChild − Is the node to add" }, { "code": null, "e": 56640, "s": 56610, "text": "newChild − Is the node to add" }, { "code": null, "e": 56676, "s": 56640, "text": "This method returns the Node added." }, { "code": null, "e": 56712, "s": 56676, "text": "This method returns the Node added." }, { "code": null, "e": 56879, "s": 56712, "text": "The following example (appendchildnode_example.htm) parses an XML document (node.xml) into an XML DOM object and appends new child PhoneNo to the element <FirstName>." }, { "code": null, "e": 57651, "s": 56879, "text": "<!DOCTYPE html>\n<html>\n <head>\n <script>\n function loadXMLDoc(filename) {\n if (window.XMLHttpRequest) {\n xhttp = new XMLHttpRequest();\n } else // code for IE5 and IE6 {\n xhttp = new ActiveXObject(\"Microsoft.XMLHTTP\");\n }\n xhttp.open(\"GET\",filename,false);\n xhttp.send();\n return xhttp.responseXML;\n }\n </script>\n </head>\n <body>\n <script>\n xmlDoc = loadXMLDoc(\"/dom/node.xml\");\n\n create_e = xmlDoc.createElement(\"PhoneNo\");\n\n x = xmlDoc.getElementsByTagName(\"FirstName\")[0];\n x.appendChild(create_e);\n\n document.write(x.getElementsByTagName(\"PhoneNo\")[0].nodeName);\n </script>\n </body>\n</html>" }, { "code": null, "e": 57674, "s": 57651, "text": "In the above example −" }, { "code": null, "e": 57742, "s": 57674, "text": "using the method createElement(), a new element PhoneNo is created." }, { "code": null, "e": 57810, "s": 57742, "text": "using the method createElement(), a new element PhoneNo is created." }, { "code": null, "e": 57900, "s": 57810, "text": "The new element PhoneNo is added to the element FirstName using the method appendChild()." }, { "code": null, "e": 57990, "s": 57900, "text": "The new element PhoneNo is added to the element FirstName using the method appendChild()." }, { "code": null, "e": 58177, "s": 57990, "text": "Save this file as appendchildnode_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 PhoneNo." }, { "code": null, "e": 58266, "s": 58177, "text": "The method insertBefore(), inserts the new child nodes before the specified child nodes." }, { "code": null, "e": 58314, "s": 58266, "text": "Syntax of insertBefore() method is as follows −" }, { "code": null, "e": 58383, "s": 58314, "text": "Node insertBefore(Node newChild, Node refChild) throws DOMException\n" }, { "code": null, "e": 58390, "s": 58383, "text": "Where," }, { "code": null, "e": 58423, "s": 58390, "text": "newChild − Is the node to insert" }, { "code": null, "e": 58456, "s": 58423, "text": "newChild − Is the node to insert" }, { "code": null, "e": 58549, "s": 58456, "text": "refChild − Is the reference node, i.e., the node before which the new node must be inserted." }, { "code": null, "e": 58642, "s": 58549, "text": "refChild − Is the reference node, i.e., the node before which the new node must be inserted." }, { "code": null, "e": 58687, "s": 58642, "text": "This method returns the Node being inserted." }, { "code": null, "e": 58732, "s": 58687, "text": "This method returns the Node being inserted." }, { "code": null, "e": 58908, "s": 58732, "text": "The following example (insertnodebefore_example.htm) parses an XML document (node.xml) into an XML DOM object and inserts new child Email before the specified element <Email>." }, { "code": null, "e": 59889, "s": 58908, "text": "<!DOCTYPE html>\n<html>\n <head>\n <script>\n function loadXMLDoc(filename) {\n if (window.XMLHttpRequest) {\n xhttp = new XMLHttpRequest();\n } else // code for IE5 and IE6 {\n xhttp = new ActiveXObject(\"Microsoft.XMLHTTP\");\n }\n xhttp.open(\"GET\",filename,false);\n xhttp.send();\n return xhttp.responseXML;\n }\n </script>\n </head>\n <body>\n <script>\n xmlDoc = loadXMLDoc(\"/dom/node.xml\");\n\n create_e = xmlDoc.createElement(\"Email\");\n\n x = xmlDoc.documentElement;\n y = xmlDoc.getElementsByTagName(\"Email\");\n\n document.write(\"No of Email elements before inserting was: \" + y.length);\n document.write(\"<br>\");\n x.insertBefore(create_e,y[3]);\n\n y=xmlDoc.getElementsByTagName(\"Email\");\n document.write(\"No of Email elements after inserting is: \" + y.length);\n </script>\n </body>\n</html>" }, { "code": null, "e": 59912, "s": 59889, "text": "In the above example −" }, { "code": null, "e": 59978, "s": 59912, "text": "using the method createElement(), a new element Email is created." }, { "code": null, "e": 60044, "s": 59978, "text": "using the method createElement(), a new element Email is created." }, { "code": null, "e": 60133, "s": 60044, "text": "The new element Email is added before the element Email using the method insertBefore()." }, { "code": null, "e": 60222, "s": 60133, "text": "The new element Email is added before the element Email using the method insertBefore()." }, { "code": null, "e": 60306, "s": 60222, "text": "y.length gives the total number of elements added before and after the new element." }, { "code": null, "e": 60390, "s": 60306, "text": "y.length gives the total number of elements added before and after the new element." }, { "code": null, "e": 60563, "s": 60390, "text": "Save this file as insertnodebefore_example.htm on the server path (this file and node.xml should be on the same path in your server). We will receive the following output −" }, { "code": null, "e": 60653, "s": 60563, "text": "No of Email elements before inserting was: 3\nNo of Email elements after inserting is: 4 \n" }, { "code": null, "e": 60732, "s": 60653, "text": "The method insertData(), inserts a string at the specified 16-bit unit offset." }, { "code": null, "e": 60776, "s": 60732, "text": "The insertData() has the following syntax −" }, { "code": null, "e": 60847, "s": 60776, "text": "void insertData(int offset, java.lang.String arg) throws DOMException\n" }, { "code": null, "e": 60854, "s": 60847, "text": "Where," }, { "code": null, "e": 60907, "s": 60854, "text": "offset − is the character offset at which to insert." }, { "code": null, "e": 60960, "s": 60907, "text": "offset − is the character offset at which to insert." }, { "code": null, "e": 61094, "s": 60960, "text": "arg − is the key word to insert the data. It encloses the two parameters offset and string within the parenthesis separated by comma." }, { "code": null, "e": 61228, "s": 61094, "text": "arg − is the key word to insert the data. It encloses the two parameters offset and string within the parenthesis separated by comma." }, { "code": null, "e": 61417, "s": 61228, "text": "The following example (addtext_example.htm) parses an XML document (\"node.xml\") into an XML DOM object and inserts new data MiddleName at the specified position to the element <FirstName>." }, { "code": null, "e": 62180, "s": 61417, "text": "<!DOCTYPE html>\n<html>\n <head>\n <script>\n function loadXMLDoc(filename) {\n if (window.XMLHttpRequest) {\n xhttp = new XMLHttpRequest();\n } else // code for IE5 and IE6 {\n xhttp = new ActiveXObject(\"Microsoft.XMLHTTP\");\n }\n xhttp.open(\"GET\",filename,false);\n xhttp.send();\n return xhttp.responseXML;\n }\n </script>\n </head>\n <body>\n <script>\n xmlDoc = loadXMLDoc(\"/dom/node.xml\");\n\n x = xmlDoc.getElementsByTagName(\"FirstName\")[0].childNodes[0];\n document.write(x.nodeValue);\n x.insertData(6,\"MiddleName\");\n document.write(\"<br>\");\n document.write(x.nodeValue);\n\n </script>\n </body>\n</html>" }, { "code": null, "e": 62363, "s": 62180, "text": "x.insertData(6,\"MiddleName\"); − Here, x holds the name of the specified child name, i.e, <FirstName>. We then insert to this text node the data \"MiddleName\" starting from position 6." }, { "code": null, "e": 62546, "s": 62363, "text": "x.insertData(6,\"MiddleName\"); − Here, x holds the name of the specified child name, i.e, <FirstName>. We then insert to this text node the data \"MiddleName\" starting from position 6." }, { "code": null, "e": 62717, "s": 62546, "text": "Save this file as addtext_example.htm on the server path (this file and node.xml should be on the same path in your server). We will receive the following in the output −" }, { "code": null, "e": 62743, "s": 62717, "text": "Tanmay\nTanmayMiddleName \n" }, { "code": null, "e": 63019, "s": 62743, "text": "In this chapter, we will study about the replace node operation in an XML DOM object. As we know everything in the DOM is maintained in a hierarchical informational unit known as node and the replacing node provides another way to update these specified nodes or a text node." }, { "code": null, "e": 63071, "s": 63019, "text": "Following are the two methods to replace the nodes." }, { "code": null, "e": 63086, "s": 63071, "text": "replaceChild()" }, { "code": null, "e": 63100, "s": 63086, "text": "replaceData()" }, { "code": null, "e": 63173, "s": 63100, "text": "The method replaceChild() replaces the specified node with the new node." }, { "code": null, "e": 63217, "s": 63173, "text": "The insertData() has the following syntax −" }, { "code": null, "e": 63286, "s": 63217, "text": "Node replaceChild(Node newChild, Node oldChild) throws DOMException\n" }, { "code": null, "e": 63293, "s": 63286, "text": "Where," }, { "code": null, "e": 63346, "s": 63293, "text": "newChild − is the new node to put in the child list." }, { "code": null, "e": 63399, "s": 63346, "text": "newChild − is the new node to put in the child list." }, { "code": null, "e": 63450, "s": 63399, "text": "oldChild − is the node being replaced in the list." }, { "code": null, "e": 63501, "s": 63450, "text": "oldChild − is the node being replaced in the list." }, { "code": null, "e": 63540, "s": 63501, "text": "This method returns the node replaced." }, { "code": null, "e": 63579, "s": 63540, "text": "This method returns the node replaced." }, { "code": null, "e": 63754, "s": 63579, "text": "The following example (replacenode_example.htm) parses an XML document (node.xml) into an XML DOM object and replaces the specified node <FirstName> with the new node <Name>." }, { "code": null, "e": 65480, "s": 63754, "text": "<!DOCTYPE html>\n<html>\n <head>\n <script>\n function loadXMLDoc(filename) {\n if (window.XMLHttpRequest) {\n xhttp = new XMLHttpRequest();\n } else // code for IE5 and IE6 {\n xhttp = new ActiveXObject(\"Microsoft.XMLHTTP\");\n }\n xhttp.open(\"GET\",filename,false);\n xhttp.send();\n return xhttp.responseXML;\n }\n </script>\n </head>\n <body>\n <script>\n xmlDoc = loadXMLDoc(\"/dom/node.xml\");\n\n x = xmlDoc.documentElement;\n\n z = xmlDoc.getElementsByTagName(\"FirstName\");\n document.write(\"<b>Content of FirstName element before replace operation</b><br>\");\n for (i=0;i<z.length;i++) {\n document.write(z[i].childNodes[0].nodeValue);\n document.write(\"<br>\");\n }\n //create a Employee element, FirstName element and a text node\n newNode = xmlDoc.createElement(\"Employee\");\n newTitle = xmlDoc.createElement(\"Name\");\n newText = xmlDoc.createTextNode(\"MS Dhoni\");\n\n //add the text node to the title node,\n newTitle.appendChild(newText);\n //add the title node to the book node\n newNode.appendChild(newTitle);\n\n y = xmlDoc.getElementsByTagName(\"Employee\")[0]\n //replace the first book node with the new node\n x.replaceChild(newNode,y);\n\n z = xmlDoc.getElementsByTagName(\"FirstName\");\n document.write(\"<b>Content of FirstName element after replace operation</b><br>\");\n for (i = 0;i<z.length;i++) {\n document.write(z[i].childNodes[0].nodeValue);\n document.write(\"<br>\");\n }\n </script>\n </body>\n</html>" }, { "code": null, "e": 65649, "s": 65480, "text": "Save this file as replacenode_example.htm on the server path (this file and node.xml should be on the same path in your server). We will get the output as shown below −" }, { "code": null, "e": 65795, "s": 65649, "text": "Content of FirstName element before replace operation\nTanmay\nTaniya\nTanisha\n\nContent of FirstName element after replace operation\nTaniya\nTanisha\n" }, { "code": null, "e": 65916, "s": 65795, "text": "The method replaceData() replaces the characters starting at the specified 16-bit unit offset with the specified string." }, { "code": null, "e": 65961, "s": 65916, "text": "The replaceData() has the following syntax −" }, { "code": null, "e": 66044, "s": 65961, "text": "void replaceData(int offset, int count, java.lang.String arg) throws DOMException\n" }, { "code": null, "e": 66050, "s": 66044, "text": "Where" }, { "code": null, "e": 66104, "s": 66050, "text": "offset − is the offset from which to start replacing." }, { "code": null, "e": 66158, "s": 66104, "text": "offset − is the offset from which to start replacing." }, { "code": null, "e": 66318, "s": 66158, "text": "count − is the number of 16-bit units to replace. If the sum of offset and count exceeds length, then all the 16-bit units to the end of the data are replaced." }, { "code": null, "e": 66478, "s": 66318, "text": "count − is the number of 16-bit units to replace. If the sum of offset and count exceeds length, then all the 16-bit units to the end of the data are replaced." }, { "code": null, "e": 66537, "s": 66478, "text": "arg − the DOMString with which the range must be replaced." }, { "code": null, "e": 66596, "s": 66537, "text": "arg − the DOMString with which the range must be replaced." }, { "code": null, "e": 66718, "s": 66596, "text": "The following example (replacedata_example.htm) parses an XML document (node.xml) into an XML DOM object and replaces it." }, { "code": null, "e": 67583, "s": 66718, "text": "<!DOCTYPE html>\n<html>\n <head>\n <script>\n function loadXMLDoc(filename) {\n if (window.XMLHttpRequest) {\n xhttp = new XMLHttpRequest();\n } else // code for IE5 and IE6 {\n xhttp = new ActiveXObject(\"Microsoft.XMLHTTP\");\n }\n xhttp.open(\"GET\",filename,false);\n xhttp.send();\n return xhttp.responseXML;\n }\n </script>\n </head>\n <body>\n <script>\n xmlDoc = loadXMLDoc(\"/dom/node.xml\");\n\n x = xmlDoc.getElementsByTagName(\"ContactNo\")[0].childNodes[0];\n document.write(\"<b>ContactNo before replace operation:</b> \"+x.nodeValue);\n x.replaceData(1,5,\"9999999\");\n document.write(\"<br>\");\n document.write(\"<b>ContactNo after replace operation:</b> \"+x.nodeValue);\n\n </script>\n </body>\n</html>" }, { "code": null, "e": 67606, "s": 67583, "text": "In the above example −" }, { "code": null, "e": 67794, "s": 67606, "text": "x.replaceData(2,3,\"999\"); − Here x holds the text of the specified element <ContactNo> whose text is replaced by the new text \"9999999\", starting from the position 1 till the length of 5." }, { "code": null, "e": 67982, "s": 67794, "text": "x.replaceData(2,3,\"999\"); − Here x holds the text of the specified element <ContactNo> whose text is replaced by the new text \"9999999\", starting from the position 1 till the length of 5." }, { "code": null, "e": 68151, "s": 67982, "text": "Save this file as replacedata_example.htm on the server path (this file and node.xml should be on the same path in your server). We will get the output as shown below −" }, { "code": null, "e": 68249, "s": 68151, "text": "ContactNo before replace operation: 1234567890\n\nContactNo after replace operation: 199999997890 \n" }, { "code": null, "e": 68498, "s": 68249, "text": "In this chapter, we will study about the XML DOM Remove Node operation. The remove node operation removes the specified node from the document. This operation can be implemented to remove the nodes like text node, element node or an attribute node." }, { "code": null, "e": 68566, "s": 68498, "text": "Following are the methods that are used for remove node operation −" }, { "code": null, "e": 68580, "s": 68566, "text": "removeChild()" }, { "code": null, "e": 68594, "s": 68580, "text": "removeChild()" }, { "code": null, "e": 68612, "s": 68594, "text": "removeAttribute()" }, { "code": null, "e": 68630, "s": 68612, "text": "removeAttribute()" }, { "code": null, "e": 68875, "s": 68630, "text": "The method removeChild() removes the child node indicated by oldChild from the list of children, and returns it. Removing a child node is equivalent to removing a text node. Hence, removing a child node removes the text node associated with it." }, { "code": null, "e": 68923, "s": 68875, "text": "The syntax to use removeChild() is as follows −" }, { "code": null, "e": 68976, "s": 68923, "text": "Node removeChild(Node oldChild) throws DOMException\n" }, { "code": null, "e": 68983, "s": 68976, "text": "Where," }, { "code": null, "e": 69021, "s": 68983, "text": "oldChild − is the node being removed." }, { "code": null, "e": 69059, "s": 69021, "text": "oldChild − is the node being removed." }, { "code": null, "e": 69097, "s": 69059, "text": "This method returns the node removed." }, { "code": null, "e": 69135, "s": 69097, "text": "This method returns the node removed." }, { "code": null, "e": 69311, "s": 69135, "text": "The following example (removecurrentnode_example.htm) parses an XML document (node.xml) into an XML DOM object and removes the specified node <ContactNo> from the parent node." }, { "code": null, "e": 70316, "s": 69311, "text": "<!DOCTYPE html>\n<html>\n <head>\n <script>\n function loadXMLDoc(filename) {\n if (window.XMLHttpRequest) {\n xhttp = new XMLHttpRequest();\n } else // code for IE5 and IE6 {\n xhttp = new ActiveXObject(\"Microsoft.XMLHTTP\");\n }\n xhttp.open(\"GET\",filename,false);\n xhttp.send();\n return xhttp.responseXML;\n }\n </script>\n </head>\n <body>\n <script>\n xmlDoc = loadXMLDoc(\"/dom/node.xml\");\n\n document.write(\"<b>Before remove operation, total ContactNo elements: </b>\");\n document.write(xmlDoc.getElementsByTagName(\"ContactNo\").length);\n document.write(\"<br>\");\n\n x = xmlDoc.getElementsByTagName(\"ContactNo\")[0];\n x.parentNode.removeChild(x);\n\n document.write(\"<b>After remove operation, total ContactNo elements: </b>\");\n document.write(xmlDoc.getElementsByTagName(\"ContactNo\").length);\n </script>\n </body>\n</html>" }, { "code": null, "e": 70339, "s": 70316, "text": "In the above example −" }, { "code": null, "e": 70430, "s": 70339, "text": "x = xmlDoc.getElementsByTagName(\"ContactNo\")[0] gets the element <ContactNo> indexed at 0." }, { "code": null, "e": 70521, "s": 70430, "text": "x = xmlDoc.getElementsByTagName(\"ContactNo\")[0] gets the element <ContactNo> indexed at 0." }, { "code": null, "e": 70617, "s": 70521, "text": "x.parentNode.removeChild(x); removes the element <ContactNo> indexed at 0 from the parent node." }, { "code": null, "e": 70713, "s": 70617, "text": "x.parentNode.removeChild(x); removes the element <ContactNo> indexed at 0 from the parent node." }, { "code": null, "e": 70878, "s": 70713, "text": "Save this file as removecurrentnode_example.htm on the server path (this file and node.xml should be on the same path in your server). We get the following result −" }, { "code": null, "e": 70985, "s": 70878, "text": "Before remove operation, total ContactNo elements: 3\nAfter remove operation, total ContactNo elements: 2 \n" }, { "code": null, "e": 71143, "s": 70985, "text": "The following example (removetextNode_example.htm) parses an XML document (node.xml) into an XML DOM object and removes the specified child node <FirstName>." }, { "code": null, "e": 72097, "s": 71143, "text": "<!DOCTYPE html>\n<html>\n <head>\n <script>\n function loadXMLDoc(filename) {\n if (window.XMLHttpRequest) {\n xhttp = new XMLHttpRequest();\n } else // code for IE5 and IE6 {\n xhttp = new ActiveXObject(\"Microsoft.XMLHTTP\");\n }\n xhttp.open(\"GET\",filename,false);\n xhttp.send();\n return xhttp.responseXML;\n }\n </script>\n </head>\n <body>\n <script>\n xmlDoc = loadXMLDoc(\"/dom/node.xml\");\n\n x = xmlDoc.getElementsByTagName(\"FirstName\")[0];\n\n document.write(\"<b>Text node of child node before removal is:</b> \");\n document.write(x.childNodes.length);\n document.write(\"<br>\");\n\n y = x.childNodes[0];\n x.removeChild(y);\n document.write(\"<b>Text node of child node after removal is:</b> \");\n document.write(x.childNodes.length);\n\n </script>\n </body>\n</html>" }, { "code": null, "e": 72120, "s": 72097, "text": "In the above example −" }, { "code": null, "e": 72229, "s": 72120, "text": "x = xmlDoc.getElementsByTagName(\"FirstName\")[0]; − gets the first element <FirstName> to the x indexed at 0." }, { "code": null, "e": 72338, "s": 72229, "text": "x = xmlDoc.getElementsByTagName(\"FirstName\")[0]; − gets the first element <FirstName> to the x indexed at 0." }, { "code": null, "e": 72411, "s": 72338, "text": "y = x.childNodes[0]; − in this line y holds the child node to be remove." }, { "code": null, "e": 72484, "s": 72411, "text": "y = x.childNodes[0]; − in this line y holds the child node to be remove." }, { "code": null, "e": 72538, "s": 72484, "text": "x.removeChild(y); − removes the specified child node." }, { "code": null, "e": 72592, "s": 72538, "text": "x.removeChild(y); − removes the specified child node." }, { "code": null, "e": 72754, "s": 72592, "text": "Save this file as removetextNode_example.htm on the server path (this file and node.xml should be on the same path in your server). We get the following result −" }, { "code": null, "e": 72845, "s": 72754, "text": "Text node of child node before removal is: 1\nText node of child node after removal is: 0 \n" }, { "code": null, "e": 72918, "s": 72845, "text": "The method removeAttribute() removes an attribute of an element by name." }, { "code": null, "e": 72966, "s": 72918, "text": "Syntax to use removeAttribute() is as follows −" }, { "code": null, "e": 73031, "s": 72966, "text": "void removeAttribute(java.lang.String name) throws DOMException\n" }, { "code": null, "e": 73038, "s": 73031, "text": "Where," }, { "code": null, "e": 73085, "s": 73038, "text": "name − is the name of the attribute to remove." }, { "code": null, "e": 73132, "s": 73085, "text": "name − is the name of the attribute to remove." }, { "code": null, "e": 73290, "s": 73132, "text": "The following example (removeelementattribute_example.htm) parses an XML document (node.xml) into an XML DOM object and removes the specified attribute node." }, { "code": null, "e": 74091, "s": 73290, "text": "<!DOCTYPE html>\n<html>\n <head>\n <script>\n function loadXMLDoc(filename) {\n if (window.XMLHttpRequest) {\n xhttp = new XMLHttpRequest();\n } else // code for IE5 and IE6 {\n xhttp = new ActiveXObject(\"Microsoft.XMLHTTP\");\n }\n xhttp.open(\"GET\",filename,false);\n xhttp.send();\n return xhttp.responseXML;\n }\n </script>\n </head>\n <body>\n\n <script>\n xmlDoc = loadXMLDoc(\"/dom/node.xml\");\n\n x = xmlDoc.getElementsByTagName('Employee');\n\n document.write(x[1].getAttribute('category'));\n document.write(\"<br>\");\n\n x[1].removeAttribute('category');\n\n document.write(x[1].getAttribute('category'));\n\n </script>\n </body>\n</html>" }, { "code": null, "e": 74114, "s": 74091, "text": "In the above example −" }, { "code": null, "e": 74227, "s": 74114, "text": "document.write(x[1].getAttribute('category')); − value of attribute category indexed at 1st position is invoked." }, { "code": null, "e": 74340, "s": 74227, "text": "document.write(x[1].getAttribute('category')); − value of attribute category indexed at 1st position is invoked." }, { "code": null, "e": 74405, "s": 74340, "text": "x[1].removeAttribute('category'); − removes the attribute value." }, { "code": null, "e": 74470, "s": 74405, "text": "x[1].removeAttribute('category'); − removes the attribute value." }, { "code": null, "e": 74640, "s": 74470, "text": "Save this file as removeelementattribute_example.htm on the server path (this file and node.xml should be on the same path in your server). We get the following result −" }, { "code": null, "e": 74660, "s": 74640, "text": "Non-Technical\nnull\n" }, { "code": null, "e": 74857, "s": 74660, "text": "In this chapter, we will discucss the Clone Node operation on XML DOM object. Clone node operation is used to create a duplicate copy of the specified node. cloneNode() is used for this operation." }, { "code": null, "e": 75030, "s": 74857, "text": "This method returns a duplicate of this node, i.e., serves as a generic copy constructor for nodes. The duplicate node has no parent ( parentNode is null) and no user data." }, { "code": null, "e": 75080, "s": 75030, "text": "The cloneNode() method has the following syntax −" }, { "code": null, "e": 75110, "s": 75080, "text": "Node cloneNode(boolean deep)\n" }, { "code": null, "e": 75263, "s": 75110, "text": "deep − If true, recursively clones the subtree under the specified node; if false, clone only the node itself (and its attributes, if it is an Element)." }, { "code": null, "e": 75416, "s": 75263, "text": "deep − If true, recursively clones the subtree under the specified node; if false, clone only the node itself (and its attributes, if it is an Element)." }, { "code": null, "e": 75456, "s": 75416, "text": "This method returns the duplicate node." }, { "code": null, "e": 75496, "s": 75456, "text": "This method returns the duplicate node." }, { "code": null, "e": 75654, "s": 75496, "text": "The following example (clonenode_example.htm) parses an XML document (node.xml) into an XML DOM object and creates a deep copy of the first Employee element." }, { "code": null, "e": 76903, "s": 75654, "text": "<!DOCTYPE html>\n<html>\n <head>\n <script>\n function loadXMLDoc(filename) {\n if (window.XMLHttpRequest) {\n xhttp = new XMLHttpRequest();\n } else // code for IE5 and IE6 {\n xhttp = new ActiveXObject(\"Microsoft.XMLHTTP\");\n }\n xhttp.open(\"GET\",filename,false);\n xhttp.send();\n return xhttp.responseXML;\n }\n </script>\n </head>\n <body>\n <script>\n xmlDoc = loadXMLDoc(\"/dom/node.xml\");\n\n x = xmlDoc.getElementsByTagName('Employee')[0];\n clone_node = x.cloneNode(true);\n xmlDoc.documentElement.appendChild(clone_node);\n\n firstname = xmlDoc.getElementsByTagName(\"FirstName\");\n lastname = xmlDoc.getElementsByTagName(\"LastName\");\n\t contact = xmlDoc.getElementsByTagName(\"ContactNo\");\n\t email = xmlDoc.getElementsByTagName(\"Email\");\n for (i = 0;i < firstname.length;i++) {\n document.write(firstname[i].childNodes[0].nodeValue+' \n '+lastname[i].childNodes[0].nodeValue+', \n '+contact[i].childNodes[0].nodeValue+', '+email[i].childNodes[0].nodeValue);\n document.write(\"<br>\");\n }\n </script>\n </body>\n</html>" }, { "code": null, "e": 77063, "s": 76903, "text": "As you can see in the above example, we have set the cloneNode() param to true. Hence each of the child element under the Employee element is copied or cloned." }, { "code": null, "e": 77230, "s": 77063, "text": "Save this file as clonenode_example.htm on the server path (this file and node.xml should be on the same path in your server). We will get the output as shown below −" }, { "code": null, "e": 77421, "s": 77230, "text": "Tanmay Patil, 1234567890, [email protected]\nTaniya Mishra, 1234667898, [email protected]\nTanisha Sharma, 1234562350, [email protected]\nTanmay Patil, 1234567890, [email protected]\n" }, { "code": null, "e": 77491, "s": 77421, "text": "You will notice that the first Employee element is cloned completely." }, { "code": null, "e": 77648, "s": 77491, "text": "Node interface is the primary datatype for the entire Document Object Model. The node is used to represent a single XML element in the entire document tree." }, { "code": null, "e": 77890, "s": 77648, "text": "A node can be any type that is an attribute node, a text node or any other node. The attributes nodeName, nodeValue and attributes are included as a mechanism to get at node information without casting down to the specific derived interface." }, { "code": null, "e": 77952, "s": 77890, "text": "The following table lists the attributes of the Node object −" }, { "code": null, "e": 77993, "s": 77952, "text": "We have listed the node types as below −" }, { "code": null, "e": 78006, "s": 77993, "text": "ELEMENT_NODE" }, { "code": null, "e": 78021, "s": 78006, "text": "ATTRIBUTE_NODE" }, { "code": null, "e": 78033, "s": 78021, "text": "ENTITY_NODE" }, { "code": null, "e": 78055, "s": 78033, "text": "ENTITY_REFERENCE_NODE" }, { "code": null, "e": 78078, "s": 78055, "text": "DOCUMENT_FRAGMENT_NODE" }, { "code": null, "e": 78088, "s": 78078, "text": "TEXT_NODE" }, { "code": null, "e": 78107, "s": 78088, "text": "CDATA_SECTION_NODE" }, { "code": null, "e": 78120, "s": 78107, "text": "COMMENT_NODE" }, { "code": null, "e": 78148, "s": 78120, "text": "PROCESSING_INSTRUCTION_NODE" }, { "code": null, "e": 78162, "s": 78148, "text": "DOCUMENT_NODE" }, { "code": null, "e": 78181, "s": 78162, "text": "DOCUMENT_TYPE_NODE" }, { "code": null, "e": 78195, "s": 78181, "text": "NOTATION_NODE" }, { "code": null, "e": 78249, "s": 78195, "text": "Below table lists the different Node Object methods −" }, { "code": null, "e": 78357, "s": 78249, "text": "This method adds a node after the last child node of the specified element node. It returns the added node." }, { "code": null, "e": 78473, "s": 78357, "text": "This method is used to create a duplicate node, when overridden in a derived class. It returns the duplicated node." }, { "code": null, "e": 78680, "s": 78473, "text": "This method is used to compare the position of the current node against a specified node according to the document order. Returns unsigned short, how the node is positioned relatively to the reference node." }, { "code": null, "e": 78729, "s": 78680, "text": "getFeature(DOMString feature, DOMString version)" }, { "code": null, "e": 78903, "s": 78729, "text": "Returns the DOM Object which implements the specialized APIs of the specified feature and version, if any, or null if there is no object. This has been removed. Refer specs." }, { "code": null, "e": 78930, "s": 78903, "text": "getUserData(DOMString key)" }, { "code": null, "e": 79209, "s": 78930, "text": "Retrieves the object associated to a key on this node. The object must first have been set to this node by calling the setUserData with the same key. Returns the DOMUserData associated to the given key on this node, or null if there was none. This has been removed. Refer specs." }, { "code": null, "e": 79225, "s": 79209, "text": "hasAttributes()" }, { "code": null, "e": 79419, "s": 79225, "text": "Returns whether this node (if it is an element) has any attributes or not. Returns true if any attribute is present in the specified node else returns false. This has been removed. Refer specs." }, { "code": null, "e": 79541, "s": 79419, "text": "Returns whether this node has any children. This method returns true if the current node has child nodes otherwise false." }, { "code": null, "e": 79691, "s": 79541, "text": "This method is used to insert a new node as a child of this node, directly before an existing child of this node. It returns the node being inserted." }, { "code": null, "e": 79862, "s": 79691, "text": "This method accepts a namespace URI as an argument and returns a Boolean with a value of true if the namespace is the default namespace on the given node or false if not." }, { "code": null, "e": 79963, "s": 79862, "text": "This method tests whether two nodes are equal. Returns true if the nodes are equal, false otherwise." }, { "code": null, "e": 79986, "s": 79963, "text": "isSameNode(Node other)" }, { "code": null, "e": 80155, "s": 79986, "text": "This method returns whether current node is the same node as the given one. Returns true if the nodes are the same, false otherwise. This has been removed. Refer specs." }, { "code": null, "e": 80205, "s": 80155, "text": "isSupported(DOMString feature, DOMString version)" }, { "code": null, "e": 80411, "s": 80205, "text": "This method returns whether the specified DOM module is supported by the current node. Returns true if the specified feature is supported on this node, false otherwise. This has been removed. Refer specs." }, { "code": null, "e": 80491, "s": 80411, "text": "This method gets the URI of the namespace associated with the namespace prefix." }, { "code": null, "e": 80660, "s": 80491, "text": "This method returns the closest prefix defined in the current namespace for the namespace URI. Returns an associated namespace prefix if found or null if none is found." }, { "code": null, "e": 80958, "s": 80660, "text": "Normalization adds all the text nodes including attribute nodes which define a normal form where structure of the nodes which contain elements, comments, processing instructions, CDATA sections, and entity references separates the text nodes, i.e, neither adjacent Text nodes nor empty Text nodes." }, { "code": null, "e": 81065, "s": 80958, "text": "This method is used to remove a specified child node from the current node. This returns the node removed." }, { "code": null, "e": 81164, "s": 81065, "text": "This method is used to replace the old child node with a new node. This returns the node replaced." }, { "code": null, "e": 81234, "s": 81164, "text": "setUserData(DOMString key, DOMUserData data, UserDataHandler handler)" }, { "code": null, "e": 81499, "s": 81234, "text": "This method associates an object to a key on this node. The object can later be retrieved from this node by calling getUserData with the same key. This returns the DOMUserData previously associated to the given key on this node. This has been removed. Refer specs." }, { "code": null, "e": 81661, "s": 81499, "text": "The NodeList object specifies the abstraction of an ordered collection of nodes. The items in the NodeList are accessible via an integral index, starting from 0." }, { "code": null, "e": 81727, "s": 81661, "text": "The following table lists the attributes of the NodeList object −" }, { "code": null, "e": 81784, "s": 81727, "text": "The following is the only method of the NodeList object." }, { "code": null, "e": 81920, "s": 81784, "text": "It returns the indexth item in the collection. If index is greater than or equal to the number of nodes in the list, this returns null." }, { "code": null, "e": 82016, "s": 81920, "text": "The NamedNodeMap object is used to represent collections of nodes that can be accessed by name." }, { "code": null, "e": 82083, "s": 82016, "text": "The following table lists the Property of the NamedNodeMap Object." }, { "code": null, "e": 82149, "s": 82083, "text": "The following table lists the methods of the NamedNodeMap object." }, { "code": null, "e": 82187, "s": 82149, "text": "Retrieves the node specified by name." }, { "code": null, "e": 82247, "s": 82187, "text": "Retrieves a node specified by local name and namespace URI." }, { "code": null, "e": 82373, "s": 82247, "text": "Returns the indexth item in the map. If index is greater than or equal to the number of nodes in this map, this returns null." }, { "code": null, "e": 82407, "s": 82373, "text": "Removes a node specified by name." }, { "code": null, "e": 82465, "s": 82407, "text": "Removes a node specified by local name and namespace URI." }, { "code": null, "e": 82595, "s": 82465, "text": "Adds a node using its nodeName attribute. If a node with that name is already present in this map, it is replaced by the new one." }, { "code": null, "e": 82804, "s": 82595, "text": "Adds a node using its namespaceURI and localName. If a node with that namespace URI and that local name is already present in this map, it is replaced by the new one. Replacing a node by itself has no effect." }, { "code": null, "e": 82966, "s": 82804, "text": "The DOMImplementation object provides a number of methods for performing operations that are independent of any particular instance of the document object model." }, { "code": null, "e": 83034, "s": 82966, "text": "Following table lists the methods of the DOMImplementation object −" }, { "code": null, "e": 83116, "s": 83034, "text": "It creates a DOM Document object of the specified type with its document element." }, { "code": null, "e": 83155, "s": 83116, "text": "It creates an empty DocumentType node." }, { "code": null, "e": 83184, "s": 83155, "text": "getFeature(feature, version)" }, { "code": null, "e": 83337, "s": 83184, "text": "This method returns a specialized object which implements the specialized APIs of the specified feature and version. This has been removed. Refer specs." }, { "code": null, "e": 83424, "s": 83337, "text": "This method tests if the DOM implementation implements a specific feature and version." }, { "code": null, "e": 83694, "s": 83424, "text": "The DocumentType objects are the key to access the document's data and in the document, the doctype attribute can have either the null value or the DocumentType Object value. These DocumentType objects act as an interface to the entities described for an XML document. " }, { "code": null, "e": 83764, "s": 83694, "text": "The following table lists the attributes of the DocumentType object −" }, { "code": null, "e": 83857, "s": 83764, "text": "DocumentType inherits methods from its parent, Node, and implements the ChildNode interface." }, { "code": null, "e": 83994, "s": 83857, "text": "ProcessingInstruction gives that application-specific information which is generally included in the prolog section of the XML document." }, { "code": null, "e": 84253, "s": 83994, "text": "Processing instructions (PIs) can be used to pass information to applications. PIs can appear anywhere in the document outside the markup. They can appear in the prolog, including the document type definition (DTD), in textual content, or after the document." }, { "code": null, "e": 84386, "s": 84253, "text": "A PI starts with a special tag <? and ends with ?>. Processing of the contents ends immediately after the string ?> is encountered." }, { "code": null, "e": 84465, "s": 84386, "text": "The following table lists the attributes of the ProcessingInstruction object −" }, { "code": null, "e": 84640, "s": 84465, "text": "Entity interface represents a known entity, either parsed or unparsed, in an XML document. The nodeName attribute that is inherited from Node contains the name of the entity." }, { "code": null, "e": 84731, "s": 84640, "text": "An Entity object does not have any parent node, and all its successor nodes are read-only." }, { "code": null, "e": 84795, "s": 84731, "text": "The following table lists the attributes of the Entity object −" }, { "code": null, "e": 85080, "s": 84795, "text": "The EntityReference objects are the general entity references which are inserted into the XML document providing scope to replace the text. The EntityReference Object does not work for the pre-defined entities since they are considered to be expanded by the HTML or the XML processor." }, { "code": null, "e": 85166, "s": 85080, "text": "This interface does not have properties or methods of its own but inherits from Node." }, { "code": null, "e": 85516, "s": 85166, "text": "In this chapter, we will study about the XML DOM Notation object. The notation object property provides a scope to recognize the format of elements with a notation attribute, a particular processing instruction or a non-XML data. The Node Object properties and methods can be performed on the Notation Object since that is also considered as a Node." }, { "code": null, "e": 85621, "s": 85516, "text": "This object inherits methods and properties from Node. Its nodeName is the notation name. Has no parent." }, { "code": null, "e": 85687, "s": 85621, "text": "The following table lists the attributes of the Notation object −" }, { "code": null, "e": 86035, "s": 85687, "text": "The XML elements can be defined as building blocks of XML. Elements can behave as containers to hold text, elements, attributes, media objects or all of these. Whenever parser parses an XML document against the well-formedness, parser navigates through an element node. An element node contains the text within it which is called as the text node." }, { "code": null, "e": 86252, "s": 86035, "text": "Element object inherits the properties and the methods of the Node object as element object is also considered as a Node. Other than the node object properties and methods it has the following properties and methods." }, { "code": null, "e": 86317, "s": 86252, "text": "The following table lists the attributes of the Element object −" }, { "code": null, "e": 86364, "s": 86317, "text": "Below table lists the Element Object methods −" }, { "code": null, "e": 86758, "s": 86364, "text": "Attr interface represents an attribute in an Element object. Typically, the allowable values for the attribute are defined in a schema associated with the document. Attr objects are not considered as part of the document tree since they are not actually child nodes of the element they describe. Thus for the child nodes parentNode, previousSibling and nextSibling the attribute value is null." }, { "code": null, "e": 86825, "s": 86758, "text": "The following table lists the attributes of the Attribute object −" }, { "code": null, "e": 87331, "s": 86825, "text": "In this chapter, we will study about the XML DOM CDATASection Object. The text present within an XML document is parsed or unparsed depending on what it is declared. If the text is declared as Parse Character Data (PCDATA), it is parsed by the parser to convert an XML document into an XML DOM Object. On the other hand, if the text is declared as the unparsed Character Data (CDATA) the text within is not parsed by the XML parser. These are not considered as the markup and will not expand the entities." }, { "code": null, "e": 87568, "s": 87331, "text": "The purpose of using the CDATASection object is to escape the blocks of text containing characters that would otherwise be regarded as markup. \"]]>\", this is the only delimiter recognized in a CDATA section that ends the CDATA section." }, { "code": null, "e": 87737, "s": 87568, "text": "The CharacterData.data attribute holds the text that is contained by the CDATA section. This interface inherits the CharatcterData interface through the Text interface." }, { "code": null, "e": 87996, "s": 87737, "text": "In this chapter, we will study about the Comment object. Comments are added as a notes or the lines for understanding the purpose of an XML code. Comments can be used to include related links, information and terms. These may appear anywhere in the XML code." }, { "code": null, "e": 88096, "s": 87996, "text": "The comment interface inherits the CharacterData interface representing the content of the comment." }, { "code": null, "e": 88135, "s": 88096, "text": "XML comment has the following syntax −" }, { "code": null, "e": 88164, "s": 88135, "text": "<!-------Your comment----->\n" }, { "code": null, "e": 88320, "s": 88164, "text": "A comment starts with <!-- and ends with -->. You can add textual notes as comments between the characters. You must not nest one comment inside the other." }, { "code": null, "e": 88559, "s": 88320, "text": "XMLHttpRequest object establishes a medium between a web page's client-side and server-side that can be used by the many scripting languages like JavaScript, JScript, VBScript and other web browser to transfer and manipulate the XML data." }, { "code": null, "e": 88779, "s": 88559, "text": "With the XMLHttpRequest object it is possible to update the part of a web page without reloading the whole page, request and receive the data from a server after the page has been loaded and send the data to the server." }, { "code": null, "e": 88836, "s": 88779, "text": "An XMLHttpRequest object can be instatiated as follows −" }, { "code": null, "e": 88869, "s": 88836, "text": "xmlhttp = new XMLHttpRequest();\n" }, { "code": null, "e": 88983, "s": 88869, "text": "To handle all browsers, including IE5 and IE6, check if the browser supports the XMLHttpRequest object as below −" }, { "code": null, "e": 89208, "s": 88983, "text": "if(window.XMLHttpRequest) // for Firefox, IE7+, Opera, Safari, ... {\n xmlHttp = new XMLHttpRequest();\n} else if(window.ActiveXObject) // for Internet Explorer 5 or 6 {\n xmlHttp = new ActiveXObject(\"Microsoft.XMLHTTP\");\n}" }, { "code": null, "e": 89290, "s": 89208, "text": "Examples to load an XML file using the XMLHttpRequest object can be referred here" }, { "code": null, "e": 89359, "s": 89290, "text": "The following table lists the methods of the XMLHttpRequest object −" }, { "code": null, "e": 89367, "s": 89359, "text": "abort()" }, { "code": null, "e": 89404, "s": 89367, "text": "Terminates the current request made." }, { "code": null, "e": 89428, "s": 89404, "text": "getAllResponseHeaders()" }, { "code": null, "e": 89516, "s": 89428, "text": "Returns all the response headers as a string, or null if no response has been received." }, { "code": null, "e": 89536, "s": 89516, "text": "getResponseHeader()" }, { "code": null, "e": 89702, "s": 89536, "text": "Returns the string containing the text of the specified header, or null if either the response has not yet been received or the header doesn't exist in the response." }, { "code": null, "e": 89736, "s": 89702, "text": "open(method,url,async,uname,pswd)" }, { "code": null, "e": 89871, "s": 89736, "text": "It is used in conjugation with the Send method to send the request to the server. The open method specifies the following parameters −" }, { "code": null, "e": 89928, "s": 89871, "text": "method − specifies the type of request i.e. Get or Post." }, { "code": null, "e": 89985, "s": 89928, "text": "method − specifies the type of request i.e. Get or Post." }, { "code": null, "e": 90023, "s": 89985, "text": "url − it is the location of the file." }, { "code": null, "e": 90061, "s": 90023, "text": "url − it is the location of the file." }, { "code": null, "e": 90323, "s": 90061, "text": "async − indicates how the request should be handled. It is boolean value. where,\n\n'true' means the request is processed asynchronously without waiting for a Http response.\n'false' means the request is processed synchronously after receiving the Http response.\n\n" }, { "code": null, "e": 90404, "s": 90323, "text": "async − indicates how the request should be handled. It is boolean value. where," }, { "code": null, "e": 90494, "s": 90404, "text": "'true' means the request is processed asynchronously without waiting for a Http response." }, { "code": null, "e": 90584, "s": 90494, "text": "'true' means the request is processed asynchronously without waiting for a Http response." }, { "code": null, "e": 90672, "s": 90584, "text": "'false' means the request is processed synchronously after receiving the Http response." }, { "code": null, "e": 90760, "s": 90672, "text": "'false' means the request is processed synchronously after receiving the Http response." }, { "code": null, "e": 90785, "s": 90760, "text": "uname − is the username." }, { "code": null, "e": 90810, "s": 90785, "text": "uname − is the username." }, { "code": null, "e": 90834, "s": 90810, "text": "pswd − is the password." }, { "code": null, "e": 90858, "s": 90834, "text": "pswd − is the password." }, { "code": null, "e": 90871, "s": 90858, "text": "send(string)" }, { "code": null, "e": 90947, "s": 90871, "text": "It is used to send the request working in conjugation with the Open method." }, { "code": null, "e": 90966, "s": 90947, "text": "setRequestHeader()" }, { "code": null, "e": 91033, "s": 90966, "text": "Header contains the label/value pair to which the request is sent." }, { "code": null, "e": 91105, "s": 91033, "text": "The following table lists the attributes of the XMLHttpRequest object −" }, { "code": null, "e": 91124, "s": 91105, "text": "onreadystatechange" }, { "code": null, "e": 91193, "s": 91124, "text": "It is an event based property which is set on at every state change." }, { "code": null, "e": 91204, "s": 91193, "text": "readyState" }, { "code": null, "e": 91327, "s": 91204, "text": "This describes the present state of the XMLHttpRequest object. There are five possible states of the readyState property −" }, { "code": null, "e": 91380, "s": 91327, "text": "readyState = 0 − means request is yet to initialize." }, { "code": null, "e": 91433, "s": 91380, "text": "readyState = 0 − means request is yet to initialize." }, { "code": null, "e": 91466, "s": 91433, "text": "readyState = 1 − request is set." }, { "code": null, "e": 91499, "s": 91466, "text": "readyState = 1 − request is set." }, { "code": null, "e": 91533, "s": 91499, "text": "readyState = 2 − request is sent." }, { "code": null, "e": 91567, "s": 91533, "text": "readyState = 2 − request is sent." }, { "code": null, "e": 91607, "s": 91567, "text": "readyState = 3 − request is processing." }, { "code": null, "e": 91647, "s": 91607, "text": "readyState = 3 − request is processing." }, { "code": null, "e": 91686, "s": 91647, "text": "readyState = 4 − request is completed." }, { "code": null, "e": 91725, "s": 91686, "text": "readyState = 4 − request is completed." }, { "code": null, "e": 91738, "s": 91725, "text": "responseText" }, { "code": null, "e": 91810, "s": 91738, "text": "This property is used when the response from the server is a text file." }, { "code": null, "e": 91822, "s": 91810, "text": "responseXML" }, { "code": null, "e": 91894, "s": 91822, "text": "This property is used when the response from the server is an XML file." }, { "code": null, "e": 91901, "s": 91894, "text": "status" }, { "code": null, "e": 91912, "s": 91901, "text": "statusText" }, { "code": null, "e": 92003, "s": 91912, "text": "Gives the status of the Http request object as a string. For example, \"Not Found\" or \"OK\"." }, { "code": null, "e": 92036, "s": 92003, "text": "node.xml contents are as below −" }, { "code": null, "e": 92706, "s": 92036, "text": "<?xml version = \"1.0\"?>\n<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": 92857, "s": 92706, "text": "Following example demonstrates how to retrive specific information of a resource file using the method getResponseHeader() and the property readState." }, { "code": null, "e": 94128, "s": 92857, "text": "<!DOCTYPE html>\n<html>\n <head>\n <meta http-equiv = \"content-type\" content = \"text/html; charset = iso-8859-2\" />\n <script>\n function loadXMLDoc() {\n var xmlHttp = null;\n if(window.XMLHttpRequest) // for Firefox, IE7+, Opera, Safari, ... {\n xmlHttp = new XMLHttpRequest();\n }\n else if(window.ActiveXObject) // for Internet Explorer 5 or 6 {\n xmlHttp = new ActiveXObject(\"Microsoft.XMLHTTP\");\n }\n\n return xmlHttp;\n }\n\n function makerequest(serverPage, myDiv) {\n var request = loadXMLDoc();\n request.open(\"GET\", serverPage);\n request.send(null);\n\n request.onreadystatechange = function() {\n if (request.readyState == 4) {\n document.getElementById(myDiv).innerHTML = request.getResponseHeader(\"Content-length\");\n }\n }\n }\n </script>\n </head>\n <body>\n <button type = \"button\" onclick=\"makerequest('/dom/node.xml', 'ID')\">Click me to get the specific ResponseHeader</button>\n <div id = \"ID\">Specific header information is returned.</div>\n </body>\n</html>" }, { "code": null, "e": 94315, "s": 94128, "text": "Save this file as elementattribute_removeAttributeNS.htm on the server path (this file and node_ns.xml should be on the same path in your server). We will get the output as shown below −" }, { "code": null, "e": 94389, "s": 94315, "text": "Before removing the attributeNS: en\nAfter removing the attributeNS: null\n" }, { "code": null, "e": 94551, "s": 94389, "text": "Following example demonstrates how to retrieve the header information of a resource file, using the method getAllResponseHeaders() using the property readyState." }, { "code": null, "e": 95762, "s": 94551, "text": "<!DOCTYPE html>\n<html>\n <head>\n <meta http-equiv=\"content-type\" content=\"text/html; charset=iso-8859-2\" />\n <script>\n function loadXMLDoc() {\n var xmlHttp = null;\n\n if(window.XMLHttpRequest) // for Firefox, IE7+, Opera, Safari, ... {\n xmlHttp = new XMLHttpRequest();\n } else if(window.ActiveXObject) // for Internet Explorer 5 or 6 {\n xmlHttp = new ActiveXObject(\"Microsoft.XMLHTTP\");\n }\n\n return xmlHttp;\n }\n\n function makerequest(serverPage, myDiv) {\n var request = loadXMLDoc();\n request.open(\"GET\", serverPage);\n request.send(null);\n request.onreadystatechange = function() {\n if (request.readyState == 4) {\n document.getElementById(myDiv).innerHTML = request.getAllResponseHeaders();\n }\n }\n }\n </script>\n </head>\n <body>\n <button type = \"button\" onclick = \"makerequest('/dom/node.xml', 'ID')\">\n Click me to load the AllResponseHeaders</button>\n <div id = \"ID\"></div>\n </body>\n</html>" }, { "code": null, "e": 95952, "s": 95762, "text": "Save this file as http_allheader.html on the server path (this file and node.xml should be on the same path in your server). We will get the output as shown below (depends on the browser) −" }, { "code": null, "e": 96217, "s": 95952, "text": "Date: Sat, 27 Sep 2014 07:48:07 GMT Server: Apache Last-Modified: \n Wed, 03 Sep 2014 06:35:30 GMT Etag: \"464bf9-2af-50223713b8a60\" Accept-Ranges: bytes Vary: Accept-Encoding,User-Agent \n Content-Encoding: gzip Content-Length: 256 Content-Type: text/xml \n" }, { "code": null, "e": 96310, "s": 96217, "text": "The DOMException represents an abnormal event happening when a method or a property is used." }, { "code": null, "e": 96370, "s": 96310, "text": "Below table lists the properties of the DOMException object" }, { "code": null, "e": 96375, "s": 96370, "text": "name" }, { "code": null, "e": 96488, "s": 96375, "text": "Returns a DOMString that contains one of the string associated with an error constant (as seen the table below)." }, { "code": null, "e": 96503, "s": 96488, "text": "IndexSizeError" }, { "code": null, "e": 96659, "s": 96503, "text": "The index is not in the allowed range. For example, this can be thrown by the Range object. (Legacy code value: 1 and legacy constant name: INDEX_SIZE_ERR)" }, { "code": null, "e": 96681, "s": 96659, "text": "HierarchyRequestError" }, { "code": null, "e": 96792, "s": 96681, "text": "The node tree hierarchy is not correct. (Legacy code value: 3 and legacy constant name: HIERARCHY_REQUEST_ERR)" }, { "code": null, "e": 96811, "s": 96792, "text": "WrongDocumentError" }, { "code": null, "e": 96916, "s": 96811, "text": "The object is in the wrong document. (Legacy code value: 4 and legacy constant name: WRONG_DOCUMENT_ERR)" }, { "code": null, "e": 96938, "s": 96916, "text": "InvalidCharacterError" }, { "code": null, "e": 97049, "s": 96938, "text": "The string contains invalid characters. (Legacy code value: 5 and legacy constant name: INVALID_CHARACTER_ERR)" }, { "code": null, "e": 97076, "s": 97049, "text": "NoModificationAllowedError" }, { "code": null, "e": 97184, "s": 97076, "text": "The object cannot be modified. (Legacy code value: 7 and legacy constant name: NO_MODIFICATION_ALLOWED_ERR)" }, { "code": null, "e": 97198, "s": 97184, "text": "NotFoundError" }, { "code": null, "e": 97294, "s": 97198, "text": "The object cannot be found here. (Legacy code value: 8 and legacy constant name: NOT_FOUND_ERR)" }, { "code": null, "e": 97312, "s": 97294, "text": "NotSupportedError" }, { "code": null, "e": 97411, "s": 97312, "text": "The operation is not supported. (Legacy code value: 9 and legacy constant name: NOT_SUPPORTED_ERR)" }, { "code": null, "e": 97429, "s": 97411, "text": "InvalidStateError" }, { "code": null, "e": 97532, "s": 97429, "text": "The object is in an invalid state. (Legacy code value: 11 and legacy constant name: INVALID_STATE_ERR)" }, { "code": null, "e": 97544, "s": 97532, "text": "SyntaxError" }, { "code": null, "e": 97652, "s": 97544, "text": "The string did not match the expected pattern. (Legacy code value: 12 and legacy constant name: SYNTAX_ERR)" }, { "code": null, "e": 97677, "s": 97652, "text": "InvalidModificationError" }, { "code": null, "e": 97795, "s": 97677, "text": "The object cannot be modified in this way. (Legacy code value: 13 and legacy constant name: INVALID_MODIFICATION_ERR)" }, { "code": null, "e": 97810, "s": 97795, "text": "NamespaceError" }, { "code": null, "e": 97925, "s": 97810, "text": "The operation is not allowed by Namespaces in XML. (Legacy code value: 14 and legacy constant name: NAMESPACE_ERR)" }, { "code": null, "e": 97944, "s": 97925, "text": "InvalidAccessError" }, { "code": null, "e": 98068, "s": 97944, "text": "The object does not support the operation or argument. (Legacy code value: 15 and legacy constant name: INVALID_ACCESS_ERR)" }, { "code": null, "e": 98086, "s": 98068, "text": "TypeMismatchError" }, { "code": null, "e": 98329, "s": 98086, "text": "The type of the object does not match the expected type. (Legacy code value: 17 and legacy constant name: TYPE_MISMATCH_ERR) This value is deprecated, the JavaScript TypeError exception is now raised instead of a DOMException with this value." }, { "code": null, "e": 98343, "s": 98329, "text": "SecurityError" }, { "code": null, "e": 98433, "s": 98343, "text": "The operation is insecure. (Legacy code value: 18 and legacy constant name: SECURITY_ERR)" }, { "code": null, "e": 98446, "s": 98433, "text": "NetworkError" }, { "code": null, "e": 98534, "s": 98446, "text": "A network error occurred. (Legacy code value: 19 and legacy constant name: NETWORK_ERR)" }, { "code": null, "e": 98545, "s": 98534, "text": "AbortError" }, { "code": null, "e": 98632, "s": 98545, "text": "The operation was aborted. (Legacy code value: 20 and legacy constant name: ABORT_ERR)" }, { "code": null, "e": 98649, "s": 98632, "text": "URLMismatchError" }, { "code": null, "e": 98758, "s": 98649, "text": "The given URL does not match another URL. (Legacy code value: 21 and legacy constant name: URL_MISMATCH_ERR)" }, { "code": null, "e": 98777, "s": 98758, "text": "QuotaExceededError" }, { "code": null, "e": 98875, "s": 98777, "text": "The quota has been exceeded. (Legacy code value: 22 and legacy constant name: QUOTA_EXCEEDED_ERR)" }, { "code": null, "e": 98888, "s": 98875, "text": "TimeoutError" }, { "code": null, "e": 98975, "s": 98888, "text": "The operation timed out. (Legacy code value: 23 and legacy constant name: TIMEOUT_ERR)" }, { "code": null, "e": 98996, "s": 98975, "text": "InvalidNodeTypeError" }, { "code": null, "e": 99139, "s": 98996, "text": "The node is incorrect or has an incorrect ancestor for this operation. (Legacy code value: 24 and legacy constant name: INVALID_NODE_TYPE_ERR)" }, { "code": null, "e": 99154, "s": 99139, "text": "DataCloneError" }, { "code": null, "e": 99248, "s": 99154, "text": "The object cannot be cloned. (Legacy code value: 25 and legacy constant name: DATA_CLONE_ERR)" }, { "code": null, "e": 99262, "s": 99248, "text": "EncodingError" }, { "code": null, "e": 99372, "s": 99262, "text": "The encoding operation, being an encoding or a decoding one, failed (No legacy code value and constant name)." }, { "code": null, "e": 99389, "s": 99372, "text": "NotReadableError" }, { "code": null, "e": 99470, "s": 99389, "text": "The input/output read operation failed (No legacy code value and constant name)." }, { "code": null, "e": 99565, "s": 99470, "text": "Following example demonstrates how using a not well-formed XML document causes a DOMException." }, { "code": null, "e": 99599, "s": 99565, "text": "error.xml contents are as below −" }, { "code": null, "e": 99936, "s": 99599, "text": "<?xml version = \"1.0\" encoding = \"UTF-8\" standalone = \"no\" ?>\n<Company id = \"companyid\">\n <Employee category = \"Technical\" id = \"firstelement\" type = \"text/html\">\n <FirstName>Tanmay</first>\n <LastName>Patil</LastName>\n <ContactNo>1234567890</ContactNo>\n <Email>[email protected]</Email>\n </Employee>\n</Company>" }, { "code": null, "e": 100001, "s": 99936, "text": "Following example demonstrates the usage of the name attribute −" }, { "code": null, "e": 100863, "s": 100001, "text": "<html>\n <head>\n <script>\n function loadXMLDoc(filename) {\n if (window.XMLHttpRequest) {\n xhttp = new XMLHttpRequest();\n } else // code for IE5 and IE6 {\n xhttp = new ActiveXObject(\"Microsoft.XMLHTTP\");\n }\n xhttp.open(\"GET\",filename,false);\n xhttp.send();\n return xhttp.responseXML;\n }\n </script>\n </head>\n <body>\n <script>\n try {\n xmlDoc = loadXMLDoc(\"/dom/error.xml\");\n var node = xmlDoc.getElementsByTagName(\"to\").item(0);\n var refnode = node.nextSibling;\n var newnode = xmlDoc.createTextNode('That is why you fail.');\n node.insertBefore(newnode, refnode);\n } catch(err) {\n document.write(err.name);\n }\n </script>\n </body>\n</html>" }, { "code": null, "e": 101031, "s": 100863, "text": "Save this file as domexcption_name.html on the server path (this file and error.xml should be on the same path in your server). We will get the output as shown below −" }, { "code": null, "e": 101042, "s": 101031, "text": "TypeError\n" }, { "code": null, "e": 101075, "s": 101042, "text": "\n 41 Lectures \n 5 hours \n" }, { "code": null, "e": 101097, "s": 101075, "text": " Abhishek And Pukhraj" }, { "code": null, "e": 101132, "s": 101097, "text": "\n 33 Lectures \n 3.5 hours \n" }, { "code": null, "e": 101154, "s": 101132, "text": " Abhishek And Pukhraj" }, { "code": null, "e": 101187, "s": 101154, "text": "\n 15 Lectures \n 1 hours \n" }, { "code": null, "e": 101200, "s": 101187, "text": " Zach Miller" }, { "code": null, "e": 101233, "s": 101200, "text": "\n 15 Lectures \n 4 hours \n" }, { "code": null, "e": 101257, "s": 101233, "text": " Prof. Paul Cline, Ed.D" }, { "code": null, "e": 101290, "s": 101257, "text": "\n 13 Lectures \n 4 hours \n" }, { "code": null, "e": 101314, "s": 101290, "text": " Prof. Paul Cline, Ed.D" }, { "code": null, "e": 101347, "s": 101314, "text": "\n 17 Lectures \n 2 hours \n" }, { "code": null, "e": 101364, "s": 101347, "text": " Laurence Svekis" }, { "code": null, "e": 101371, "s": 101364, "text": " Print" }, { "code": null, "e": 101382, "s": 101371, "text": " Add Notes" } ]
How to count number of rows in a table with jQuery?
Live Demo <html> <head> <title>table</title> <style type="text/css"> table,th,td { border:2px solid black; margin-left:400px; } h2 { margin-left:400px; } button { margin-left:400px; } </style> <script src="../../Scripts/jquery-1.4.1.min.js" type="text/javascript"></script> <script type="text/javascript"> $(document).ready(function () { $("button").click(function () { var rowcount = $('table tr').length; alert("No. Of Rows ::" +rowcount); }); }); </script> </head> <body> <div> <h2>HTML TABLE</h2> <table> <tr> <th> NAME </th> <th> AGE </th> </tr> <tr> <td>DD</td> <td>35</td> </tr> <tr> <td>SB</td> <td>35</td> </tr> <tr> <td>AD</td> <td>5</td> </tr> <tr> <td>AA</td> <td>5</td> </tr> </table> <button type="button" id="btn">Click Here</button> </div> </body> </html>
[ { "code": null, "e": 1073, "s": 1062, "text": " Live Demo" }, { "code": null, "e": 1922, "s": 1073, "text": "<html>\n<head>\n<title>table</title>\n <style type=\"text/css\">\n table,th,td {\n border:2px solid black;\n margin-left:400px;\n }\n h2 {\n margin-left:400px;\n }\n button {\n margin-left:400px;\n }\n </style>\n <script src=\"../../Scripts/jquery-1.4.1.min.js\" type=\"text/javascript\"></script>\n<script type=\"text/javascript\">\n $(document).ready(function () {\n $(\"button\").click(function () {\n var rowcount = $('table tr').length;\n alert(\"No. Of Rows ::\" +rowcount);\n });\n });\n</script>\n</head>\n<body>\n<div>\n<h2>HTML TABLE</h2>\n<table>\n<tr>\n<th>\nNAME\n</th>\n<th>\nAGE\n</th>\n</tr>\n<tr>\n<td>DD</td>\n<td>35</td>\n</tr>\n<tr>\n<td>SB</td>\n<td>35</td>\n</tr>\n<tr>\n<td>AD</td>\n<td>5</td>\n</tr>\n<tr>\n<td>AA</td>\n<td>5</td>\n</tr>\n</table>\n<button type=\"button\" id=\"btn\">Click Here</button>\n</div>\n</body>\n</html>" } ]
Deletion of array of objects in C++ - GeeksforGeeks
18 Jan, 2021 Need for deletion of the object: To avoid memory leak as when an object is created dynamically using new, it occupies memory in the Heap Section. If objects are not deleted explicitly then the program will crash during runtime. Program 1: Create an object of the class which is created dynamically using the new operator and deleting it explicitly using the delete operator: C++ // C++ program to create an object// dynamically and delete explicitly#include <iostream>using namespace std; // Classclass Student { public: // Constructor Student() { cout << "Constructor is called!\n"; } // Destructor ~Student() { cout << "Destructor is called!\n"; } // Function to display the message void write() { cout << "Writing!\n"; }}; // Driver Codeint main(){ // Create an array of objects Student* student = new Student(); // Function Call to write() // using instance student->write(); // De-allocate the memory // explicitly delete student; return 0;} Constructor is called! Writing! Destructor is called! Program 2: Create an array of objects using the new operator dynamically. Whenever an array of the object of a class is created at runtime then it is the programmer’s responsibility to delete it and avoid a memory leak: C++ // C++ program to create an array of// objects and deleting it explicitly#include <iostream>using namespace std; // Classclass Student { public: // Constructor Student() { cout << "Constructor is called!\n"; } // Destructor ~Student() { cout << "Destructor is called!\n"; } // Function to display message void write() { cout << "Writing!\n"; }}; // Driver Codeint main(){ // Create an array of the object // dynamically Student* student = new Student[3]; // Function Call to write() student[0].write(); student[1].write(); student[2].write(); // De-allocate the memory // explicitly delete[] student; return 0;} Constructor is called! Constructor is called! Constructor is called! Writing! Writing! Writing! Destructor is called! Destructor is called! Destructor is called! Program 3: Below is the program where delete is used to delete an array of objects: C++ // C++ program to delete array of// objects#include <iostream>using namespace std; // Classclass Student { public: // Constructor Student() { cout << "Constructor is called!\n"; } // Destructor ~Student() { cout << "Destructor is called!\n"; } // Function to display message void write() { cout << "Writing!\n"; }}; // Driver Codeint main(){ // Create an object dynamically Student* student = new Student[3]; // Function call to write() student[0].write(); student[1].write(); student[2].write(); // De-allocate the memory // explicitly delete student; return 0;} Explanation: This program will crash in runtime. In this program, constructors are working properly but the destructor is executed only for the first object, and after that program is crashing at runtime because of a memory leak. It is because 3 objects are created at runtime but only one object is deleted explicitly and that’s why the remaining two objects are crashing at runtime. Conclusion:In C++, the single object of the class which is created at runtime using a new operator is deleted by using the delete operator, while the array of objects is deleted using the delete[] operator so that it cannot lead to a memory leak. C Basics CPP-Basics new and delete C++ C++ Programs CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Operator Overloading in C++ Polymorphism in C++ Friend class and function in C++ Sorting a vector in C++ Iterators in C++ STL Header files in C/C++ and its uses C++ Program for QuickSort How to return multiple values from a function in C or C++? Program to print ASCII Value of a character CSV file management using C++
[ { "code": null, "e": 24098, "s": 24070, "text": "\n18 Jan, 2021" }, { "code": null, "e": 24131, "s": 24098, "text": "Need for deletion of the object:" }, { "code": null, "e": 24244, "s": 24131, "text": "To avoid memory leak as when an object is created dynamically using new, it occupies memory in the Heap Section." }, { "code": null, "e": 24326, "s": 24244, "text": "If objects are not deleted explicitly then the program will crash during runtime." }, { "code": null, "e": 24473, "s": 24326, "text": "Program 1: Create an object of the class which is created dynamically using the new operator and deleting it explicitly using the delete operator:" }, { "code": null, "e": 24477, "s": 24473, "text": "C++" }, { "code": "// C++ program to create an object// dynamically and delete explicitly#include <iostream>using namespace std; // Classclass Student { public: // Constructor Student() { cout << \"Constructor is called!\\n\"; } // Destructor ~Student() { cout << \"Destructor is called!\\n\"; } // Function to display the message void write() { cout << \"Writing!\\n\"; }}; // Driver Codeint main(){ // Create an array of objects Student* student = new Student(); // Function Call to write() // using instance student->write(); // De-allocate the memory // explicitly delete student; return 0;}", "e": 25143, "s": 24477, "text": null }, { "code": null, "e": 25198, "s": 25143, "text": "Constructor is called!\nWriting!\nDestructor is called!\n" }, { "code": null, "e": 25418, "s": 25198, "text": "Program 2: Create an array of objects using the new operator dynamically. Whenever an array of the object of a class is created at runtime then it is the programmer’s responsibility to delete it and avoid a memory leak:" }, { "code": null, "e": 25422, "s": 25418, "text": "C++" }, { "code": "// C++ program to create an array of// objects and deleting it explicitly#include <iostream>using namespace std; // Classclass Student { public: // Constructor Student() { cout << \"Constructor is called!\\n\"; } // Destructor ~Student() { cout << \"Destructor is called!\\n\"; } // Function to display message void write() { cout << \"Writing!\\n\"; }}; // Driver Codeint main(){ // Create an array of the object // dynamically Student* student = new Student[3]; // Function Call to write() student[0].write(); student[1].write(); student[2].write(); // De-allocate the memory // explicitly delete[] student; return 0;}", "e": 26137, "s": 25422, "text": null }, { "code": null, "e": 26300, "s": 26137, "text": "Constructor is called!\nConstructor is called!\nConstructor is called!\nWriting!\nWriting!\nWriting!\nDestructor is called!\nDestructor is called!\nDestructor is called!\n" }, { "code": null, "e": 26311, "s": 26300, "text": "Program 3:" }, { "code": null, "e": 26384, "s": 26311, "text": "Below is the program where delete is used to delete an array of objects:" }, { "code": null, "e": 26388, "s": 26384, "text": "C++" }, { "code": "// C++ program to delete array of// objects#include <iostream>using namespace std; // Classclass Student { public: // Constructor Student() { cout << \"Constructor is called!\\n\"; } // Destructor ~Student() { cout << \"Destructor is called!\\n\"; } // Function to display message void write() { cout << \"Writing!\\n\"; }}; // Driver Codeint main(){ // Create an object dynamically Student* student = new Student[3]; // Function call to write() student[0].write(); student[1].write(); student[2].write(); // De-allocate the memory // explicitly delete student; return 0;}", "e": 27052, "s": 26388, "text": null }, { "code": null, "e": 27437, "s": 27052, "text": "Explanation: This program will crash in runtime. In this program, constructors are working properly but the destructor is executed only for the first object, and after that program is crashing at runtime because of a memory leak. It is because 3 objects are created at runtime but only one object is deleted explicitly and that’s why the remaining two objects are crashing at runtime." }, { "code": null, "e": 27684, "s": 27437, "text": "Conclusion:In C++, the single object of the class which is created at runtime using a new operator is deleted by using the delete operator, while the array of objects is deleted using the delete[] operator so that it cannot lead to a memory leak." }, { "code": null, "e": 27693, "s": 27684, "text": "C Basics" }, { "code": null, "e": 27704, "s": 27693, "text": "CPP-Basics" }, { "code": null, "e": 27719, "s": 27704, "text": "new and delete" }, { "code": null, "e": 27723, "s": 27719, "text": "C++" }, { "code": null, "e": 27736, "s": 27723, "text": "C++ Programs" }, { "code": null, "e": 27740, "s": 27736, "text": "CPP" }, { "code": null, "e": 27838, "s": 27740, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27847, "s": 27838, "text": "Comments" }, { "code": null, "e": 27860, "s": 27847, "text": "Old Comments" }, { "code": null, "e": 27888, "s": 27860, "text": "Operator Overloading in C++" }, { "code": null, "e": 27908, "s": 27888, "text": "Polymorphism in C++" }, { "code": null, "e": 27941, "s": 27908, "text": "Friend class and function in C++" }, { "code": null, "e": 27965, "s": 27941, "text": "Sorting a vector in C++" }, { "code": null, "e": 27986, "s": 27965, "text": "Iterators in C++ STL" }, { "code": null, "e": 28021, "s": 27986, "text": "Header files in C/C++ and its uses" }, { "code": null, "e": 28047, "s": 28021, "text": "C++ Program for QuickSort" }, { "code": null, "e": 28106, "s": 28047, "text": "How to return multiple values from a function in C or C++?" }, { "code": null, "e": 28150, "s": 28106, "text": "Program to print ASCII Value of a character" } ]
Beans and Dependency Injection
In Spring Boot, we can use Spring Framework to define our beans and their dependency injection. The @ComponentScan annotation is used to find beans and the corresponding injected with @Autowired annotation. If you followed the Spring Boot typical layout, no need to specify any arguments for @ComponentScan annotation. All component class files are automatically registered with Spring Beans. The following example provides an idea about Auto wiring the Rest Template object and creating a Bean for the same − @Bean public RestTemplate getRestTemplate() { return new RestTemplate(); } The following code shows the code for auto wired Rest Template object and Bean creation object in main Spring Boot Application class file − package com.tutorialspoint.demo; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.annotation.Bean; import org.springframework.web.client.RestTemplate; @SpringBootApplication public class DemoApplication { @Autowired RestTemplate restTemplate; public static void main(String[] args) { SpringApplication.run(DemoApplication.class, args); } @Bean public RestTemplate getRestTemplate() { return new RestTemplate(); } } 102 Lectures 8 hours Karthikeya T 39 Lectures 5 hours Chaand Sheikh 73 Lectures 5.5 hours Senol Atac 62 Lectures 4.5 hours Senol Atac 67 Lectures 4.5 hours Senol Atac 69 Lectures 5 hours Senol Atac Print Add Notes Bookmark this page
[ { "code": null, "e": 3232, "s": 3025, "text": "In Spring Boot, we can use Spring Framework to define our beans and their dependency injection. The @ComponentScan annotation is used to find beans and the corresponding injected with @Autowired annotation." }, { "code": null, "e": 3418, "s": 3232, "text": "If you followed the Spring Boot typical layout, no need to specify any arguments for @ComponentScan annotation. All component class files are automatically registered with Spring Beans." }, { "code": null, "e": 3535, "s": 3418, "text": "The following example provides an idea about Auto wiring the Rest Template object and creating a Bean for the same −" }, { "code": null, "e": 3613, "s": 3535, "text": "@Bean\npublic RestTemplate getRestTemplate() {\n return new RestTemplate();\n}" }, { "code": null, "e": 3753, "s": 3613, "text": "The following code shows the code for auto wired Rest Template object and Bean creation object in main Spring Boot Application class file −" }, { "code": null, "e": 4376, "s": 3753, "text": "package com.tutorialspoint.demo;\n\nimport org.springframework.beans.factory.annotation.Autowired;\nimport org.springframework.boot.SpringApplication;\nimport org.springframework.boot.autoconfigure.SpringBootApplication;\nimport org.springframework.context.annotation.Bean;\nimport org.springframework.web.client.RestTemplate;\n\n@SpringBootApplication\npublic class DemoApplication {\n@Autowired\n RestTemplate restTemplate;\n \n public static void main(String[] args) {\n SpringApplication.run(DemoApplication.class, args);\n }\n @Bean\n public RestTemplate getRestTemplate() {\n return new RestTemplate(); \n }\n}" }, { "code": null, "e": 4410, "s": 4376, "text": "\n 102 Lectures \n 8 hours \n" }, { "code": null, "e": 4424, "s": 4410, "text": " Karthikeya T" }, { "code": null, "e": 4457, "s": 4424, "text": "\n 39 Lectures \n 5 hours \n" }, { "code": null, "e": 4472, "s": 4457, "text": " Chaand Sheikh" }, { "code": null, "e": 4507, "s": 4472, "text": "\n 73 Lectures \n 5.5 hours \n" }, { "code": null, "e": 4519, "s": 4507, "text": " Senol Atac" }, { "code": null, "e": 4554, "s": 4519, "text": "\n 62 Lectures \n 4.5 hours \n" }, { "code": null, "e": 4566, "s": 4554, "text": " Senol Atac" }, { "code": null, "e": 4601, "s": 4566, "text": "\n 67 Lectures \n 4.5 hours \n" }, { "code": null, "e": 4613, "s": 4601, "text": " Senol Atac" }, { "code": null, "e": 4646, "s": 4613, "text": "\n 69 Lectures \n 5 hours \n" }, { "code": null, "e": 4658, "s": 4646, "text": " Senol Atac" }, { "code": null, "e": 4665, "s": 4658, "text": " Print" }, { "code": null, "e": 4676, "s": 4665, "text": " Add Notes" } ]
How to create a dotted vertical line using ggplot2 in R?
To create a vertical line using ggplot2, we can use geom_vline function of ggplot2 package and if we want to have a dotted vertical line then linetype will be set to 3 inside the same function. To draw the line, we will have to provide xintercept because the line will start on X-axis. Check out the below example to understand how it works. Following snippet creates a sample data frame − x<-rpois(20,5) y<-rpois(20,2) df<-data.frame(x,y) df The following dataframe is created − x y 1 5 2 2 3 4 3 6 2 4 3 4 5 4 2 6 5 2 7 7 1 8 4 2 9 3 2 10 4 4 11 6 2 12 2 2 13 7 1 14 7 1 15 6 1 16 7 1 17 7 2 18 7 1 19 6 3 20 4 3 To load ggplot2 package and create point chart between x and y with vertical line at X=5, add the following code to the above snippet − library(ggplot2) ggplot(df,aes(x,y))+geom_point()+geom_vline(xintercept=5) If you execute all the above given snippets as a single program, it generates the following output − Now, to create point chart between x and y with dotted vertical line at X=5, add the following code to the above snippet − ggplot(df,aes(x,y))+geom_point()+geom_vline(xintercept=5,linetype=3) If you execute all the above given snippets as a single program, it generates the following output −
[ { "code": null, "e": 1348, "s": 1062, "text": "To create a vertical line using ggplot2, we can use geom_vline function of ggplot2 package and if we want to have a dotted vertical line then linetype will be set to 3 inside the same function. To draw the line, we will have to provide xintercept because the line will start on X-axis." }, { "code": null, "e": 1404, "s": 1348, "text": "Check out the below example to understand how it works." }, { "code": null, "e": 1452, "s": 1404, "text": "Following snippet creates a sample data frame −" }, { "code": null, "e": 1505, "s": 1452, "text": "x<-rpois(20,5)\ny<-rpois(20,2)\ndf<-data.frame(x,y)\ndf" }, { "code": null, "e": 1542, "s": 1505, "text": "The following dataframe is created −" }, { "code": null, "e": 1710, "s": 1542, "text": " x y\n1 5 2\n2 3 4\n3 6 2\n4 3 4\n5 4 2\n6 5 2\n7 7 1\n8 4 2\n9 3 2\n10 4 4\n11 6 2\n12 2 2\n13 7 1\n14 7 1\n15 6 1\n16 7 1\n17 7 2\n18 7 1\n19 6 3\n20 4 3" }, { "code": null, "e": 1846, "s": 1710, "text": "To load ggplot2 package and create point chart between x and y with vertical line at X=5, add the following code to the above snippet −" }, { "code": null, "e": 1921, "s": 1846, "text": "library(ggplot2)\nggplot(df,aes(x,y))+geom_point()+geom_vline(xintercept=5)" }, { "code": null, "e": 2022, "s": 1921, "text": "If you execute all the above given snippets as a single program, it generates the following output −" }, { "code": null, "e": 2145, "s": 2022, "text": "Now, to create point chart between x and y with dotted vertical line at X=5, add the following code to the above snippet −" }, { "code": null, "e": 2215, "s": 2145, "text": "ggplot(df,aes(x,y))+geom_point()+geom_vline(xintercept=5,linetype=3)\n" }, { "code": null, "e": 2316, "s": 2215, "text": "If you execute all the above given snippets as a single program, it generates the following output −" } ]
How do you declare an interface in C++?
An interface describes the behavior or capabilities of a C++ class without committing to a particular implementation of that class. The C++ interfaces are implemented using abstract classes and these abstract classes should not be confused with data abstraction which is a concept of keeping implementation details separate from associated data. A class is made abstract by declaring at least one of its functions as a pure virtual function. A pure virtual function is specified by placing "= 0" in its declaration as follows − class Box { public: // pure virtual function virtual double getVolume() = 0; private: double length; // Length of a box double breadth; // Breadth of a box double height; // Height of a box }; The purpose of an abstract class (often referred to as an ABC) is to provide an appropriate base class from which other classes can inherit. Abstract classes cannot be used to instantiate objects and serve only as an interface. Attempting to instantiate an object of an abstract class causes a compilation error. Thus, if a subclass of an ABC needs to be instantiated, it has to implement each of the virtual functions, which means that it supports the interface declared by the ABC. Failure to override a pure virtual function in a derived class, then attempting to instantiate objects of that class, is a compilation error. Classes that can be used to instantiate objects are called concrete classes. Consider the following example where parent class provides an interface to the base class to implement a function called getArea() − Live Demo #include <iostream> using namespace std; class Shape { // Base class public: // pure virtual function providing interface framework. virtual int getArea() = 0; void setWidth(int w) { width = w; } void setHeight(int h) { height = h; } protected: int width; int height; }; class Rectangle: public Shape { // Derived classes public: int getArea() { return (width * height); } }; class Triangle: public Shape { public: int getArea() { return (width * height)/2; } }; int main(void) { Rectangle Rect; Triangle Tri; Rect.setWidth(5); Rect.setHeight(7); // Print the area of the object. cout << "Total Rectangle area: " << Rect.getArea() << endl; Tri.setWidth(5); Tri.setHeight(7); // Print the area of the object. cout << "Total Triangle area: " << Tri.getArea() << endl; return 0; } Total Rectangle area: 35 Total Triangle area: 17 You can see how an abstract class defined an interface in terms of getArea() and two other classes implemented the same function but with a different algorithm to calculate the area specific to the shape. An object-oriented system might use an abstract base class to provide a common and standardized interface appropriate for all the external applications. Then, through inheritance from that abstract base class, derived classes are formed that operate similarly. The capabilities (i.e., the public functions) offered by the external applications are provided as pure virtual functions in the abstract base class. The implementations of these pure virtual functions are provided in the derived classes that correspond to the specific types of the application. This architecture also allows new applications to be added to a system easily, even after the system has been defined.
[ { "code": null, "e": 1194, "s": 1062, "text": "An interface describes the behavior or capabilities of a C++ class without committing to a particular implementation of that class." }, { "code": null, "e": 1408, "s": 1194, "text": "The C++ interfaces are implemented using abstract classes and these abstract classes should not be confused with data abstraction which is a concept of keeping implementation details separate from associated data." }, { "code": null, "e": 1590, "s": 1408, "text": "A class is made abstract by declaring at least one of its functions as a pure virtual function. A pure virtual function is specified by placing \"= 0\" in its declaration as follows −" }, { "code": null, "e": 1820, "s": 1590, "text": "class Box {\n public:\n // pure virtual function\n virtual double getVolume() = 0;\n\n private:\n double length; // Length of a box\n double breadth; // Breadth of a box\n double height; // Height of a box\n};" }, { "code": null, "e": 2133, "s": 1820, "text": "The purpose of an abstract class (often referred to as an ABC) is to provide an appropriate base class from which other classes can inherit. Abstract classes cannot be used to instantiate objects and serve only as an interface. Attempting to instantiate an object of an abstract class causes a compilation error." }, { "code": null, "e": 2446, "s": 2133, "text": "Thus, if a subclass of an ABC needs to be instantiated, it has to implement each of the virtual functions, which means that it supports the interface declared by the ABC. Failure to override a pure virtual function in a derived class, then attempting to instantiate objects of that class, is a compilation error." }, { "code": null, "e": 2523, "s": 2446, "text": "Classes that can be used to instantiate objects are called concrete classes." }, { "code": null, "e": 2656, "s": 2523, "text": "Consider the following example where parent class provides an interface to the base class to implement a function called getArea() −" }, { "code": null, "e": 2667, "s": 2656, "text": " Live Demo" }, { "code": null, "e": 3607, "s": 2667, "text": "#include <iostream>\nusing namespace std;\nclass Shape { // Base class\n public:\n // pure virtual function providing interface framework.\n virtual int getArea() = 0;\n void setWidth(int w) {\n width = w;\n }\n\n void setHeight(int h) {\n height = h;\n }\n\n protected:\n int width;\n int height;\n};\n\nclass Rectangle: public Shape { // Derived classes\n public:\n int getArea() {\n return (width * height);\n }\n};\n\nclass Triangle: public Shape {\n public:\n int getArea() {\n return (width * height)/2;\n }\n};\n\nint main(void) {\n Rectangle Rect;\n Triangle Tri;\n\n Rect.setWidth(5);\n Rect.setHeight(7);\n\n // Print the area of the object.\n cout << \"Total Rectangle area: \" << Rect.getArea() << endl;\n\n Tri.setWidth(5);\n Tri.setHeight(7);\n\n // Print the area of the object.\n cout << \"Total Triangle area: \" << Tri.getArea() << endl;\n return 0;\n}" }, { "code": null, "e": 3656, "s": 3607, "text": "Total Rectangle area: 35\nTotal Triangle area: 17" }, { "code": null, "e": 3861, "s": 3656, "text": "You can see how an abstract class defined an interface in terms of getArea() and two other classes implemented the same function but with a different algorithm to calculate the area specific to the shape." }, { "code": null, "e": 4122, "s": 3861, "text": "An object-oriented system might use an abstract base class to provide a common and standardized interface appropriate for all the external applications. Then, through inheritance from that abstract base class, derived classes are formed that operate similarly." }, { "code": null, "e": 4418, "s": 4122, "text": "The capabilities (i.e., the public functions) offered by the external applications are provided as pure virtual functions in the abstract base class. The implementations of these pure virtual functions are provided in the derived classes that correspond to the specific types of the application." }, { "code": null, "e": 4537, "s": 4418, "text": "This architecture also allows new applications to be added to a system easily, even after the system has been defined." } ]
RTOS Introduction with Arduino
RTOS stands for Real Time Operating System. It is used to run multiple tasks concurrently, schedule them as required, and enable them to share resources. Now, while getting into the details of RTOS is out of the scope of this article, we will walk through an example that will give you a fair idea of RTOS. For now, you can just note that RTOS will help you perform multi-tasking within your Arduino, just like how the OS on your machine helps you run multiple tasks (like writing mails, listening to music, etc.) simultaneously. Now, since we are concerned with microcontrollers, we will use FreeRTOS, which is RTOS for embedded devices. Basically, it is designed to be small enough to support microcontrollers. You can read more about FreeRTOS here: https://en.wikipedia.org/wiki/FreeRTOS Now, to get started with FreeRTOS on Arduino, we will first need an external library. Go to Tools -> Manage Libraries and search for FreeRTOS. You will see the library by Richard Barry. As mentioned, it works for Uno, Nano, Leonardo and Mega boards. We are using the Uno board, so we will install this library. Now, once the library is installed, you will be able to see all the example codes related to this library in File -> Examples. You are encouraged to go through all the examples to further understand FreeRTOS. We will walk through one of the examples: Blink_AnalogRead. As you can see, we first include the library #include <Arduino_FreeRTOS.h> Later, we declare two tasks, Blink task and AnalogRead task. void TaskBlink( void *pvParameters ); void TaskAnalogRead( void *pvParameters ); Note that this takes in pvParameters pointer as an input. We will come back to this later. Next comes the important setup part. // the setup function runs once when you press reset or power the board void setup() { // initialize serial communication at 9600 bits per second: Serial.begin(9600); while (!Serial) { ; // wait for serial port to connect. Needed for native USB, on LEONARDO, MICRO, YUN, and other 32u4 based boards. } // Now set up two tasks to run independently. xTaskCreate( TaskBlink , "Blink" // A name just for humans , 128 // This stack size can be checked & adjusted by reading the Stack Highwater , NULL , 2 // Priority, with 3 (configMAX_PRIORITIES - 1) being the highest, and 0 being the lowest. , NULL ); xTaskCreate( TaskAnalogRead , "AnalogRead" , 128 // Stack size , NULL , 1 // Priority , NULL ); // Now the task scheduler, which takes over control of scheduling individual tasks, is automatically started. } Pay attention to all the comments in this part. We first initialize serial and then wait for it to get initialized. Then, we create the task using xTaskCreate. Now, xTaskCreate has the following syntax − BaseType_t xTaskCreate(TaskFunction_t pvTaskCode,const char * const pcName,configSTACK_DEPTH_TYPE usStackDepth,void *pvParameters, UBaseType_t uxPriority,TaskHandle_t *pxCreatedTask); pvTaskCode is the name of the function that executes the task (TaskBlink and TaskAnalogRead). pcName is the name of the task (as mentioned in the comments, just for human reference) usStackDepth is the number of words that are allocated to the task’s stack. Please refer to the datasheet of your board to determine how many bytes is equal to one word pvParameters are the parameters to be passed to the created task. You remember the pvParameters arguments at the time of declaring the tasks? These are where they come from. Say you want to pass in the number 1 to the task. You can do it by passing (void *) 1 to pvParameters argument of xTaskCreate uxPriority defines the priority of the task. Higher the number, more is the priority pxCreatedTask is the task handle. This is optional and you can pass in NULL. Its purpose is to reference the task in other parts of the code. Once our tasks have been created, as mentioned in the comments, the task scheduler automatically gets started. Next, our loop is empty, since we are executing our code in tasks. Finally, the functions for the two tasks are defined. void TaskBlink(void *pvParameters) // This is a task. { (void) pvParameters; /* Blink Turns on an LED on for one second, then off for one second, repeatedly. Most Arduinos have an on-board LED you can control. On the UNO, LEONARDO, MEGA, and ZERO, it is attached to digital pin 13, on MKR1000 on pin 6. LED_BUILTIN takes care of use the correct LED pin whatever is the board used. The MICRO does not have a LED_BUILTIN available. For the MICRO board please substitute the LED_BUILTIN definition with either LED_BUILTIN_RX or LED_BUILTIN_TX. e.g. pinMode(LED_BUILTIN_RX, OUTPUT); etc. If you want to know what pin the on-board LED is connected to on your Arduino model, check the Technical Specs of your board at https://www.arduino.cc/en/Main/Products This example code is in the public domain. modified 8 May 2014 by Scott Fitzgerald modified 2 Sep 2016 by Arturo Guadalupi */ // initialize digital LED_BUILTIN on pin 13 as an output. pinMode(LED_BUILTIN, OUTPUT); for (;;) // A Task shall never return or exit. { digitalWrite(LED_BUILTIN, HIGH); // turn the LED on (HIGH is the voltage level) vTaskDelay( 1000 / portTICK_PERIOD_MS ); // wait for one second digitalWrite(LED_BUILTIN, LOW); // turn the LED off by making the voltage LOW vTaskDelay( 1000 / portTICK_PERIOD_MS ); // wait for one second } } void TaskAnalogRead(void *pvParameters) // This is a task. { (void) pvParameters; /* AnalogReadSerial Reads an analog input on pin 0, prints the result to the serial monitor. Graphical representation is available using serial plotter (Tools > Serial Plotter menu) Attach the center pin of a potentiometer to pin A0, and the outside pins to +5V and ground. This example code is in the public domain. */ for (;;) { // read the input on analog pin 0: int sensorValue = analogRead(A0); // print out the value you read: Serial.println(sensorValue); vTaskDelay(1); // one tick delay (15ms) in between reads for stability } The comments within the tasks explain the code very well. Please note that within tasks, instead of delay(), we use vTaskDelay() within tasks. vTaskDelay(1) introduces a delay of 1 tick. Now, 1 tick may or may not correspond to 1ms. As mentioned in the comments of the AnalogRead task, 1 tick corresponds to 15ms. It depends on the clock frequency of the board. In order to get the delay time in ms, we can divide the time in ms with the portTICK_PERIOD_MS constant. As done in the TaskBlink, the delay of 1 second is realized with the following command: vTaskDelay( 1000 / portTICK_PERIOD_MS ); You can read more about freeRTOS here: https://www.freertos.org/
[ { "code": null, "e": 1592, "s": 1062, "text": "RTOS stands for Real Time Operating System. It is used to run multiple tasks concurrently, schedule them as required, and enable them to share resources. Now, while getting into the details of RTOS is out of the scope of this article, we will walk through an example that will give you a fair idea of RTOS. For now, you can just note that RTOS will help you perform multi-tasking within your Arduino, just like how the OS on your machine helps you run multiple tasks (like writing mails, listening to music, etc.) simultaneously." }, { "code": null, "e": 1853, "s": 1592, "text": "Now, since we are concerned with microcontrollers, we will use FreeRTOS, which is RTOS for embedded devices. Basically, it is designed to be small enough to support microcontrollers. You can read more about FreeRTOS here: https://en.wikipedia.org/wiki/FreeRTOS" }, { "code": null, "e": 1996, "s": 1853, "text": "Now, to get started with FreeRTOS on Arduino, we will first need an external library. Go to Tools -> Manage Libraries and search for FreeRTOS." }, { "code": null, "e": 2167, "s": 1996, "text": "You will see the library by Richard Barry. As mentioned, it works for Uno, Nano, Leonardo and Mega boards. We are using the Uno board, so we will install this library. " }, { "code": null, "e": 2294, "s": 2167, "text": "Now, once the library is installed, you will be able to see all the example codes related to this library in File -> Examples." }, { "code": null, "e": 2436, "s": 2294, "text": "You are encouraged to go through all the examples to further understand FreeRTOS. We will walk through one of the examples: Blink_AnalogRead." }, { "code": null, "e": 2481, "s": 2436, "text": "As you can see, we first include the library" }, { "code": null, "e": 2511, "s": 2481, "text": "#include <Arduino_FreeRTOS.h>" }, { "code": null, "e": 2572, "s": 2511, "text": "Later, we declare two tasks, Blink task and AnalogRead task." }, { "code": null, "e": 2653, "s": 2572, "text": "void TaskBlink( void *pvParameters );\nvoid TaskAnalogRead( void *pvParameters );" }, { "code": null, "e": 2744, "s": 2653, "text": "Note that this takes in pvParameters pointer as an input. We will come back to this later." }, { "code": null, "e": 2781, "s": 2744, "text": "Next comes the important setup part." }, { "code": null, "e": 3729, "s": 2781, "text": "// the setup function runs once when you press reset or power the board\nvoid setup() { \n // initialize serial communication at 9600 bits per second:\n Serial.begin(9600); \n while (!Serial) {\n ; // wait for serial port to connect. Needed for native USB, on LEONARDO, MICRO, YUN, and other 32u4 based boards.\n }\n // Now set up two tasks to run independently.\n xTaskCreate(\n TaskBlink\n , \"Blink\" // A name just for humans\n , 128 // This stack size can be checked & adjusted by reading the Stack Highwater\n , NULL\n , 2 // Priority, with 3 (configMAX_PRIORITIES - 1) being the highest, and 0 being the lowest.\n , NULL );\n xTaskCreate(\n TaskAnalogRead\n , \"AnalogRead\"\n , 128 // Stack size\n , NULL\n , 1 // Priority\n , NULL\n );\n // Now the task scheduler, which takes over control of scheduling individual tasks, is automatically started.\n}" }, { "code": null, "e": 3777, "s": 3729, "text": "Pay attention to all the comments in this part." }, { "code": null, "e": 3845, "s": 3777, "text": "We first initialize serial and then wait for it to get initialized." }, { "code": null, "e": 3933, "s": 3845, "text": "Then, we create the task using xTaskCreate. Now, xTaskCreate has the following syntax −" }, { "code": null, "e": 4117, "s": 3933, "text": "BaseType_t xTaskCreate(TaskFunction_t pvTaskCode,const char * const pcName,configSTACK_DEPTH_TYPE usStackDepth,void *pvParameters, UBaseType_t uxPriority,TaskHandle_t *pxCreatedTask);" }, { "code": null, "e": 4211, "s": 4117, "text": "pvTaskCode is the name of the function that executes the task (TaskBlink and TaskAnalogRead)." }, { "code": null, "e": 4299, "s": 4211, "text": "pcName is the name of the task (as mentioned in the comments, just for human reference)" }, { "code": null, "e": 4468, "s": 4299, "text": "usStackDepth is the number of words that are allocated to the task’s stack. Please refer to the datasheet of your board to determine how many bytes is equal to one word" }, { "code": null, "e": 4768, "s": 4468, "text": "pvParameters are the parameters to be passed to the created task. You remember the pvParameters arguments at the time of declaring the tasks? These are where they come from. Say you want to pass in the number 1 to the task. You can do it by passing (void *) 1 to pvParameters argument of xTaskCreate" }, { "code": null, "e": 4853, "s": 4768, "text": "uxPriority defines the priority of the task. Higher the number, more is the priority" }, { "code": null, "e": 4995, "s": 4853, "text": "pxCreatedTask is the task handle. This is optional and you can pass in NULL. Its purpose is to reference the task in other parts of the code." }, { "code": null, "e": 5173, "s": 4995, "text": "Once our tasks have been created, as mentioned in the comments, the task scheduler automatically gets started. Next, our loop is empty, since we are executing our code in tasks." }, { "code": null, "e": 5227, "s": 5173, "text": "Finally, the functions for the two tasks are defined." }, { "code": null, "e": 7305, "s": 5227, "text": "void TaskBlink(void *pvParameters) // This is a task.\n{\n (void) pvParameters;\n\n/*\n Blink\n Turns on an LED on for one second, then off for one second, repeatedly.\n Most Arduinos have an on-board LED you can control. On the UNO, LEONARDO, MEGA, and ZERO, it is attached to digital pin 13, on MKR1000 on pin 6. LED_BUILTIN takes care of use the correct LED pin whatever is the board used.\n The MICRO does not have a LED_BUILTIN available. For the MICRO board please substitute the LED_BUILTIN definition with either LED_BUILTIN_RX or LED_BUILTIN_TX. e.g. pinMode(LED_BUILTIN_RX, OUTPUT); etc.\n If you want to know what pin the on-board LED is connected to on your Arduino model, check the Technical Specs of your board at https://www.arduino.cc/en/Main/Products\n \n This example code is in the public domain.\n modified 8 May 2014\n by Scott Fitzgerald\n modified 2 Sep 2016\n by Arturo Guadalupi\n*/\n\n // initialize digital LED_BUILTIN on pin 13 as an output.\n pinMode(LED_BUILTIN, OUTPUT);\n\n for (;;) // A Task shall never return or exit.\n {\n digitalWrite(LED_BUILTIN, HIGH); // turn the LED on (HIGH is the voltage level)\n vTaskDelay( 1000 / portTICK_PERIOD_MS ); // wait for one second\n digitalWrite(LED_BUILTIN, LOW); // turn the LED off by making the voltage LOW\n vTaskDelay( 1000 / portTICK_PERIOD_MS ); // wait for one second\n }\n}\n\nvoid TaskAnalogRead(void *pvParameters) // This is a task.\n{\n (void) pvParameters;\n \n/*\n AnalogReadSerial\n Reads an analog input on pin 0, prints the result to the serial monitor.\n Graphical representation is available using serial plotter (Tools > Serial Plotter menu)\n Attach the center pin of a potentiometer to pin A0, and the outside pins to +5V and ground.\n This example code is in the public domain.\n*/\n\n for (;;)\n {\n // read the input on analog pin 0:\n int sensorValue = analogRead(A0);\n // print out the value you read:\n Serial.println(sensorValue);\n vTaskDelay(1); // one tick delay (15ms) in between reads for stability\n }" }, { "code": null, "e": 7902, "s": 7305, "text": "The comments within the tasks explain the code very well. Please note that within tasks, instead of delay(), we use vTaskDelay() within tasks. vTaskDelay(1) introduces a delay of 1 tick. Now, 1 tick may or may not correspond to 1ms. As mentioned in the comments of the AnalogRead task, 1 tick corresponds to 15ms. It depends on the clock frequency of the board. In order to get the delay time in ms, we can divide the time in ms with the portTICK_PERIOD_MS constant. As done in the TaskBlink, the delay of 1 second is realized with the following command: vTaskDelay( 1000 / portTICK_PERIOD_MS ); " }, { "code": null, "e": 7967, "s": 7902, "text": "You can read more about freeRTOS here: https://www.freertos.org/" } ]
Statistical Significance Explained | by Will Koehrsen | Towards Data Science
What does it mean to prove something with data? As the dean at a major university, you receive a concerning report showing your students get an average of 6.80 hours of sleep per night compared to the national college average of 7.02 hours. The student body president is worried about the health of students and points to this study as proof that homework must be reduced. The university president on the other hand dismisses the study as nonsense: “Back in my day we got four hours of sleep a night and considered ourselves lucky.” You have to decide if this is a serious issue. Fortunately, you’re well-versed in statistics and finally see a chance to put your education to use! Statistical significance is one of those terms we often hear without really understanding. When someone claims data proves their point, we nod and accept it, assuming statisticians have done complex operations that yielded a result which cannot be questioned. In fact, statistical significance is not a complicated phenomenon requiring years of study to master, but a straightforward idea that everyone can — and should — understand. Like with most technical concepts, statistical significance is built on a few simple ideas: hypothesis testing, the normal distribution, and p values. In this article, we will briefly touch on all of these concepts (with further resources provided) as we work up to solving the conundrum presented above. Author’s Note: An earlier edition of this post oversimplified the definition of the p-value. I would like to thank Professor Timothy Bates for correcting my mistake. This was a great example of the type of collaborative learning possible online and I encourage any feedback, corrections, or discussion! The first idea we have to discuss is hypothesis testing, a technique for evaluating a theory using data. The “hypothesis” refers to the researcher’s initial belief about the situation before the study. This initial theory is known as the alternative hypothesis and the opposite is known as the null hypothesis. In our example these are: Alternative Hypothesis: The average amount of sleep by students at our university is below the national average for college student. Null Hypothesis: The average amount of sleep by students at our university is not below the national average for college students. Notice how careful we have to be about the wording: we are looking for a very specific effect, which needs to be formalized in the hypotheses so after the fact we cannot claim to have been testing something else! (This is an example of a one-sided hypothesis test because we are concerned with a change in only one direction.) Hypothesis tests are one of the foundations of statistics and are used to assess the results of most studies. These studies can be anything from a medical trial to assess drug effectiveness to an observational study evaluating an exercise plan. What all studies have in common is that they are concerned with making comparisons, either between two groups or between one group and the entire population. In the medical example, we might compare the average time to recover between groups taking two different drugs, or, in our problem as dean, we want to compare sleep between our students and all the students in the country. The testing part of hypothesis tests allows us to determine which theory, the null or alternative, is better supported by the evidence. There are many hypothesis tests and we will use one called the z-test. However, before we can get to testing our data, we need to talk about two more crucial ideas. The second building block of statistical significance is the normal distribution, also called the Gaussian or bell curve. The normal distribution is used to represent how data from a process is distributed and is defined by the mean, given the Greek letter μ (mu), and the standard deviation, given the letter σ (sigma). The mean shows the location of the center of the data and the standard deviation is the spread in the data. The application of the normal distribution comes from assessing data points in terms of the standard deviation. We can determine how anomalous a data point is based on how many standard deviations it is from the mean. The normal distribution has the following helpful properties: 68% of data is within ± 1 standard deviations from the mean 95% of data is within ± 2 standard deviations from the mean 99.7% of data is within ± 3 standard deviations from the mean If we have a normal distribution for a statistic, we can characterize any point in terms of standard deviations from the mean. For example, average female height in the US is 65 inches (5' 5") with a standard deviation of 4 inches. If we meet a new acquaintance who is 73 inches tall, we can say she is two standard deviations above the mean and is in the tallest 2.5% of females. (2.5% of females will be shorter than μ — 2σ (57 in) and 2.5% will be taller than μ+2σ). In statistics, instead of saying our data is two standard deviations from the mean, we assess it in terms of a z-score, which just represents the number of standard deviations a point is from the mean. Conversion to a z-score is done by subtracting the mean of the distribution from the data point and dividing by the standard deviation. In the height example, you can check that our friend would have a z-score of 2. If we do this to all the data points the new distribution is called the standard normal with a mean of 0 and a standard deviation of 1 as shown below. Every time we do a hypothesis test, we need to assume a distribution for the test statistic, which in our case is the average (mean) hours of sleep for our students. For a z-test, the normal curve is used as an approximation for the distribution of the test statistic. Generally, according to the central limit theorem, as we take more averages from a data distribution, the averages will tend towards a normal distribution. However, this will always be an estimate because real-world data never perfectly follows a normal distribution. Assuming a normal distribution lets us determine how meaningful the result we observe in a study is. The higher or lower the z-score, the more unlikely the result is to happen by chance and the more likely the result is meaningful. To quantify just how meaningful the results are, we use one more concept. The final core idea is that of p-values. A p-value is the probability of observing results at least as extreme as those measured when the null hypothesis is true. That might seem a little convoluted, so let’s look at an example. Say we are measuring average IQ in the US states of Florida and Washington. Our null hypothesis is that average IQs in Washington are not higher than average IQs in Florida. We perform the study and find IQs in Washington are higher by 2.2 points with a p-value of 0.346. This means, in a world where the null hypothesis — average IQs in Washington are not higher than average IQs in Florida — is true, there is a 34.6% chance we would measure IQs at least 2.2 points higher in Washington. So, if IQs in Washington are not actually higher, we would still measure they are higher by at least 2.2 points about 1/3 of the time due to random noise. Subsequently, the lower the p-value, the more meaningful the result because it is less likely to be caused by noise. Whether or not the result can be called statistically significant depends on the p-value (known as alpha) we establish for significance before we begin the experiment . If the observed p-value is less than alpha, then the results are statistically significant. We need to choose alpha before the experiment because if we waited until after, we could just select a number that proves our results are significant no matter what the data shows! The choice of alpha depends on the situation and the field of study, but the most commonly used value is 0.05, corresponding to a 5% chance the results occurred at random. In my lab, I see values from 0.1 to 0.001 commonly in use. As an extreme example, the physicists who discovered the Higgs Boson particle used a p-value of 0.0000003, or a 1 in 3.5 million chance the discovery occurred because of noise. (Statisticians are loathe to admit that a p-value of 0.05 is arbitrary. R.A. Fischer, the father of modern statistics, choose a p-value of 0.05 for indeterminate reasons and it stuck)! To get from a z-score on the normal distribution to a p-value, we can use a table or statistical software like R. The result will show us the probability of a z-score lower than the calculated value. For example, with a z-score of 2, the p-value is 0.977, which means there is only a 2.3% probability we observe a z-score higher than 2 at random. As a summary so far, we have covered three ideas: Hypothesis Testing: A technique used to test a theoryNormal Distribution: An approximate representation of the data in a hypothesis test.p-value: The probability a result at least as extreme at that observed would have occurred if the null hypothesis is true. Hypothesis Testing: A technique used to test a theory Normal Distribution: An approximate representation of the data in a hypothesis test. p-value: The probability a result at least as extreme at that observed would have occurred if the null hypothesis is true. Now, let’s put the pieces together in our example. Here are the basics: Students across the country average 7.02 hours of sleep per night according to the National Sleep Foundation In a poll of 202 students at our university the average hours of sleep per night was 6.90 hours with a standard deviation of 0.84 hours. Our alternative hypothesis is the average sleep of students at our university is below the national average for college students. We will use an alpha value of 0.05 which means the results are significant f the p-value is below 0.05. First, we need to convert our measurement into a z-score, or the number of standard deviations it is away from the mean. We do this by subtracting the population mean (the national average) from our measured value and dividing by the standard deviation over the square root of the number of samples. (As the number of samples increases, the standard deviation and hence the variation decreases. We account for this by dividing the standard deviation by the square root of the number of samples.) The z-score is called our test-statistic. Once we have a test-statistic, we can use a table or a programming language such as R to calculate the p-value. I use code here not to intimidate but to show how easy it is to implement our solution with free tools! (# are comments and bold is output) # Calculate the resultsz_score = (6.90 - 7.02) / (0.84 / sqrt(202)) p_value = pnorm(z_score)# Print our resultssprintf('The p-value is %0:5f for a z-score of %0.5f.', p_value, z_score)"The p-value is 0.02116 for a z-score of -2.03038." Based on the p-value of 0.02116, we can reject the null hypothesis. (Statisticians like us to say reject the null rather than accept the alternative.) There is statistically significant evidence our students get less sleep on average than college students in the US at a significance level of 0.05. The p-value shows there is a 2.12% chance that our results occurred because of random noise. In this battle of the presidents, the student was right. Before we ban all homework, we need to be careful not to assign too much to this result. Notice that our p-value, 0.02116, would not be significant if we had used a threshold of 0.01. Someone who wants to prove the opposite point in our study can simply manipulate the p-value. Anytime we examine a study, we should think about the p-value and the sample size in addition to the conclusion. With a relatively small sample size of 202, our study might have statistical significance, but that does mean it is practically meaningful. Further, this was an observational study, which means there is only evidence for correlation and not causation. We showed there is a correlation between students at our school and less average sleep, but not that going to our school causes a decrease in sleep. There could be other factors at play that affect sleep and only a randomized controlled study is able to prove causation. As with most technical concepts, statistical significance is not that complex and is just a combination of many small ideas. Most of the trouble comes with learning the vocabulary! Once you put the pieces together, you can start applying these statistical concepts. As you learn the basics of stats, you become better prepared to view studies and the news with a healthy skepticism. You can see what the data actually says rather than what someone tells you it means. The best tactic against dishonest politicians and corporations is a skeptical, well-educated public! As always, I welcome constructive criticism and feedback. I can be reached on Twitter @koehrsen_will.
[ { "code": null, "e": 219, "s": 171, "text": "What does it mean to prove something with data?" }, { "code": null, "e": 852, "s": 219, "text": "As the dean at a major university, you receive a concerning report showing your students get an average of 6.80 hours of sleep per night compared to the national college average of 7.02 hours. The student body president is worried about the health of students and points to this study as proof that homework must be reduced. The university president on the other hand dismisses the study as nonsense: “Back in my day we got four hours of sleep a night and considered ourselves lucky.” You have to decide if this is a serious issue. Fortunately, you’re well-versed in statistics and finally see a chance to put your education to use!" }, { "code": null, "e": 1591, "s": 852, "text": "Statistical significance is one of those terms we often hear without really understanding. When someone claims data proves their point, we nod and accept it, assuming statisticians have done complex operations that yielded a result which cannot be questioned. In fact, statistical significance is not a complicated phenomenon requiring years of study to master, but a straightforward idea that everyone can — and should — understand. Like with most technical concepts, statistical significance is built on a few simple ideas: hypothesis testing, the normal distribution, and p values. In this article, we will briefly touch on all of these concepts (with further resources provided) as we work up to solving the conundrum presented above." }, { "code": null, "e": 1894, "s": 1591, "text": "Author’s Note: An earlier edition of this post oversimplified the definition of the p-value. I would like to thank Professor Timothy Bates for correcting my mistake. This was a great example of the type of collaborative learning possible online and I encourage any feedback, corrections, or discussion!" }, { "code": null, "e": 2231, "s": 1894, "text": "The first idea we have to discuss is hypothesis testing, a technique for evaluating a theory using data. The “hypothesis” refers to the researcher’s initial belief about the situation before the study. This initial theory is known as the alternative hypothesis and the opposite is known as the null hypothesis. In our example these are:" }, { "code": null, "e": 2364, "s": 2231, "text": "Alternative Hypothesis: The average amount of sleep by students at our university is below the national average for college student." }, { "code": null, "e": 2495, "s": 2364, "text": "Null Hypothesis: The average amount of sleep by students at our university is not below the national average for college students." }, { "code": null, "e": 3448, "s": 2495, "text": "Notice how careful we have to be about the wording: we are looking for a very specific effect, which needs to be formalized in the hypotheses so after the fact we cannot claim to have been testing something else! (This is an example of a one-sided hypothesis test because we are concerned with a change in only one direction.) Hypothesis tests are one of the foundations of statistics and are used to assess the results of most studies. These studies can be anything from a medical trial to assess drug effectiveness to an observational study evaluating an exercise plan. What all studies have in common is that they are concerned with making comparisons, either between two groups or between one group and the entire population. In the medical example, we might compare the average time to recover between groups taking two different drugs, or, in our problem as dean, we want to compare sleep between our students and all the students in the country." }, { "code": null, "e": 3749, "s": 3448, "text": "The testing part of hypothesis tests allows us to determine which theory, the null or alternative, is better supported by the evidence. There are many hypothesis tests and we will use one called the z-test. However, before we can get to testing our data, we need to talk about two more crucial ideas." }, { "code": null, "e": 4178, "s": 3749, "text": "The second building block of statistical significance is the normal distribution, also called the Gaussian or bell curve. The normal distribution is used to represent how data from a process is distributed and is defined by the mean, given the Greek letter μ (mu), and the standard deviation, given the letter σ (sigma). The mean shows the location of the center of the data and the standard deviation is the spread in the data." }, { "code": null, "e": 4458, "s": 4178, "text": "The application of the normal distribution comes from assessing data points in terms of the standard deviation. We can determine how anomalous a data point is based on how many standard deviations it is from the mean. The normal distribution has the following helpful properties:" }, { "code": null, "e": 4518, "s": 4458, "text": "68% of data is within ± 1 standard deviations from the mean" }, { "code": null, "e": 4578, "s": 4518, "text": "95% of data is within ± 2 standard deviations from the mean" }, { "code": null, "e": 4640, "s": 4578, "text": "99.7% of data is within ± 3 standard deviations from the mean" }, { "code": null, "e": 5110, "s": 4640, "text": "If we have a normal distribution for a statistic, we can characterize any point in terms of standard deviations from the mean. For example, average female height in the US is 65 inches (5' 5\") with a standard deviation of 4 inches. If we meet a new acquaintance who is 73 inches tall, we can say she is two standard deviations above the mean and is in the tallest 2.5% of females. (2.5% of females will be shorter than μ — 2σ (57 in) and 2.5% will be taller than μ+2σ)." }, { "code": null, "e": 5679, "s": 5110, "text": "In statistics, instead of saying our data is two standard deviations from the mean, we assess it in terms of a z-score, which just represents the number of standard deviations a point is from the mean. Conversion to a z-score is done by subtracting the mean of the distribution from the data point and dividing by the standard deviation. In the height example, you can check that our friend would have a z-score of 2. If we do this to all the data points the new distribution is called the standard normal with a mean of 0 and a standard deviation of 1 as shown below." }, { "code": null, "e": 6522, "s": 5679, "text": "Every time we do a hypothesis test, we need to assume a distribution for the test statistic, which in our case is the average (mean) hours of sleep for our students. For a z-test, the normal curve is used as an approximation for the distribution of the test statistic. Generally, according to the central limit theorem, as we take more averages from a data distribution, the averages will tend towards a normal distribution. However, this will always be an estimate because real-world data never perfectly follows a normal distribution. Assuming a normal distribution lets us determine how meaningful the result we observe in a study is. The higher or lower the z-score, the more unlikely the result is to happen by chance and the more likely the result is meaningful. To quantify just how meaningful the results are, we use one more concept." }, { "code": null, "e": 6751, "s": 6522, "text": "The final core idea is that of p-values. A p-value is the probability of observing results at least as extreme as those measured when the null hypothesis is true. That might seem a little convoluted, so let’s look at an example." }, { "code": null, "e": 7513, "s": 6751, "text": "Say we are measuring average IQ in the US states of Florida and Washington. Our null hypothesis is that average IQs in Washington are not higher than average IQs in Florida. We perform the study and find IQs in Washington are higher by 2.2 points with a p-value of 0.346. This means, in a world where the null hypothesis — average IQs in Washington are not higher than average IQs in Florida — is true, there is a 34.6% chance we would measure IQs at least 2.2 points higher in Washington. So, if IQs in Washington are not actually higher, we would still measure they are higher by at least 2.2 points about 1/3 of the time due to random noise. Subsequently, the lower the p-value, the more meaningful the result because it is less likely to be caused by noise." }, { "code": null, "e": 7955, "s": 7513, "text": "Whether or not the result can be called statistically significant depends on the p-value (known as alpha) we establish for significance before we begin the experiment . If the observed p-value is less than alpha, then the results are statistically significant. We need to choose alpha before the experiment because if we waited until after, we could just select a number that proves our results are significant no matter what the data shows!" }, { "code": null, "e": 8548, "s": 7955, "text": "The choice of alpha depends on the situation and the field of study, but the most commonly used value is 0.05, corresponding to a 5% chance the results occurred at random. In my lab, I see values from 0.1 to 0.001 commonly in use. As an extreme example, the physicists who discovered the Higgs Boson particle used a p-value of 0.0000003, or a 1 in 3.5 million chance the discovery occurred because of noise. (Statisticians are loathe to admit that a p-value of 0.05 is arbitrary. R.A. Fischer, the father of modern statistics, choose a p-value of 0.05 for indeterminate reasons and it stuck)!" }, { "code": null, "e": 8895, "s": 8548, "text": "To get from a z-score on the normal distribution to a p-value, we can use a table or statistical software like R. The result will show us the probability of a z-score lower than the calculated value. For example, with a z-score of 2, the p-value is 0.977, which means there is only a 2.3% probability we observe a z-score higher than 2 at random." }, { "code": null, "e": 8945, "s": 8895, "text": "As a summary so far, we have covered three ideas:" }, { "code": null, "e": 9205, "s": 8945, "text": "Hypothesis Testing: A technique used to test a theoryNormal Distribution: An approximate representation of the data in a hypothesis test.p-value: The probability a result at least as extreme at that observed would have occurred if the null hypothesis is true." }, { "code": null, "e": 9259, "s": 9205, "text": "Hypothesis Testing: A technique used to test a theory" }, { "code": null, "e": 9344, "s": 9259, "text": "Normal Distribution: An approximate representation of the data in a hypothesis test." }, { "code": null, "e": 9467, "s": 9344, "text": "p-value: The probability a result at least as extreme at that observed would have occurred if the null hypothesis is true." }, { "code": null, "e": 9539, "s": 9467, "text": "Now, let’s put the pieces together in our example. Here are the basics:" }, { "code": null, "e": 9648, "s": 9539, "text": "Students across the country average 7.02 hours of sleep per night according to the National Sleep Foundation" }, { "code": null, "e": 9785, "s": 9648, "text": "In a poll of 202 students at our university the average hours of sleep per night was 6.90 hours with a standard deviation of 0.84 hours." }, { "code": null, "e": 9915, "s": 9785, "text": "Our alternative hypothesis is the average sleep of students at our university is below the national average for college students." }, { "code": null, "e": 10019, "s": 9915, "text": "We will use an alpha value of 0.05 which means the results are significant f the p-value is below 0.05." }, { "code": null, "e": 10515, "s": 10019, "text": "First, we need to convert our measurement into a z-score, or the number of standard deviations it is away from the mean. We do this by subtracting the population mean (the national average) from our measured value and dividing by the standard deviation over the square root of the number of samples. (As the number of samples increases, the standard deviation and hence the variation decreases. We account for this by dividing the standard deviation by the square root of the number of samples.)" }, { "code": null, "e": 10809, "s": 10515, "text": "The z-score is called our test-statistic. Once we have a test-statistic, we can use a table or a programming language such as R to calculate the p-value. I use code here not to intimidate but to show how easy it is to implement our solution with free tools! (# are comments and bold is output)" }, { "code": null, "e": 11045, "s": 10809, "text": "# Calculate the resultsz_score = (6.90 - 7.02) / (0.84 / sqrt(202)) p_value = pnorm(z_score)# Print our resultssprintf('The p-value is %0:5f for a z-score of %0.5f.', p_value, z_score)\"The p-value is 0.02116 for a z-score of -2.03038.\"" }, { "code": null, "e": 11494, "s": 11045, "text": "Based on the p-value of 0.02116, we can reject the null hypothesis. (Statisticians like us to say reject the null rather than accept the alternative.) There is statistically significant evidence our students get less sleep on average than college students in the US at a significance level of 0.05. The p-value shows there is a 2.12% chance that our results occurred because of random noise. In this battle of the presidents, the student was right." }, { "code": null, "e": 12408, "s": 11494, "text": "Before we ban all homework, we need to be careful not to assign too much to this result. Notice that our p-value, 0.02116, would not be significant if we had used a threshold of 0.01. Someone who wants to prove the opposite point in our study can simply manipulate the p-value. Anytime we examine a study, we should think about the p-value and the sample size in addition to the conclusion. With a relatively small sample size of 202, our study might have statistical significance, but that does mean it is practically meaningful. Further, this was an observational study, which means there is only evidence for correlation and not causation. We showed there is a correlation between students at our school and less average sleep, but not that going to our school causes a decrease in sleep. There could be other factors at play that affect sleep and only a randomized controlled study is able to prove causation." }, { "code": null, "e": 12977, "s": 12408, "text": "As with most technical concepts, statistical significance is not that complex and is just a combination of many small ideas. Most of the trouble comes with learning the vocabulary! Once you put the pieces together, you can start applying these statistical concepts. As you learn the basics of stats, you become better prepared to view studies and the news with a healthy skepticism. You can see what the data actually says rather than what someone tells you it means. The best tactic against dishonest politicians and corporations is a skeptical, well-educated public!" } ]
Responsible Machine Learning with Error Analysis | by Besmira Nushi | Towards Data Science
Website: ErrorAnalysis.ai Github repository: https://github.com/microsoft/responsible-ai-widgets/ Machine Learning (ML) teams who deploy models in the real world often face the challenges of conducting rigorous performance evaluation and testing for ML models. How often do we read claims such as “Model X is 90% on a given benchmark” and wonder, what does this claim mean for practical usage of the model? In practice, teams are well aware that model accuracy may not be uniform across subgroups of data and that there might exist input conditions for which the model fails more often. Often, such failures may cause direct consequences related to lack of reliability and safety, unfairness, or more broadly lack of trust in machine learning altogether. For instance, when a traffic sign detector does not operate well in certain daylight conditions or for unexpected inputs, even though the overall accuracy of the model may be high, it is still important for the development team to know ahead of time about the fact that the model may not be as reliable in such situations. While there exist several problems with current model assessment practices, one of the most obvious is the usage of aggregate metrics to score models on a whole benchmark. It is difficult to convey a detailed story on model behavior with a single number and yet most of the research and leaderboards operate on single scores. At the same time, there may exist several dimensions of the input feature space that a practitioner may be interested in taking a deep dive and ask questions such as “What happens to the accuracy of the recognition model in a self-driving car when it is dark and snowing outside?” or “Does the loan approval model perform similarly for population cohorts across ethnicity, gender, age, and education?”. Navigating the terrain of failures along multiple potential dimensions like the above can be challenging. In addition, in the longer term, when models are updated and re-deployed frequently upon new data evidence or scientific progress, teams also need to continuously track and monitor model behavior so that updates do not introduce new mistakes and therefore break user trust. To address these problems, practitioners often have to create custom infrastructure, which is tedious and time-consuming. To accelerate rigorous ML development, in this blog you will learn how to use the Error Analysis tool for: 1) Getting a deep understanding of how failure is distributed for a model. 2) Debugging ML errors with active data exploration and interpretability techniques. The Error Analysis toolkit is integrated within the Responsible AI Widgets OSS repository, our starting point to provide a set of integrated tools to the open source community and ML practitioners. Not only a contribution to the OSS RAI community, but practitioners can also leverage these assessment tools in Azure Machine Learning, including Fairlearn & InterpretML and now Error Analysis in mid 2021. If you are interested in learning more about training model updates that remain backward compatible with their previous selves by minimizing regress and new errors, you can also check out our most recent open source library and tool BackwardCompatibilityML. To install the Responsible AI Widgets “raiwidgets” package, in your python environment simply run the following to install the raiwidgets package from pypi. If you do not have interpret-community already installed, you will also need to install this for supporting the generation of model explanations. pip install interpret-communitypip install raiwidgets Alternatively, you can also clone the open source repository and build the code from scratch: git clone https://github.com/microsoft/responsible-ai-widgets.git You will need to install yarn and node to build the visualization code, and then you can run: yarn installyarn buildall And install from the raiwidgets folder locally: cd raiwidgetspip install –e . For more information see the contributing guide. If you intend to run repository tests, in the raiwidgets folder of the repository run: pip install -r requirements.txt This post illustrates the Error Analysis tool by using a binary classification task on income prediction (>50K, <50K). The model under inspection will be trained using the tabular UCI Census Income dataset, which contains both numerical and categorical features such as age, education, number of working hours, ethnicity, etc. We can call the error analysis dashboard using the API below, which takes in an explanation object computed by one of the explainers from the interpret-community repository, the model or pipeline, a dataset and the corresponding labels (true_y parameter): ErrorAnalysisDashboard(global_explanation, model, dataset=x_test, true_y=y_test) For larger datasets, we can downsample the explanation to fewer rows but run error analysis on the full dataset. We can provide the downsampled explanation, the model or pipeline, the full dataset, and then both the labels for the sampled explanation and the full dataset, as well as (optionally) the names of the categorical features: ErrorAnalysisDashboard(global_explanation, model, dataset=X_test_original_full,true_y=y_test, categorical_features=categorical_features, true_y_dataset=y_test_full) All screenshots below are generated using a LGBMClassifier with three estimators. You can directly run this example using the jupyter notebooks in our repository. Error Analysis starts with identifying the cohorts of data with a higher error rate versus the overall benchmark error rate. The dashboard allows for error exploration by using either an error heatmap or a decision tree guided by errors. Error Heatmap for Error Identification The view slices the data based on a one- or two-dimensional grid of input features. Users can choose the input features of interest for analysis. The heatmap visualizes cells with higher error with a darker red color to bring the user’s attention to regions with high error discrepancy. This is beneficial especially when the error themes are different in different partitions, which happens frequently in practice. In this error identification view, the analysis is highly guided by the users and their knowledge or hypotheses of what features might be most important for understanding failure. Decision Tree for Error Identification Very often, error patterns may be complex and involve more than one or two features. Therefore, it may be difficult for developers to explore all possible combinations of features to discover hidden data pockets with critical failure. To alleviate the burden, the binary tree visualization automatically partitions the benchmark data into interpretable subgroups, which have unexpectedly high or low error rates. In other words, the tree leverages the input features to maximally separate model error from success. For each node defining a data subgroup, users can investigate the following information: Error rate — a portion of instances in the node for which the model is incorrect. This is shown through the intensity of the red color. Error coverage — a portion of all errors that fall into the node. This is shown through the fill rate of the node. Data representation — number of instances in the node. This is shown through the thickness of the incoming edge to the node along with the actual total number of instances in the node. Cohort definition and manipulation To specialize the analysis and allow for deep dives, both error identification views can be generated for any data cohort and not only for the whole benchmark. Cohorts are subgroups of data that the user may choose to save for later use if they wish to come back to those cohorts for future investigation. They can be defined and manipulated interactively either from the heatmap or the tree. They can also be carried over to the next diagnostical views on data exploration and model explanations. After identifying cohorts with higher error rates, Error Analysis enables debugging and exploring these cohorts further. It is then possible to gain deeper insights about the model or the data through data exploration and model interpretability. Data Explorer: Users can explore dataset statistics and distributions by selecting different features and estimators along the two axes of the data explorer. They can further compare the subgroup data stats with other subgroups or the overall benchmark data. This view can for instance uncover if certain cohorts are underrepresented or if their feature distribution is significantly different from the overall data, hinting therefore to the potential existence of outliers or unusual covariate shift. Instance views: Beyond data statistics, sometimes it is useful to merely just observe the raw data along with labels in a tabular or tile form. Instance views provide this functionality and divide the instances into correct and incorrect tabs. By eyeballing the data, the developer can identify potential issues related to missing features or label noise. Model interpretability is a powerful means for extracting knowledge on how a model works. To extract this knowledge, Error Analysis relies on Microsoft’s InterpretML dashboard and library. The library is a prominent contribution in ML interpretability lead by Rich Caruana, Paul Koch, Harsha Nori, and Sam Jenkins. Global explanations Feature Importance: Users can explore the top K important features that impact the overall model predictions (a.k.a. global explanation) for a selected subgroup of data or cohort. They can also compare feature importance values for different cohorts side by side. The information on feature importance or the ordering is useful for understanding whether the model is leveraging features that are necessary for the prediction or whether it is relying on spurious correlations. By contrasting explanations that are specific to the cohort with those for the whole benchmark, it is possible to understand whether the model behaves differently or in an unusual way for the selected cohort. Dependence Plot: Users can see the relationship between the values of the selected feature to its corresponding feature importance values. This shows them how values of the selected feature impact model prediction. Local explanations Global explanations approximate the overall model behavior. For focusing the debugging process on a given data instance, users can select any individual data points (with correct or incorrect predictions) from the tabular instance view to explore their local feature importance values (local explanation) and individual conditional expectation (ICE) plots. Local Feature Importance: Users can investigate the top K (configurable K) important features for an individual prediction. Helps illustrate the local behavior of the underlying model on a specific data point. Individual Conditional Expectation (ICE): Users can investigate how changing a feature value from a minimum value to a maximum value impacts the prediction on the selected data instance. Perturbation Exploration (what-if analysis): Users can apply changes to feature values of the selected data point and observe resulting changes to the prediction. They can save their hypothetical what-if data points for further comparisons with other what-if or original data points. Error Analysis enables practitioners to identify and diagnose error patterns. The integration with model interpretability techniques testifies to the joint power of providing such tools together as part of the same platform. We are actively working towards integrating further considerations into the model assessment experience such as fairness and inclusion (via FairLearn) as well as backward compatibility during updates (via BackwardCompatibilityML). The initial work on error analysis started with research investigations on methodologies for in-depth understanding and explanation of Machine Learning failures. Besmira Nushi, Ece Kamar, and Eric Horvitz at Microsoft Research are leading these efforts and continue to innovate with new techniques for debugging ML models. In the past two years, our team was extended via a collaboration with the RAI tooling team in the Azure Machine Learning group as well as the Analysis Platform team in Microsoft Mixed Reality. The Analysis Platform team has invested several years of engineering work in building internal infrastructure and now we are making these efforts available to the community as open source as part of the Azure Machine Learning ecosystem. The RAI tooling team consists of Ilya Matiach, Mehrnoosh Sameki, Roman Lutz, Richard Edgar, Hyemi Song, Minsoo Thigpen, and Anup Shirgaonkar. They are passionate about democratizing Responsible AI and have several years of experience in shipping such tools for the community with previous examples on FairLearn, InterpretML Dashboard etc. We also received generous help and expertise along the way from our partners at Microsoft Aether Committee and Microsoft Mixed Reality: Parham Mohadjer, Paul Koch, Xavier Fernandes, and Juan Lema. All marketing initiatives, including the presentation of this blog, were coordinated by Thuy Nguyen. Big thanks to everyone who made this possible! Towards Accountable AI: Hybrid Human-Machine Analyses for Characterizing System Failure. Besmira Nushi, Ece Kamar, Eric Horvitz; HCOMP 2018. pdf Software Engineering for Machine Learning: A Case Study. Saleema Amershi, Andrew Begel, Christian Bird, Rob DeLine, Harald Gall, Ece Kamar, Nachiappan Nagappan, Besmira Nushi, Thomas Zimmermann; ICSE 2019. pdf Updates in Human-AI Teams: Understanding and Addressing the Performance/Compatibility Tradeoff. Gagan Bansal, Besmira Nushi, Ece Kamar, Daniel S Weld, Walter S Lasecki, Eric Horvitz; AAAI 2019. pdf An Empirical Analysis of Backward Compatibility in Machine Learning Systems. Megha Srivastava, Besmira Nushi, Ece Kamar, Shital Shah, Eric Horvitz; KDD 2020. pdf Understanding Failures of Deep Networks via Robust Feature Extraction. Sahil Singla, Besmira Nushi, Shital Shah, Ece Kamar, Eric Horvitz. CVPR 2021 (to appear). pdf
[ { "code": null, "e": 197, "s": 171, "text": "Website: ErrorAnalysis.ai" }, { "code": null, "e": 269, "s": 197, "text": "Github repository: https://github.com/microsoft/responsible-ai-widgets/" }, { "code": null, "e": 1249, "s": 269, "text": "Machine Learning (ML) teams who deploy models in the real world often face the challenges of conducting rigorous performance evaluation and testing for ML models. How often do we read claims such as “Model X is 90% on a given benchmark” and wonder, what does this claim mean for practical usage of the model? In practice, teams are well aware that model accuracy may not be uniform across subgroups of data and that there might exist input conditions for which the model fails more often. Often, such failures may cause direct consequences related to lack of reliability and safety, unfairness, or more broadly lack of trust in machine learning altogether. For instance, when a traffic sign detector does not operate well in certain daylight conditions or for unexpected inputs, even though the overall accuracy of the model may be high, it is still important for the development team to know ahead of time about the fact that the model may not be as reliable in such situations." }, { "code": null, "e": 2358, "s": 1249, "text": "While there exist several problems with current model assessment practices, one of the most obvious is the usage of aggregate metrics to score models on a whole benchmark. It is difficult to convey a detailed story on model behavior with a single number and yet most of the research and leaderboards operate on single scores. At the same time, there may exist several dimensions of the input feature space that a practitioner may be interested in taking a deep dive and ask questions such as “What happens to the accuracy of the recognition model in a self-driving car when it is dark and snowing outside?” or “Does the loan approval model perform similarly for population cohorts across ethnicity, gender, age, and education?”. Navigating the terrain of failures along multiple potential dimensions like the above can be challenging. In addition, in the longer term, when models are updated and re-deployed frequently upon new data evidence or scientific progress, teams also need to continuously track and monitor model behavior so that updates do not introduce new mistakes and therefore break user trust." }, { "code": null, "e": 2587, "s": 2358, "text": "To address these problems, practitioners often have to create custom infrastructure, which is tedious and time-consuming. To accelerate rigorous ML development, in this blog you will learn how to use the Error Analysis tool for:" }, { "code": null, "e": 2662, "s": 2587, "text": "1) Getting a deep understanding of how failure is distributed for a model." }, { "code": null, "e": 2747, "s": 2662, "text": "2) Debugging ML errors with active data exploration and interpretability techniques." }, { "code": null, "e": 3151, "s": 2747, "text": "The Error Analysis toolkit is integrated within the Responsible AI Widgets OSS repository, our starting point to provide a set of integrated tools to the open source community and ML practitioners. Not only a contribution to the OSS RAI community, but practitioners can also leverage these assessment tools in Azure Machine Learning, including Fairlearn & InterpretML and now Error Analysis in mid 2021." }, { "code": null, "e": 3409, "s": 3151, "text": "If you are interested in learning more about training model updates that remain backward compatible with their previous selves by minimizing regress and new errors, you can also check out our most recent open source library and tool BackwardCompatibilityML." }, { "code": null, "e": 3712, "s": 3409, "text": "To install the Responsible AI Widgets “raiwidgets” package, in your python environment simply run the following to install the raiwidgets package from pypi. If you do not have interpret-community already installed, you will also need to install this for supporting the generation of model explanations." }, { "code": null, "e": 3766, "s": 3712, "text": "pip install interpret-communitypip install raiwidgets" }, { "code": null, "e": 3860, "s": 3766, "text": "Alternatively, you can also clone the open source repository and build the code from scratch:" }, { "code": null, "e": 3926, "s": 3860, "text": "git clone https://github.com/microsoft/responsible-ai-widgets.git" }, { "code": null, "e": 4020, "s": 3926, "text": "You will need to install yarn and node to build the visualization code, and then you can run:" }, { "code": null, "e": 4046, "s": 4020, "text": "yarn installyarn buildall" }, { "code": null, "e": 4094, "s": 4046, "text": "And install from the raiwidgets folder locally:" }, { "code": null, "e": 4124, "s": 4094, "text": "cd raiwidgetspip install –e ." }, { "code": null, "e": 4173, "s": 4124, "text": "For more information see the contributing guide." }, { "code": null, "e": 4260, "s": 4173, "text": "If you intend to run repository tests, in the raiwidgets folder of the repository run:" }, { "code": null, "e": 4292, "s": 4260, "text": "pip install -r requirements.txt" }, { "code": null, "e": 4619, "s": 4292, "text": "This post illustrates the Error Analysis tool by using a binary classification task on income prediction (>50K, <50K). The model under inspection will be trained using the tabular UCI Census Income dataset, which contains both numerical and categorical features such as age, education, number of working hours, ethnicity, etc." }, { "code": null, "e": 4875, "s": 4619, "text": "We can call the error analysis dashboard using the API below, which takes in an explanation object computed by one of the explainers from the interpret-community repository, the model or pipeline, a dataset and the corresponding labels (true_y parameter):" }, { "code": null, "e": 4956, "s": 4875, "text": "ErrorAnalysisDashboard(global_explanation, model, dataset=x_test, true_y=y_test)" }, { "code": null, "e": 5292, "s": 4956, "text": "For larger datasets, we can downsample the explanation to fewer rows but run error analysis on the full dataset. We can provide the downsampled explanation, the model or pipeline, the full dataset, and then both the labels for the sampled explanation and the full dataset, as well as (optionally) the names of the categorical features:" }, { "code": null, "e": 5457, "s": 5292, "text": "ErrorAnalysisDashboard(global_explanation, model, dataset=X_test_original_full,true_y=y_test, categorical_features=categorical_features, true_y_dataset=y_test_full)" }, { "code": null, "e": 5620, "s": 5457, "text": "All screenshots below are generated using a LGBMClassifier with three estimators. You can directly run this example using the jupyter notebooks in our repository." }, { "code": null, "e": 5858, "s": 5620, "text": "Error Analysis starts with identifying the cohorts of data with a higher error rate versus the overall benchmark error rate. The dashboard allows for error exploration by using either an error heatmap or a decision tree guided by errors." }, { "code": null, "e": 5897, "s": 5858, "text": "Error Heatmap for Error Identification" }, { "code": null, "e": 6493, "s": 5897, "text": "The view slices the data based on a one- or two-dimensional grid of input features. Users can choose the input features of interest for analysis. The heatmap visualizes cells with higher error with a darker red color to bring the user’s attention to regions with high error discrepancy. This is beneficial especially when the error themes are different in different partitions, which happens frequently in practice. In this error identification view, the analysis is highly guided by the users and their knowledge or hypotheses of what features might be most important for understanding failure." }, { "code": null, "e": 6532, "s": 6493, "text": "Decision Tree for Error Identification" }, { "code": null, "e": 7136, "s": 6532, "text": "Very often, error patterns may be complex and involve more than one or two features. Therefore, it may be difficult for developers to explore all possible combinations of features to discover hidden data pockets with critical failure. To alleviate the burden, the binary tree visualization automatically partitions the benchmark data into interpretable subgroups, which have unexpectedly high or low error rates. In other words, the tree leverages the input features to maximally separate model error from success. For each node defining a data subgroup, users can investigate the following information:" }, { "code": null, "e": 7272, "s": 7136, "text": "Error rate — a portion of instances in the node for which the model is incorrect. This is shown through the intensity of the red color." }, { "code": null, "e": 7387, "s": 7272, "text": "Error coverage — a portion of all errors that fall into the node. This is shown through the fill rate of the node." }, { "code": null, "e": 7572, "s": 7387, "text": "Data representation — number of instances in the node. This is shown through the thickness of the incoming edge to the node along with the actual total number of instances in the node." }, { "code": null, "e": 7607, "s": 7572, "text": "Cohort definition and manipulation" }, { "code": null, "e": 8105, "s": 7607, "text": "To specialize the analysis and allow for deep dives, both error identification views can be generated for any data cohort and not only for the whole benchmark. Cohorts are subgroups of data that the user may choose to save for later use if they wish to come back to those cohorts for future investigation. They can be defined and manipulated interactively either from the heatmap or the tree. They can also be carried over to the next diagnostical views on data exploration and model explanations." }, { "code": null, "e": 8351, "s": 8105, "text": "After identifying cohorts with higher error rates, Error Analysis enables debugging and exploring these cohorts further. It is then possible to gain deeper insights about the model or the data through data exploration and model interpretability." }, { "code": null, "e": 8853, "s": 8351, "text": "Data Explorer: Users can explore dataset statistics and distributions by selecting different features and estimators along the two axes of the data explorer. They can further compare the subgroup data stats with other subgroups or the overall benchmark data. This view can for instance uncover if certain cohorts are underrepresented or if their feature distribution is significantly different from the overall data, hinting therefore to the potential existence of outliers or unusual covariate shift." }, { "code": null, "e": 9209, "s": 8853, "text": "Instance views: Beyond data statistics, sometimes it is useful to merely just observe the raw data along with labels in a tabular or tile form. Instance views provide this functionality and divide the instances into correct and incorrect tabs. By eyeballing the data, the developer can identify potential issues related to missing features or label noise." }, { "code": null, "e": 9524, "s": 9209, "text": "Model interpretability is a powerful means for extracting knowledge on how a model works. To extract this knowledge, Error Analysis relies on Microsoft’s InterpretML dashboard and library. The library is a prominent contribution in ML interpretability lead by Rich Caruana, Paul Koch, Harsha Nori, and Sam Jenkins." }, { "code": null, "e": 9544, "s": 9524, "text": "Global explanations" }, { "code": null, "e": 10229, "s": 9544, "text": "Feature Importance: Users can explore the top K important features that impact the overall model predictions (a.k.a. global explanation) for a selected subgroup of data or cohort. They can also compare feature importance values for different cohorts side by side. The information on feature importance or the ordering is useful for understanding whether the model is leveraging features that are necessary for the prediction or whether it is relying on spurious correlations. By contrasting explanations that are specific to the cohort with those for the whole benchmark, it is possible to understand whether the model behaves differently or in an unusual way for the selected cohort." }, { "code": null, "e": 10444, "s": 10229, "text": "Dependence Plot: Users can see the relationship between the values of the selected feature to its corresponding feature importance values. This shows them how values of the selected feature impact model prediction." }, { "code": null, "e": 10463, "s": 10444, "text": "Local explanations" }, { "code": null, "e": 10820, "s": 10463, "text": "Global explanations approximate the overall model behavior. For focusing the debugging process on a given data instance, users can select any individual data points (with correct or incorrect predictions) from the tabular instance view to explore their local feature importance values (local explanation) and individual conditional expectation (ICE) plots." }, { "code": null, "e": 11030, "s": 10820, "text": "Local Feature Importance: Users can investigate the top K (configurable K) important features for an individual prediction. Helps illustrate the local behavior of the underlying model on a specific data point." }, { "code": null, "e": 11217, "s": 11030, "text": "Individual Conditional Expectation (ICE): Users can investigate how changing a feature value from a minimum value to a maximum value impacts the prediction on the selected data instance." }, { "code": null, "e": 11501, "s": 11217, "text": "Perturbation Exploration (what-if analysis): Users can apply changes to feature values of the selected data point and observe resulting changes to the prediction. They can save their hypothetical what-if data points for further comparisons with other what-if or original data points." }, { "code": null, "e": 11957, "s": 11501, "text": "Error Analysis enables practitioners to identify and diagnose error patterns. The integration with model interpretability techniques testifies to the joint power of providing such tools together as part of the same platform. We are actively working towards integrating further considerations into the model assessment experience such as fairness and inclusion (via FairLearn) as well as backward compatibility during updates (via BackwardCompatibilityML)." }, { "code": null, "e": 13347, "s": 11957, "text": "The initial work on error analysis started with research investigations on methodologies for in-depth understanding and explanation of Machine Learning failures. Besmira Nushi, Ece Kamar, and Eric Horvitz at Microsoft Research are leading these efforts and continue to innovate with new techniques for debugging ML models. In the past two years, our team was extended via a collaboration with the RAI tooling team in the Azure Machine Learning group as well as the Analysis Platform team in Microsoft Mixed Reality. The Analysis Platform team has invested several years of engineering work in building internal infrastructure and now we are making these efforts available to the community as open source as part of the Azure Machine Learning ecosystem. The RAI tooling team consists of Ilya Matiach, Mehrnoosh Sameki, Roman Lutz, Richard Edgar, Hyemi Song, Minsoo Thigpen, and Anup Shirgaonkar. They are passionate about democratizing Responsible AI and have several years of experience in shipping such tools for the community with previous examples on FairLearn, InterpretML Dashboard etc. We also received generous help and expertise along the way from our partners at Microsoft Aether Committee and Microsoft Mixed Reality: Parham Mohadjer, Paul Koch, Xavier Fernandes, and Juan Lema. All marketing initiatives, including the presentation of this blog, were coordinated by Thuy Nguyen." }, { "code": null, "e": 13394, "s": 13347, "text": "Big thanks to everyone who made this possible!" }, { "code": null, "e": 13539, "s": 13394, "text": "Towards Accountable AI: Hybrid Human-Machine Analyses for Characterizing System Failure. Besmira Nushi, Ece Kamar, Eric Horvitz; HCOMP 2018. pdf" }, { "code": null, "e": 13749, "s": 13539, "text": "Software Engineering for Machine Learning: A Case Study. Saleema Amershi, Andrew Begel, Christian Bird, Rob DeLine, Harald Gall, Ece Kamar, Nachiappan Nagappan, Besmira Nushi, Thomas Zimmermann; ICSE 2019. pdf" }, { "code": null, "e": 13947, "s": 13749, "text": "Updates in Human-AI Teams: Understanding and Addressing the Performance/Compatibility Tradeoff. Gagan Bansal, Besmira Nushi, Ece Kamar, Daniel S Weld, Walter S Lasecki, Eric Horvitz; AAAI 2019. pdf" }, { "code": null, "e": 14109, "s": 13947, "text": "An Empirical Analysis of Backward Compatibility in Machine Learning Systems. Megha Srivastava, Besmira Nushi, Ece Kamar, Shital Shah, Eric Horvitz; KDD 2020. pdf" } ]
Financial Fraud Detection with AutoXGB | by Kenneth Leung | Towards Data Science
XGBoost has established itself as one of the most important machine learning algorithms due to its versatility and impressive performance. Having used XGBoost for previous projects, I am always open to making its implementation faster, better, and cheaper. My curiosity was piqued when I came across AutoXGB, which claims to be an automated tool for simplifying the training and deployment of XGBoost models. Given my work in the financial services sector, where fraud is a significant concern, it would be an excellent opportunity to use credit card fraud data to assess how AutoXGB fares against the standard XGBoost setup usually used. (1) Data Acquisition and Understanding(2) Handling Class Imbalance(3) Choice of Performance Metric(4) Baseline — XGBoost with RandomizedSearchCV(5) Putting AutoXGB to the Test(6) Final Verdict Click here to view the GitHub repo for this project This project uses the credit card transaction data from the research collaboration between Worldline and Machine Learning Group (University of Brussells) on fraud detection (used under GNU Public License). The dataset is a realistic simulation of real-world credit card transactions and has been designed to include complicated fraud detection issues. These issues include class imbalance (only <1% of transactions are fraudulent), a mix of numerical and (high cardinality) categorical variables, and time-dependent fraud occurrences. We will be using the transformed dataset instead of the raw one to align with the project objective. The details of the baseline feature engineering are out of scope, so here is a brief summary: Indicate whether the transaction occurred (i) during the day or night; (ii) on a weekday or weekend. This is done because fraudulent patterns differ based on time of day and day of week Characterize customer spending behavior (e.g., average spending, number of transactions) by using the RFM (Recency, Frequency, Monetary value) metric Classify risk associated with each payment terminal by calculating its average count of fraud cases over a time window Upon completion of the feature engineering, we have a dataset with the following features: TX_AMOUNT: Transaction amount in dollars [float] TX_DURING_WEEKEND: Whether transaction took place on the weekend [boolean] TX_DURING_NIGHT: Whether transaction took place at night [boolean] CUSTOMER_ID_NB_TX_*DAY_WINDOW: Number of transactions for each customer over the last 1, 7, and 30 days [integer] CUSTOMER_ID_AVG_AMOUNT_*DAY_WINDOW: Average amount (dollars) spent by each customer in the last 1, 7, and 30 days [float] TERMINAL_ID_NB_TX_*DAY_WINDOW: Number of transactions on the terminal over the last 1, 7, and 30 days [integer] TERMINAL_ID_RISK_*DAY_WINDOW: Average number of fraudulent transactions on the terminal over the last 1, 7, and 30 days [integer] TX_FRAUD: Indicator for whether the transaction is legitimate (0) or fraudulent (1) [boolean] From the target variable TX_FRAUD, we can see that we are dealing with a binary classification task. An important aspect to consider in fraud detection is the delay period (aka feedback delay). In real-world situations, a fraudulent transaction is only known some time after a complaint or investigation has been made. Therefore, we need to introduce a sequential delay period (e.g., one week) to separate the train and test sets, where the test set should occur at least one week after the last transaction of the train set. The train-test split is as follows: Train Set: 8 weeks (2018–Jul–01 to 2018–Aug–27) Delay Period: 1 week (2018–Aug–28 to 2018–Sep–03) Test Set: 1 week (2018–Sep–04 to 2018–Sep–10) Fraudulent transactions do not happen regularly, so it is no surprise that we have a heavily imbalanced dataset on our hands. From the value count of the target variable, there were only 4,935 fraudulent cases (0.9%) out of the 550k+ transactions. We can use the synthetic Minority Oversampling Technique (SMOTE) to handle this class imbalance. The authors of the original SMOTE paper combined SMOTE and random under-sampling in their implementation, so I used that combination in this project. The specific sampling strategy is as follows: SMOTE over-sampling to increase the minority class to 5% of the total dataset (500% increase from original 0.9%), thenRandom under-sampling to make the majority class twice the size of the minority class (i.e., minority class 50% the size of majority class) SMOTE over-sampling to increase the minority class to 5% of the total dataset (500% increase from original 0.9%), then Random under-sampling to make the majority class twice the size of the minority class (i.e., minority class 50% the size of majority class) Although the SMOTE authors showed that varying combinations gave comparable results, I chose the 500%/50% combination because the paper showed that it gave the highest accuracy on minority examples in the Oil dataset. After this sampling, the dataset is more balanced, with the minority class increasing from 0.9% to 33.3% of the entire dataset. Before we begin modeling, we have to decide what is the ideal metric to assess model performance. The typical ones are threshold-based metrics like accuracy and F1-score. While they can assess the degree of misclassification, they depend on the definition of a specific decision threshold, e.g., probability>0.5 =fraud. These metrics’ dependence on a decision threshold makes it challenging to compare different models. Therefore, a better choice would be threshold-free metrics such as AUC ROC and Average Precision. Average Precision summarizes the precision-recall curve as the weighted mean of precisions achieved at each threshold, with the weight being the increase in recall from the previous threshold. While AUC-ROC is more common, Average Precision is chosen as the primary reporting metric in this project for the following reasons: Average Precision is more informative than AUC ROC for imbalanced datasets. While we have applied sampling to balance our data, I felt that there was still a degree of residual imbalance (67:33 instead of 50:50) Too many false positives can overburden the fraud investigation team, so we want to assess the recall (aka sensitivity) at low false-positive rate (FPR) values. The advantage of using PR curves (and AP) over ROC is that PR curves can effectively highlight model performance for low FPR values. The setup for the baseline model (XGBoost with RandomizedSearchCV) is the one that I tend to use as a first-line approach for classification tasks. Here are the test set prediction results from the baseline model, where the key metric of Average Precision is 0.776. The time taken for training was 13 minutes. In line with the recent rise of AutoML solutions, AutoXGB is a library that automatically trains, evaluates, and deploys XGBoost models from tabular data in CSV format. The hyperparameter tuning is done automatically using Optuna, and the deployment is carried out with FastAPI. AutoXGB was developed by Abhishek Thakur, a researcher at HuggingFace who holds the title of the world’s first 4x Kaggle Grandmaster. In his own words, AutoXGB is a no-brainer for setting up XGBoost models. Therefore, I was keen to tap into his expertise to explore and improve the way my XGBoost models are usually implemented. To install AutoXGB, run the following command: pip install autoxgb The AutoXGB framework significantly simplifies the steps required to set up XGBoost training and prediction. Here is the code used to setup AutoXGB for the binary classification task: Here are the test set results from AutoXGB, where the key metric of Average Precision is 0.782. The time taken for training was 9 minutes. AutoXGB delivered a slightly higher Average Precision score of 0.782 as compared to the baseline score of 0.776. The time taken for AutoXGB training is approximately 30% shorter, taking just 9 minutes as compared to the baseline of 13 minutes. Another key advantage of AutoXGB is that we are only one command line away from serving the model as a FastAPI endpoint. This setup reduces the time to model deployment, which is a critical factor beyond training time. The following factors are likely the ones that drive AutoXGB’s better performance: Use of Bayesian optimization with Optuna for hyperparameter tuning, which is faster than randomized search as it uses information from previous iterations to find the best hyperparameters in fewer iterations Careful selection of XGBoost hyperparameters (type and range) for tuning based on the author’s extensive data science experience Optimization of memory usage with specific typecasting, e.g., convert values with data type int8 to int64 (which consumes 8x less memory) While the performance metrics give AutoXGB an edge, one of its most significant issues is the loss of granular control in the parameter settings. If you have been following closely, you may realize that we did not introduce the sequential delay period we applied for train/test split for cross-validation (which we should have been done). In this case, AutoXGB does not allow us to specify the validation fold we want to use as part of cross-validation (CV) since the only CV-related parameter is n_folds (number of CV folds). Another issue with this lack of control is that we cannot specify the evaluation metric for the XGBoost classifier. In the baseline model, I was able to set the eval_metric to be aucpr (AUC under PR curve), which aligns with our primary metric of Average Precision. However, the hard-coded evaluation metric within the XGBoost Classifier of AutoXGB is logloss for binary classification. At the end of the day, while solutions like AutoXGB do well in simplifying (and possibly improving) XGBoost implementation, data scientists need to understand its limitations by knowing what goes on under the hood. Feel free to check out the codes in the GitHub repo here. I welcome you to join me on a data science learning journey! Follow my Medium page and GitHub to stay in the loop of more exciting data science content. Meanwhile, have fun using AutoXGB in your ML tasks! medium.com towardsdatascience.com towardsdatascience.com Machine Learning for Credit Card Fraud Detection — Practical Handbook AutoXGB — GitHub
[ { "code": null, "e": 311, "s": 172, "text": "XGBoost has established itself as one of the most important machine learning algorithms due to its versatility and impressive performance." }, { "code": null, "e": 581, "s": 311, "text": "Having used XGBoost for previous projects, I am always open to making its implementation faster, better, and cheaper. My curiosity was piqued when I came across AutoXGB, which claims to be an automated tool for simplifying the training and deployment of XGBoost models." }, { "code": null, "e": 811, "s": 581, "text": "Given my work in the financial services sector, where fraud is a significant concern, it would be an excellent opportunity to use credit card fraud data to assess how AutoXGB fares against the standard XGBoost setup usually used." }, { "code": null, "e": 1004, "s": 811, "text": "(1) Data Acquisition and Understanding(2) Handling Class Imbalance(3) Choice of Performance Metric(4) Baseline — XGBoost with RandomizedSearchCV(5) Putting AutoXGB to the Test(6) Final Verdict" }, { "code": null, "e": 1056, "s": 1004, "text": "Click here to view the GitHub repo for this project" }, { "code": null, "e": 1262, "s": 1056, "text": "This project uses the credit card transaction data from the research collaboration between Worldline and Machine Learning Group (University of Brussells) on fraud detection (used under GNU Public License)." }, { "code": null, "e": 1408, "s": 1262, "text": "The dataset is a realistic simulation of real-world credit card transactions and has been designed to include complicated fraud detection issues." }, { "code": null, "e": 1591, "s": 1408, "text": "These issues include class imbalance (only <1% of transactions are fraudulent), a mix of numerical and (high cardinality) categorical variables, and time-dependent fraud occurrences." }, { "code": null, "e": 1786, "s": 1591, "text": "We will be using the transformed dataset instead of the raw one to align with the project objective. The details of the baseline feature engineering are out of scope, so here is a brief summary:" }, { "code": null, "e": 1972, "s": 1786, "text": "Indicate whether the transaction occurred (i) during the day or night; (ii) on a weekday or weekend. This is done because fraudulent patterns differ based on time of day and day of week" }, { "code": null, "e": 2122, "s": 1972, "text": "Characterize customer spending behavior (e.g., average spending, number of transactions) by using the RFM (Recency, Frequency, Monetary value) metric" }, { "code": null, "e": 2241, "s": 2122, "text": "Classify risk associated with each payment terminal by calculating its average count of fraud cases over a time window" }, { "code": null, "e": 2332, "s": 2241, "text": "Upon completion of the feature engineering, we have a dataset with the following features:" }, { "code": null, "e": 2381, "s": 2332, "text": "TX_AMOUNT: Transaction amount in dollars [float]" }, { "code": null, "e": 2456, "s": 2381, "text": "TX_DURING_WEEKEND: Whether transaction took place on the weekend [boolean]" }, { "code": null, "e": 2523, "s": 2456, "text": "TX_DURING_NIGHT: Whether transaction took place at night [boolean]" }, { "code": null, "e": 2637, "s": 2523, "text": "CUSTOMER_ID_NB_TX_*DAY_WINDOW: Number of transactions for each customer over the last 1, 7, and 30 days [integer]" }, { "code": null, "e": 2759, "s": 2637, "text": "CUSTOMER_ID_AVG_AMOUNT_*DAY_WINDOW: Average amount (dollars) spent by each customer in the last 1, 7, and 30 days [float]" }, { "code": null, "e": 2871, "s": 2759, "text": "TERMINAL_ID_NB_TX_*DAY_WINDOW: Number of transactions on the terminal over the last 1, 7, and 30 days [integer]" }, { "code": null, "e": 3001, "s": 2871, "text": "TERMINAL_ID_RISK_*DAY_WINDOW: Average number of fraudulent transactions on the terminal over the last 1, 7, and 30 days [integer]" }, { "code": null, "e": 3095, "s": 3001, "text": "TX_FRAUD: Indicator for whether the transaction is legitimate (0) or fraudulent (1) [boolean]" }, { "code": null, "e": 3196, "s": 3095, "text": "From the target variable TX_FRAUD, we can see that we are dealing with a binary classification task." }, { "code": null, "e": 3414, "s": 3196, "text": "An important aspect to consider in fraud detection is the delay period (aka feedback delay). In real-world situations, a fraudulent transaction is only known some time after a complaint or investigation has been made." }, { "code": null, "e": 3621, "s": 3414, "text": "Therefore, we need to introduce a sequential delay period (e.g., one week) to separate the train and test sets, where the test set should occur at least one week after the last transaction of the train set." }, { "code": null, "e": 3657, "s": 3621, "text": "The train-test split is as follows:" }, { "code": null, "e": 3705, "s": 3657, "text": "Train Set: 8 weeks (2018–Jul–01 to 2018–Aug–27)" }, { "code": null, "e": 3755, "s": 3705, "text": "Delay Period: 1 week (2018–Aug–28 to 2018–Sep–03)" }, { "code": null, "e": 3801, "s": 3755, "text": "Test Set: 1 week (2018–Sep–04 to 2018–Sep–10)" }, { "code": null, "e": 3927, "s": 3801, "text": "Fraudulent transactions do not happen regularly, so it is no surprise that we have a heavily imbalanced dataset on our hands." }, { "code": null, "e": 4049, "s": 3927, "text": "From the value count of the target variable, there were only 4,935 fraudulent cases (0.9%) out of the 550k+ transactions." }, { "code": null, "e": 4296, "s": 4049, "text": "We can use the synthetic Minority Oversampling Technique (SMOTE) to handle this class imbalance. The authors of the original SMOTE paper combined SMOTE and random under-sampling in their implementation, so I used that combination in this project." }, { "code": null, "e": 4342, "s": 4296, "text": "The specific sampling strategy is as follows:" }, { "code": null, "e": 4600, "s": 4342, "text": "SMOTE over-sampling to increase the minority class to 5% of the total dataset (500% increase from original 0.9%), thenRandom under-sampling to make the majority class twice the size of the minority class (i.e., minority class 50% the size of majority class)" }, { "code": null, "e": 4719, "s": 4600, "text": "SMOTE over-sampling to increase the minority class to 5% of the total dataset (500% increase from original 0.9%), then" }, { "code": null, "e": 4859, "s": 4719, "text": "Random under-sampling to make the majority class twice the size of the minority class (i.e., minority class 50% the size of majority class)" }, { "code": null, "e": 5077, "s": 4859, "text": "Although the SMOTE authors showed that varying combinations gave comparable results, I chose the 500%/50% combination because the paper showed that it gave the highest accuracy on minority examples in the Oil dataset." }, { "code": null, "e": 5205, "s": 5077, "text": "After this sampling, the dataset is more balanced, with the minority class increasing from 0.9% to 33.3% of the entire dataset." }, { "code": null, "e": 5303, "s": 5205, "text": "Before we begin modeling, we have to decide what is the ideal metric to assess model performance." }, { "code": null, "e": 5525, "s": 5303, "text": "The typical ones are threshold-based metrics like accuracy and F1-score. While they can assess the degree of misclassification, they depend on the definition of a specific decision threshold, e.g., probability>0.5 =fraud." }, { "code": null, "e": 5723, "s": 5525, "text": "These metrics’ dependence on a decision threshold makes it challenging to compare different models. Therefore, a better choice would be threshold-free metrics such as AUC ROC and Average Precision." }, { "code": null, "e": 5916, "s": 5723, "text": "Average Precision summarizes the precision-recall curve as the weighted mean of precisions achieved at each threshold, with the weight being the increase in recall from the previous threshold." }, { "code": null, "e": 6049, "s": 5916, "text": "While AUC-ROC is more common, Average Precision is chosen as the primary reporting metric in this project for the following reasons:" }, { "code": null, "e": 6261, "s": 6049, "text": "Average Precision is more informative than AUC ROC for imbalanced datasets. While we have applied sampling to balance our data, I felt that there was still a degree of residual imbalance (67:33 instead of 50:50)" }, { "code": null, "e": 6555, "s": 6261, "text": "Too many false positives can overburden the fraud investigation team, so we want to assess the recall (aka sensitivity) at low false-positive rate (FPR) values. The advantage of using PR curves (and AP) over ROC is that PR curves can effectively highlight model performance for low FPR values." }, { "code": null, "e": 6703, "s": 6555, "text": "The setup for the baseline model (XGBoost with RandomizedSearchCV) is the one that I tend to use as a first-line approach for classification tasks." }, { "code": null, "e": 6865, "s": 6703, "text": "Here are the test set prediction results from the baseline model, where the key metric of Average Precision is 0.776. The time taken for training was 13 minutes." }, { "code": null, "e": 7034, "s": 6865, "text": "In line with the recent rise of AutoML solutions, AutoXGB is a library that automatically trains, evaluates, and deploys XGBoost models from tabular data in CSV format." }, { "code": null, "e": 7144, "s": 7034, "text": "The hyperparameter tuning is done automatically using Optuna, and the deployment is carried out with FastAPI." }, { "code": null, "e": 7351, "s": 7144, "text": "AutoXGB was developed by Abhishek Thakur, a researcher at HuggingFace who holds the title of the world’s first 4x Kaggle Grandmaster. In his own words, AutoXGB is a no-brainer for setting up XGBoost models." }, { "code": null, "e": 7473, "s": 7351, "text": "Therefore, I was keen to tap into his expertise to explore and improve the way my XGBoost models are usually implemented." }, { "code": null, "e": 7520, "s": 7473, "text": "To install AutoXGB, run the following command:" }, { "code": null, "e": 7540, "s": 7520, "text": "pip install autoxgb" }, { "code": null, "e": 7724, "s": 7540, "text": "The AutoXGB framework significantly simplifies the steps required to set up XGBoost training and prediction. Here is the code used to setup AutoXGB for the binary classification task:" }, { "code": null, "e": 7863, "s": 7724, "text": "Here are the test set results from AutoXGB, where the key metric of Average Precision is 0.782. The time taken for training was 9 minutes." }, { "code": null, "e": 7976, "s": 7863, "text": "AutoXGB delivered a slightly higher Average Precision score of 0.782 as compared to the baseline score of 0.776." }, { "code": null, "e": 8107, "s": 7976, "text": "The time taken for AutoXGB training is approximately 30% shorter, taking just 9 minutes as compared to the baseline of 13 minutes." }, { "code": null, "e": 8326, "s": 8107, "text": "Another key advantage of AutoXGB is that we are only one command line away from serving the model as a FastAPI endpoint. This setup reduces the time to model deployment, which is a critical factor beyond training time." }, { "code": null, "e": 8409, "s": 8326, "text": "The following factors are likely the ones that drive AutoXGB’s better performance:" }, { "code": null, "e": 8617, "s": 8409, "text": "Use of Bayesian optimization with Optuna for hyperparameter tuning, which is faster than randomized search as it uses information from previous iterations to find the best hyperparameters in fewer iterations" }, { "code": null, "e": 8746, "s": 8617, "text": "Careful selection of XGBoost hyperparameters (type and range) for tuning based on the author’s extensive data science experience" }, { "code": null, "e": 8884, "s": 8746, "text": "Optimization of memory usage with specific typecasting, e.g., convert values with data type int8 to int64 (which consumes 8x less memory)" }, { "code": null, "e": 9030, "s": 8884, "text": "While the performance metrics give AutoXGB an edge, one of its most significant issues is the loss of granular control in the parameter settings." }, { "code": null, "e": 9223, "s": 9030, "text": "If you have been following closely, you may realize that we did not introduce the sequential delay period we applied for train/test split for cross-validation (which we should have been done)." }, { "code": null, "e": 9411, "s": 9223, "text": "In this case, AutoXGB does not allow us to specify the validation fold we want to use as part of cross-validation (CV) since the only CV-related parameter is n_folds (number of CV folds)." }, { "code": null, "e": 9527, "s": 9411, "text": "Another issue with this lack of control is that we cannot specify the evaluation metric for the XGBoost classifier." }, { "code": null, "e": 9798, "s": 9527, "text": "In the baseline model, I was able to set the eval_metric to be aucpr (AUC under PR curve), which aligns with our primary metric of Average Precision. However, the hard-coded evaluation metric within the XGBoost Classifier of AutoXGB is logloss for binary classification." }, { "code": null, "e": 10013, "s": 9798, "text": "At the end of the day, while solutions like AutoXGB do well in simplifying (and possibly improving) XGBoost implementation, data scientists need to understand its limitations by knowing what goes on under the hood." }, { "code": null, "e": 10071, "s": 10013, "text": "Feel free to check out the codes in the GitHub repo here." }, { "code": null, "e": 10276, "s": 10071, "text": "I welcome you to join me on a data science learning journey! Follow my Medium page and GitHub to stay in the loop of more exciting data science content. Meanwhile, have fun using AutoXGB in your ML tasks!" }, { "code": null, "e": 10287, "s": 10276, "text": "medium.com" }, { "code": null, "e": 10310, "s": 10287, "text": "towardsdatascience.com" }, { "code": null, "e": 10333, "s": 10310, "text": "towardsdatascience.com" }, { "code": null, "e": 10403, "s": 10333, "text": "Machine Learning for Credit Card Fraud Detection — Practical Handbook" } ]
How to create a canvas image using Fabric.js ? - GeeksforGeeks
07 Jan, 2022 In this article, we are going to see how to create a canvas-like image in JavaScript. Thee canvas like image means the image is movable and can be resized according to requirement. Approach: To make this possible we are going to use a JavaScript library called FabricJS. After importing the library, we will create a canvas block in the body tag which will contain our image. Further, we will create an img element which contains the image to be added inside the canvas and set the style attribute to display:none; because we don’t want the image to be visible outside the canvas. After this, we will initialize instances of Canvas and Image provided by FabricJS and render the Image on the Canvas as given in the example below. Syntax: fabric.Image( image_element ); Example: This example uses FabricJS to create simple editable canvas image. html <!DOCTYPE html><html> <head> <title> How to create a canvas-type image with JavaScript? </title> <!-- Loading the FabricJS library --> <script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/3.6.2/fabric.min.js"> </script></head> <body> <canvas id="canvas" width="600" height="200" style="border:1px solid #000000"> </canvas> <!-- Add the image to be used in the canvas and hide it here because only need it inside the canvas --> <img style="display: none;" src="https://media.geeksforgeeks.org/wp-content/uploads/20200327230544/g4gicon.png" id="my-image" alt=""> <script> // Initiate a Canvas instance var canvas = new fabric.Canvas("canvas"); // Get the image element var image = document.getElementById('my-image'); // Initiate a Fabric instance var fabricImage = new fabric.Image(image); // Add the image to canvas canvas.add(fabricImage); </script></body> </html> sumitgumber28 HTML-Misc JavaScript-Misc HTML JavaScript Web Technologies Web technologies Questions HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments How to update Node.js and NPM to next version ? Types of CSS (Cascading Style Sheet) How to Insert Form Data into Database using PHP ? CSS to put icon inside an input element in a form REST API (Introduction) Difference between var, let and const keywords in JavaScript Convert a string to an integer in JavaScript Differences between Functional Components and Class Components in React How to calculate the number of days between two dates in javascript? File uploading in React.js
[ { "code": null, "e": 24391, "s": 24363, "text": "\n07 Jan, 2022" }, { "code": null, "e": 24572, "s": 24391, "text": "In this article, we are going to see how to create a canvas-like image in JavaScript. Thee canvas like image means the image is movable and can be resized according to requirement." }, { "code": null, "e": 25120, "s": 24572, "text": "Approach: To make this possible we are going to use a JavaScript library called FabricJS. After importing the library, we will create a canvas block in the body tag which will contain our image. Further, we will create an img element which contains the image to be added inside the canvas and set the style attribute to display:none; because we don’t want the image to be visible outside the canvas. After this, we will initialize instances of Canvas and Image provided by FabricJS and render the Image on the Canvas as given in the example below." }, { "code": null, "e": 25128, "s": 25120, "text": "Syntax:" }, { "code": null, "e": 25161, "s": 25128, "text": " fabric.Image( image_element ); " }, { "code": null, "e": 25237, "s": 25161, "text": "Example: This example uses FabricJS to create simple editable canvas image." }, { "code": null, "e": 25242, "s": 25237, "text": "html" }, { "code": "<!DOCTYPE html><html> <head> <title> How to create a canvas-type image with JavaScript? </title> <!-- Loading the FabricJS library --> <script src=\"https://cdnjs.cloudflare.com/ajax/libs/fabric.js/3.6.2/fabric.min.js\"> </script></head> <body> <canvas id=\"canvas\" width=\"600\" height=\"200\" style=\"border:1px solid #000000\"> </canvas> <!-- Add the image to be used in the canvas and hide it here because only need it inside the canvas --> <img style=\"display: none;\" src=\"https://media.geeksforgeeks.org/wp-content/uploads/20200327230544/g4gicon.png\" id=\"my-image\" alt=\"\"> <script> // Initiate a Canvas instance var canvas = new fabric.Canvas(\"canvas\"); // Get the image element var image = document.getElementById('my-image'); // Initiate a Fabric instance var fabricImage = new fabric.Image(image); // Add the image to canvas canvas.add(fabricImage); </script></body> </html>", "e": 26287, "s": 25242, "text": null }, { "code": null, "e": 26301, "s": 26287, "text": "sumitgumber28" }, { "code": null, "e": 26311, "s": 26301, "text": "HTML-Misc" }, { "code": null, "e": 26327, "s": 26311, "text": "JavaScript-Misc" }, { "code": null, "e": 26332, "s": 26327, "text": "HTML" }, { "code": null, "e": 26343, "s": 26332, "text": "JavaScript" }, { "code": null, "e": 26360, "s": 26343, "text": "Web Technologies" }, { "code": null, "e": 26387, "s": 26360, "text": "Web technologies Questions" }, { "code": null, "e": 26392, "s": 26387, "text": "HTML" }, { "code": null, "e": 26490, "s": 26392, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26499, "s": 26490, "text": "Comments" }, { "code": null, "e": 26512, "s": 26499, "text": "Old Comments" }, { "code": null, "e": 26560, "s": 26512, "text": "How to update Node.js and NPM to next version ?" }, { "code": null, "e": 26597, "s": 26560, "text": "Types of CSS (Cascading Style Sheet)" }, { "code": null, "e": 26647, "s": 26597, "text": "How to Insert Form Data into Database using PHP ?" }, { "code": null, "e": 26697, "s": 26647, "text": "CSS to put icon inside an input element in a form" }, { "code": null, "e": 26721, "s": 26697, "text": "REST API (Introduction)" }, { "code": null, "e": 26782, "s": 26721, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 26827, "s": 26782, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 26899, "s": 26827, "text": "Differences between Functional Components and Class Components in React" }, { "code": null, "e": 26968, "s": 26899, "text": "How to calculate the number of days between two dates in javascript?" } ]
Modin: Accelerating Your Pandas Functions by Changing One Line of Code | by George Seif | Towards Data Science
Want to be inspired? Come join my Super Quotes newsletter. 😎 Pandas is the go-to library for processing data in Python. It’s easy to use and quite flexible when it comes to handling different types and sizes of data. It has tons of different functions that make manipulating data a breeze. But there is one drawback: Pandas is slow for larger datasets. By default, Pandas executes its functions as a single process using a single CPU core. That works just fine for smaller datasets since you might not notice much of a difference in speed. But with larger datasets, and so many more calculations to make, speed starts to take a major hit when using only a single core. It’s doing just one calculation at a time for a dataset that can have millions or even billions of rows. Yet most modern machines made for Data Science have at least 2 CPU cores. That means, for the example of 2 CPU cores, that 50% or more of your computer’s processing power won’t be doing anything by default when using Pandas. The situation gets even worse when you get to 4 cores (modern Intel i5) or 6 cores (modern Intel i7). Pandas simply wasn’t designed to use that computing power effectively. Modin is a new library designed to accelerate Pandas by automatically distributing the computation across all of the system’s available CPU cores. With that, Modin claims to be able to get nearly linear speedup to the number of CPU cores on your system for Pandas DataFrames of any size. Let’s see how it all works and go through a few code examples. Given a DataFrame in Pandas, our goal is to perform some kind of calculation or process on it in the fastest way possible. That could be taking the mean of each column with .mean(), grouping data with groupby, dropping all duplicates with drop_duplicates(), or any of the other built-in Pandas functions. In the previous section, we mentioned how Pandas only uses one CPU core for processing. Naturally, this is a big bottleneck, especially for larger DataFrames where the lack of resources really shows through. In theory, parallelizing a calculation is as easy as applying that calculation on different data points across every available CPU core. For a Pandas DataFrame, a basic idea would be to divide up the DataFrame into a few pieces, as many pieces as you have CPU cores, and let each CPU core run the calculation on its own piece. In the end, we can aggregate the results, which is a computationally cheap operation. That’s exactly what Modin does. It slices your DataFrame into different parts such that each part can be sent to a different CPU core. Modin partitions the DataFrames across both the rows and the columns. This makes Modin’s parallel processing scalable to DataFrames of any shape. Imagine if you are given a DataFrame with many columns but fewer rows. Some libraries only perform the partitioning across rows, which would be inefficient in this case since we have more columns than rows. But with Modin, since the partitioning is done across both dimensions, the parallel processing remains efficient all shapes of DataFrames, whether they are wider (lots of columns), longer (lots of rows), or both. The figure above is a simple example. Modin actually uses a Partition Manager that can change the size and shape of the partitions based on the type of operation. For example, there might be an operation that requires entire rows or entire columns. In that case, the Partition Manager will perform the partitions and distribution to CPU cores in the most optimal way it can find. It’s flexible. To do a lot of the heavy lifting when it comes to executing the parallel processing, Modin can use either Dask or Ray. Both of them are parallel computing libraries with Python APIs and you can select one or the other to use with Modin at runtime. Ray will be the safest one to use for now as it is more stable — the Dask backend is experimental. But hey, that’s enough theory. Let’s get to the code and speed benchmarks! The easiest way to install and get Modin working is via pip. The following command installs Modin, Ray, and all of the relevant dependencies: pip install modin[ray] For our following examples and benchmarks, we’re going to be using the CS:GO Competitive Matchmaking Data from Kaggle. Each row of the CSV contains data about a round in a competitive match of CS:GO. We’ll stick to experimenting with just the biggest CSV file for now (there are several) called esea_master_dmg_demos.part1.csv which is 1.2GB. With such a size, we should be able to see how Pandas slows down and how Modin can help us out. For the tests, I’ll be using an i7–8700k CPU which has 6 physical cores and 12 threads. The first test we’ll do is simply reading in the data with our good’ol read_csv(). The code itself is the exact same for both Pandas and Modin. To measure the speed, I imported the time module and put a time.time() before and after the read_csv(). As a result, Pandas took 8.38 seconds to load the data from CSV to memory while Modin took 3.22 seconds. That’s a speedup of 2.6X. Not too shabby for just changing the import statement! Let’s do a couple of heavier processes on our DataFrame. Concatenating multiple DataFrames is a common operation in Pandas — we might have several or more CSV files containing our data which we then have to read one at a time and concatenate. We can easily do this with the pd.concat() function in Pandas and Modin. We’d expect that Modin should do well with this kind of operation since it’s handling a lot of data. The code is shown below. In the above code, we concatenated our DataFrame to itself 5 times. Pandas was able to complete the concatenation operation in 3.56 seconds while Modin finished in 0.041 seconds, an 86.83X speedup! It appears that even though we only have 6 CPU cores, the partitioning of the DataFrame helps a lot with the speed. A Pandas function commonly used for DataFrame cleaning is the .fillna() function. This function finds all NaN values within a DataFrame and replaces them with the value of your choice. There’s a lot of operations going on there. Pandas has to go through every single row and column to find NaN values and replace them. This is a perfect opportunity to apply Modin since we’re repeating a very simple operation many times. This time, Pandas ran the .fillna() in 1.8 seconds while Modin took 0.21 seconds, an 8.57X speedup! So is Modin always this fast? Well, not always. There are some cases where Pandas is actually faster than Modin, even on this big dataset with 5,992,097 (almost 6 million) rows. The table below shows the run times of Pandas vs Modin for some experiments I ran. As you can see, there were some operations in which Modin was significantly faster, usually reading in data and finding values. Other operations such as performing statistical calculations were much faster in Pandas. Modin is still a fairly young library and is constantly being developed and expanded. As such, not all of the Pandas functions have been fully accelerated yet. If you try and use a function with Modin that is not yet accelerated, it will default to Pandas so there won’t be any code bugs or errors. For the full list of Pandas methods that are supported by Modin, see this page. By default, Modin will use all of the CPU cores available on your machine. There may be some cases where you wish to limit the number of CPU cores that Modin can use, especially if you want to use that computing power elsewhere. We can limit the number of CPU cores Modin has access to through an initialization setting in Ray, since Modin uses it on the backend. import rayray.init(num_cpus=4)import modin.pandas as pd When working with big data, it’s not uncommon for the size of the dataset to exceed the amount of memory (RAM) on your system. Modin has a specific flag that we can set to true which will enable its out of core mode. Out of core basically means that Modin will use your disk as an overflow storage for your memory, allowing you to work with datasets far bigger than your RAM size. We can set the following environment variable to enable this functionality: export MODIN_OUT_OF_CORE=true So there you have it! Your guide to accelerating Pandas functions using Modin. Very easy to do by changing just the import statement. Hopefully you find Modin useful in at least a few situations to accelerate your Pandas functions. Follow me on Twitter, where I post all about the latest and greatest AI, Technology, and Science! Stay connected with me on LinkedIn too!
[ { "code": null, "e": 232, "s": 171, "text": "Want to be inspired? Come join my Super Quotes newsletter. 😎" }, { "code": null, "e": 461, "s": 232, "text": "Pandas is the go-to library for processing data in Python. It’s easy to use and quite flexible when it comes to handling different types and sizes of data. It has tons of different functions that make manipulating data a breeze." }, { "code": null, "e": 524, "s": 461, "text": "But there is one drawback: Pandas is slow for larger datasets." }, { "code": null, "e": 945, "s": 524, "text": "By default, Pandas executes its functions as a single process using a single CPU core. That works just fine for smaller datasets since you might not notice much of a difference in speed. But with larger datasets, and so many more calculations to make, speed starts to take a major hit when using only a single core. It’s doing just one calculation at a time for a dataset that can have millions or even billions of rows." }, { "code": null, "e": 1343, "s": 945, "text": "Yet most modern machines made for Data Science have at least 2 CPU cores. That means, for the example of 2 CPU cores, that 50% or more of your computer’s processing power won’t be doing anything by default when using Pandas. The situation gets even worse when you get to 4 cores (modern Intel i5) or 6 cores (modern Intel i7). Pandas simply wasn’t designed to use that computing power effectively." }, { "code": null, "e": 1631, "s": 1343, "text": "Modin is a new library designed to accelerate Pandas by automatically distributing the computation across all of the system’s available CPU cores. With that, Modin claims to be able to get nearly linear speedup to the number of CPU cores on your system for Pandas DataFrames of any size." }, { "code": null, "e": 1694, "s": 1631, "text": "Let’s see how it all works and go through a few code examples." }, { "code": null, "e": 1999, "s": 1694, "text": "Given a DataFrame in Pandas, our goal is to perform some kind of calculation or process on it in the fastest way possible. That could be taking the mean of each column with .mean(), grouping data with groupby, dropping all duplicates with drop_duplicates(), or any of the other built-in Pandas functions." }, { "code": null, "e": 2207, "s": 1999, "text": "In the previous section, we mentioned how Pandas only uses one CPU core for processing. Naturally, this is a big bottleneck, especially for larger DataFrames where the lack of resources really shows through." }, { "code": null, "e": 2620, "s": 2207, "text": "In theory, parallelizing a calculation is as easy as applying that calculation on different data points across every available CPU core. For a Pandas DataFrame, a basic idea would be to divide up the DataFrame into a few pieces, as many pieces as you have CPU cores, and let each CPU core run the calculation on its own piece. In the end, we can aggregate the results, which is a computationally cheap operation." }, { "code": null, "e": 2901, "s": 2620, "text": "That’s exactly what Modin does. It slices your DataFrame into different parts such that each part can be sent to a different CPU core. Modin partitions the DataFrames across both the rows and the columns. This makes Modin’s parallel processing scalable to DataFrames of any shape." }, { "code": null, "e": 3321, "s": 2901, "text": "Imagine if you are given a DataFrame with many columns but fewer rows. Some libraries only perform the partitioning across rows, which would be inefficient in this case since we have more columns than rows. But with Modin, since the partitioning is done across both dimensions, the parallel processing remains efficient all shapes of DataFrames, whether they are wider (lots of columns), longer (lots of rows), or both." }, { "code": null, "e": 3716, "s": 3321, "text": "The figure above is a simple example. Modin actually uses a Partition Manager that can change the size and shape of the partitions based on the type of operation. For example, there might be an operation that requires entire rows or entire columns. In that case, the Partition Manager will perform the partitions and distribution to CPU cores in the most optimal way it can find. It’s flexible." }, { "code": null, "e": 4063, "s": 3716, "text": "To do a lot of the heavy lifting when it comes to executing the parallel processing, Modin can use either Dask or Ray. Both of them are parallel computing libraries with Python APIs and you can select one or the other to use with Modin at runtime. Ray will be the safest one to use for now as it is more stable — the Dask backend is experimental." }, { "code": null, "e": 4138, "s": 4063, "text": "But hey, that’s enough theory. Let’s get to the code and speed benchmarks!" }, { "code": null, "e": 4280, "s": 4138, "text": "The easiest way to install and get Modin working is via pip. The following command installs Modin, Ray, and all of the relevant dependencies:" }, { "code": null, "e": 4303, "s": 4280, "text": "pip install modin[ray]" }, { "code": null, "e": 4503, "s": 4303, "text": "For our following examples and benchmarks, we’re going to be using the CS:GO Competitive Matchmaking Data from Kaggle. Each row of the CSV contains data about a round in a competitive match of CS:GO." }, { "code": null, "e": 4830, "s": 4503, "text": "We’ll stick to experimenting with just the biggest CSV file for now (there are several) called esea_master_dmg_demos.part1.csv which is 1.2GB. With such a size, we should be able to see how Pandas slows down and how Modin can help us out. For the tests, I’ll be using an i7–8700k CPU which has 6 physical cores and 12 threads." }, { "code": null, "e": 4974, "s": 4830, "text": "The first test we’ll do is simply reading in the data with our good’ol read_csv(). The code itself is the exact same for both Pandas and Modin." }, { "code": null, "e": 5264, "s": 4974, "text": "To measure the speed, I imported the time module and put a time.time() before and after the read_csv(). As a result, Pandas took 8.38 seconds to load the data from CSV to memory while Modin took 3.22 seconds. That’s a speedup of 2.6X. Not too shabby for just changing the import statement!" }, { "code": null, "e": 5580, "s": 5264, "text": "Let’s do a couple of heavier processes on our DataFrame. Concatenating multiple DataFrames is a common operation in Pandas — we might have several or more CSV files containing our data which we then have to read one at a time and concatenate. We can easily do this with the pd.concat() function in Pandas and Modin." }, { "code": null, "e": 5706, "s": 5580, "text": "We’d expect that Modin should do well with this kind of operation since it’s handling a lot of data. The code is shown below." }, { "code": null, "e": 6020, "s": 5706, "text": "In the above code, we concatenated our DataFrame to itself 5 times. Pandas was able to complete the concatenation operation in 3.56 seconds while Modin finished in 0.041 seconds, an 86.83X speedup! It appears that even though we only have 6 CPU cores, the partitioning of the DataFrame helps a lot with the speed." }, { "code": null, "e": 6442, "s": 6020, "text": "A Pandas function commonly used for DataFrame cleaning is the .fillna() function. This function finds all NaN values within a DataFrame and replaces them with the value of your choice. There’s a lot of operations going on there. Pandas has to go through every single row and column to find NaN values and replace them. This is a perfect opportunity to apply Modin since we’re repeating a very simple operation many times." }, { "code": null, "e": 6542, "s": 6442, "text": "This time, Pandas ran the .fillna() in 1.8 seconds while Modin took 0.21 seconds, an 8.57X speedup!" }, { "code": null, "e": 6572, "s": 6542, "text": "So is Modin always this fast?" }, { "code": null, "e": 6590, "s": 6572, "text": "Well, not always." }, { "code": null, "e": 6803, "s": 6590, "text": "There are some cases where Pandas is actually faster than Modin, even on this big dataset with 5,992,097 (almost 6 million) rows. The table below shows the run times of Pandas vs Modin for some experiments I ran." }, { "code": null, "e": 7020, "s": 6803, "text": "As you can see, there were some operations in which Modin was significantly faster, usually reading in data and finding values. Other operations such as performing statistical calculations were much faster in Pandas." }, { "code": null, "e": 7399, "s": 7020, "text": "Modin is still a fairly young library and is constantly being developed and expanded. As such, not all of the Pandas functions have been fully accelerated yet. If you try and use a function with Modin that is not yet accelerated, it will default to Pandas so there won’t be any code bugs or errors. For the full list of Pandas methods that are supported by Modin, see this page." }, { "code": null, "e": 7763, "s": 7399, "text": "By default, Modin will use all of the CPU cores available on your machine. There may be some cases where you wish to limit the number of CPU cores that Modin can use, especially if you want to use that computing power elsewhere. We can limit the number of CPU cores Modin has access to through an initialization setting in Ray, since Modin uses it on the backend." }, { "code": null, "e": 7819, "s": 7763, "text": "import rayray.init(num_cpus=4)import modin.pandas as pd" }, { "code": null, "e": 8276, "s": 7819, "text": "When working with big data, it’s not uncommon for the size of the dataset to exceed the amount of memory (RAM) on your system. Modin has a specific flag that we can set to true which will enable its out of core mode. Out of core basically means that Modin will use your disk as an overflow storage for your memory, allowing you to work with datasets far bigger than your RAM size. We can set the following environment variable to enable this functionality:" }, { "code": null, "e": 8306, "s": 8276, "text": "export MODIN_OUT_OF_CORE=true" }, { "code": null, "e": 8538, "s": 8306, "text": "So there you have it! Your guide to accelerating Pandas functions using Modin. Very easy to do by changing just the import statement. Hopefully you find Modin useful in at least a few situations to accelerate your Pandas functions." } ]
CSS position: absolute;
The position: absolute; property allows you to position element relative to the nearest positioned ancestor. You can try to run the following code to implement CSS position: absolute; Live Demo <!DOCTYPE html> <html> <head> <style> div.one { position: relative; width: 500px; height: 150px; border: 2px solid blue; } div.two { position: absolute; top: 70px; right: 0; width: 300px; height: 50px; border: 2px solid yellow; } </style> </head> <body> <h2>position: absolute;</h2> The position: absolute; property allows you to position element relative to the nearest positioned ancestor. <div class = "one">div has position: relative; <div class = "two">div has position: absolute;</div> </div> </body> </html>
[ { "code": null, "e": 1171, "s": 1062, "text": "The position: absolute; property allows you to position element relative to the nearest positioned ancestor." }, { "code": null, "e": 1246, "s": 1171, "text": "You can try to run the following code to implement CSS position: absolute;" }, { "code": null, "e": 1256, "s": 1246, "text": "Live Demo" }, { "code": null, "e": 1982, "s": 1256, "text": "<!DOCTYPE html>\n<html>\n <head>\n <style>\n div.one {\n position: relative;\n width: 500px;\n height: 150px;\n border: 2px solid blue;\n }\n div.two {\n position: absolute;\n top: 70px;\n right: 0;\n width: 300px;\n height: 50px;\n border: 2px solid yellow;\n }\n </style>\n </head>\n <body>\n <h2>position: absolute;</h2>\n The position: absolute; property allows you to position element relative to the nearest positioned ancestor.\n <div class = \"one\">div has position: relative;\n <div class = \"two\">div has position: absolute;</div>\n </div>\n </body>\n</html>" } ]
How to Configure Nginx as Reverse Proxy for WebSocket
The WebSocket is a protocol which provides a way of creating web applications that supports real-time bi-directional communication between both clients and servers. WebSocket makes it much easier to develop these types of applications. Most modern browsers support WebSocket including Firefox, Internet Explorer, Chrome, Safari, and Opera, and more and more server application frameworks are now supporting WebSocket as well. For a production environment, where multiple WebSocket servers are needed for getting a good performance and high availability of the website or application, a load balancing layer which understands the WebSocket protocol is required, NGINX supports the use of WebSocket from NGINX version 1.3 and can act as a reverse proxy for doing load balancing of applications. NGINX supports WebSocket by allowing a tunnel to be set up between both client and back-end servers. NGINX will send the Upgrade request from the client to the back-end server, the Upgrade and Connection headers must be set explicitly. location /wsapp/ { proxy_pass http://wsbackend; proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection "upgrade"; } Once this is done, NGINX deals with this as a WebSocket connection. Here is a live example to show NGINX working as a WebSocket proxy. This example helps in WebSocket implementation built on Node.js. NGINX acts as a reverse proxy for a simple WebSocket application utilizing ws and Node.js. These instructions have been tested with Ubuntu 13.10 and CentOS 6.5 but which needs to be adjusted for other OSs and versions. For this example, the WebSocket server’s IP address is 192.168.1.1 and the NGINX server’s IP address is 192.168.1.2 If you don’t have Node.js and npm installed, then run the following command: # sudo yum install nodejs npm Node.js is installed as nodejs on Ubuntu and as node on CentOS. The example uses node, so on Ubuntu we need to create a symbolic link from nodejs to node: # ln -s /usr/bin/nodejs /usr/local/bin/node To install Websocket, run the following command: # sudo npm install ws Note: If you get an error message like: “Error: failed to fetch from registry: ws”, run the following command to fix the problem # sudo npm config set registry http://registry.npmjs.org/ Then run the sudo npm install command again # sudo npm install ws ‘ws’ comes with the program /root/node_modules/ws/bin/wscat that can be used for our client, but we need to create a program to act as the server. Create a file called a server.js with these contents console.log("Server started"); var Msg = ''; var WebSocketServer = require('ws').Server , wss = new WebSocketServer({port: 8010}); wss.on('connection', function(ws) { ws.on('message', function(message) { console.log('Received from client: %s', message); ws.send('Server received from client: ' + message); }); }); To execute the server program, run the following command: # node server.js The server prints an initial “Server started” message and then listens on port 8010, waiting for a client to connect to it. When it receives a client request, it echoes it and sends a message back to the client containing the message it received. To have NGINX proxy these requests, we create the following configuration http { map $http_upgrade $connection_upgrade { default upgrade; '' close; } upstream websocket { server 192.168.1.1:8010; } server { listen 8020; location / { proxy_pass http://websocket; proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection $connection_upgrade; } } } NGINX listens on port 8020 and proxy requests to the back-end WebSocket server. The proxy_set_header directives enable NGINX to properly handle the WebSocket protocol. To test the server, we run wscat in our client system # /root/node_modules/ws/bin/wscat --connect ws://192.168.1.2:8020 wscat connects to the WebSocket server through the NGINX proxy. When you type a message for wscat to send to the server, you see it echoed on the server and then a message from the server appears on the client. Here’s a sample interaction Server: Client: # node server.js Server started # wscat –connect ws://192.168.1.2:8020 Connected (press CTRL+C to quit) > Hello Received from client: Hello < Server received from client: Hello Here we see that the client and server are able to communicate through NGINX which is acting as a proxy server and messages can continue to be sent back until either the client or server disconnects. All that is needed to get NGINX configured properly to handle WebSocket, and set the headers correctly to handle the Upgrade request that upgrades the connection from HTTP to WebSocket.
[ { "code": null, "e": 1488, "s": 1062, "text": "The WebSocket is a protocol which provides a way of creating web applications that supports real-time bi-directional communication between both clients and servers. WebSocket makes it much easier to develop these types of applications. Most modern browsers support WebSocket including Firefox, Internet Explorer, Chrome, Safari, and Opera, and more and more server application frameworks are now supporting WebSocket as well." }, { "code": null, "e": 1855, "s": 1488, "text": "For a production environment, where multiple WebSocket servers are needed for getting a good performance and high availability of the website or application, a load balancing layer which understands the WebSocket protocol is required, NGINX supports the use of WebSocket from NGINX version 1.3 and can act as a reverse proxy for doing load balancing of applications." }, { "code": null, "e": 2091, "s": 1855, "text": "NGINX supports WebSocket by allowing a tunnel to be set up between both client and back-end servers. NGINX will send the Upgrade request from the client to the back-end server, the Upgrade and Connection headers must be set explicitly." }, { "code": null, "e": 2256, "s": 2091, "text": "location /wsapp/ {\n proxy_pass http://wsbackend;\n proxy_http_version 1.1;\n proxy_set_header Upgrade $http_upgrade;\n proxy_set_header Connection \"upgrade\";\n}" }, { "code": null, "e": 2324, "s": 2256, "text": "Once this is done, NGINX deals with this as a WebSocket connection." }, { "code": null, "e": 2791, "s": 2324, "text": "Here is a live example to show NGINX working as a WebSocket proxy. This example helps in WebSocket implementation built on Node.js. NGINX acts as a reverse proxy for a simple WebSocket application utilizing ws and Node.js. These instructions have been tested with Ubuntu 13.10 and CentOS 6.5 but which needs to be adjusted for other OSs and versions. For this example, the WebSocket server’s IP address is 192.168.1.1 and the NGINX server’s IP address is 192.168.1.2" }, { "code": null, "e": 2868, "s": 2791, "text": "If you don’t have Node.js and npm installed, then run the following command:" }, { "code": null, "e": 2898, "s": 2868, "text": "# sudo yum install nodejs npm" }, { "code": null, "e": 3053, "s": 2898, "text": "Node.js is installed as nodejs on Ubuntu and as node on CentOS. The example uses node, so on Ubuntu we need to create a symbolic link from nodejs to node:" }, { "code": null, "e": 3097, "s": 3053, "text": "# ln -s /usr/bin/nodejs /usr/local/bin/node" }, { "code": null, "e": 3146, "s": 3097, "text": "To install Websocket, run the following command:" }, { "code": null, "e": 3168, "s": 3146, "text": "# sudo npm install ws" }, { "code": null, "e": 3297, "s": 3168, "text": "Note: If you get an error message like: “Error: failed to fetch from registry: ws”, run the following command to fix the problem" }, { "code": null, "e": 3355, "s": 3297, "text": "# sudo npm config set registry http://registry.npmjs.org/" }, { "code": null, "e": 3399, "s": 3355, "text": "Then run the sudo\nnpm install command again" }, { "code": null, "e": 3421, "s": 3399, "text": "# sudo npm install ws" }, { "code": null, "e": 3621, "s": 3421, "text": "‘ws’ comes with the program /root/node_modules/ws/bin/wscat that can be used for our client, but we need to create a program to act as the server. Create a file called a server.js with these contents" }, { "code": null, "e": 3974, "s": 3621, "text": "console.log(\"Server started\");\nvar Msg = '';\nvar WebSocketServer = require('ws').Server\n , wss = new WebSocketServer({port: 8010});\n wss.on('connection', function(ws) {\n ws.on('message', function(message) {\n console.log('Received from client: %s', message);\n ws.send('Server received from client: ' + message);\n });\n });" }, { "code": null, "e": 4032, "s": 3974, "text": "To execute the server program, run the following command:" }, { "code": null, "e": 4049, "s": 4032, "text": "# node server.js" }, { "code": null, "e": 4370, "s": 4049, "text": "The server prints an initial “Server started” message and then listens on port 8010, waiting for a client to connect to it. When it receives a client request, it echoes it and sends a message back to the client containing the message it received. To have NGINX proxy these requests, we create the following configuration" }, { "code": null, "e": 4767, "s": 4370, "text": "http {\n map $http_upgrade $connection_upgrade {\n default upgrade;\n '' close;\n }\n upstream websocket {\n server 192.168.1.1:8010;\n }\n server {\n listen 8020;\n location / {\n proxy_pass http://websocket;\n proxy_http_version 1.1;\n proxy_set_header Upgrade $http_upgrade;\n proxy_set_header Connection $connection_upgrade;\n }\n }\n}" }, { "code": null, "e": 4935, "s": 4767, "text": "NGINX listens on port 8020 and proxy requests to the back-end WebSocket server. The proxy_set_header directives enable NGINX to properly handle the WebSocket protocol." }, { "code": null, "e": 4989, "s": 4935, "text": "To test the server, we run wscat in our client system" }, { "code": null, "e": 5055, "s": 4989, "text": "# /root/node_modules/ws/bin/wscat --connect ws://192.168.1.2:8020" }, { "code": null, "e": 5294, "s": 5055, "text": "wscat connects to the WebSocket server through the NGINX proxy. When you type a message for wscat to send to the server, you see it echoed on the server and then a message from the server appears on the client. Here’s a sample interaction" }, { "code": null, "e": 5310, "s": 5294, "text": "Server: Client:" }, { "code": null, "e": 5487, "s": 5310, "text": "# node server.js\nServer started\n# wscat –connect ws://192.168.1.2:8020\nConnected (press CTRL+C to quit)\n> Hello\nReceived from client: Hello\n< Server received from client: Hello" }, { "code": null, "e": 5873, "s": 5487, "text": "Here we see that the client and server are able to communicate through NGINX which is acting as a proxy server and messages can continue to be sent back until either the client or server disconnects. All that is needed to get NGINX configured properly to handle WebSocket, and set the headers correctly to handle the Upgrade request that upgrades the connection from HTTP to WebSocket." } ]
MATLAB - Scalar Operations of Matrices
When you add, subtract, multiply or divide a matrix by a number, this is called the scalar operation. Scalar operations produce a new matrix with same number of rows and columns with each element of the original matrix added to, subtracted from, multiplied by or divided by the number. Create a script file with the following code − a = [ 10 12 23 ; 14 8 6; 27 8 9]; b = 2; c = a + b d = a - b e = a * b f = a / b When you run the file, it displays the following result − c = 12 14 25 16 10 8 29 10 11 d = 8 10 21 12 6 4 25 6 7 e = 20 24 46 28 16 12 54 16 18 f = 5.0000 6.0000 11.5000 7.0000 4.0000 3.0000 13.5000 4.0000 4.5000 30 Lectures 4 hours Nouman Azam 127 Lectures 12 hours Nouman Azam 17 Lectures 3 hours Sanjeev 37 Lectures 5 hours TELCOMA Global 22 Lectures 4 hours TELCOMA Global 18 Lectures 3 hours Phinite Academy Print Add Notes Bookmark this page
[ { "code": null, "e": 2243, "s": 2141, "text": "When you add, subtract, multiply or divide a matrix by a number, this is called the scalar operation." }, { "code": null, "e": 2427, "s": 2243, "text": "Scalar operations produce a new matrix with same number of rows and columns with each element of the original matrix added to, subtracted from, multiplied by or divided by the number." }, { "code": null, "e": 2474, "s": 2427, "text": "Create a script file with the following code −" }, { "code": null, "e": 2555, "s": 2474, "text": "a = [ 10 12 23 ; 14 8 6; 27 8 9];\nb = 2;\nc = a + b\nd = a - b\ne = a * b\nf = a / b" }, { "code": null, "e": 2613, "s": 2555, "text": "When you run the file, it displays the following result −" }, { "code": null, "e": 2918, "s": 2613, "text": "c =\n 12 14 25\n 16 10 8\n 29 10 11\nd =\n 8 10 21\n 12 6 4\n 25 6 7\ne =\n 20 24 46\n 28 16 12\n 54 16 18\nf =\n 5.0000 6.0000 11.5000\n 7.0000 4.0000 3.0000\n 13.5000 4.0000 4.5000\n" }, { "code": null, "e": 2951, "s": 2918, "text": "\n 30 Lectures \n 4 hours \n" }, { "code": null, "e": 2964, "s": 2951, "text": " Nouman Azam" }, { "code": null, "e": 2999, "s": 2964, "text": "\n 127 Lectures \n 12 hours \n" }, { "code": null, "e": 3012, "s": 2999, "text": " Nouman Azam" }, { "code": null, "e": 3045, "s": 3012, "text": "\n 17 Lectures \n 3 hours \n" }, { "code": null, "e": 3054, "s": 3045, "text": " Sanjeev" }, { "code": null, "e": 3087, "s": 3054, "text": "\n 37 Lectures \n 5 hours \n" }, { "code": null, "e": 3103, "s": 3087, "text": " TELCOMA Global" }, { "code": null, "e": 3136, "s": 3103, "text": "\n 22 Lectures \n 4 hours \n" }, { "code": null, "e": 3152, "s": 3136, "text": " TELCOMA Global" }, { "code": null, "e": 3185, "s": 3152, "text": "\n 18 Lectures \n 3 hours \n" }, { "code": null, "e": 3202, "s": 3185, "text": " Phinite Academy" }, { "code": null, "e": 3209, "s": 3202, "text": " Print" }, { "code": null, "e": 3220, "s": 3209, "text": " Add Notes" } ]
QTP - Ordinal Identifiers
Sometimes, there are series of objects with same class name and properties. Let us say, in a window, there are series of checkboxes with the same set of properties. If we want to act on those objects, we need to uniquely identify them so that QTP will be able to act on it. An Ordinal Identifier assigns a numerical value to the test objects, which indicates its location or order relative to its group. The Ordered value enables QTP to recognize it uniquely when the inbuilt properties are NOT sufficient to do so. There are three Ordinal Identifiers in QTP that can be used in different context − Index Location Creation Time An object appearing first in the page/Window will have a smaller Index value when compared to another object that comes later in the same page/Window. The value of index for the group of text boxes will be as follows − The Location property works vertically from top to bottom and from left to right. Hence, for the same case, the value of location for the group of text boxes will be as follows − The Creation Time property holds good only for web based application. When we open two browser sessions of the same website, QTP will not be able to recognize the window, as both the windows will have the same set of properties. Hence, we can use creation time with which QTP will be able to act on the window. 'Will have CreationTime value = 0 SystemUtil.Run "iexplore.exe", "http://www.google.com" 'Will have CreationTime value = 1 SystemUtil.Run "iexplore.exe", "http://www.yahoo.com" 'Will have CreationTime value = 2 SystemUtil.Run "iexplore.exe", "http://www.microsoft.com" 'Will have CreationTime value = 3 SystemUtil.Run "iexplore.exe", "http://www.facebook.com" Hence, to work on a specific browser, we need to explicitly mention the Creation time in OR or we can use the description of objects, which we will see in detail in descriptive programming section. 'Sync's www.google.com Browser("creationtime:=" ).Sync 'Gets the RO text property of www.yahoo.com Browser("creationtime:=1").GetROProperty("text") 'Highlights microsoft.com Browser("creationtime:=2").Highlight 108 Lectures 8 hours Pavan Lalwani Print Add Notes Bookmark this page
[ { "code": null, "e": 2396, "s": 2122, "text": "Sometimes, there are series of objects with same class name and properties. Let us say, in a window, there are series of checkboxes with the same set of properties. If we want to act on those objects, we need to uniquely identify them so that QTP will be able to act on it." }, { "code": null, "e": 2638, "s": 2396, "text": "An Ordinal Identifier assigns a numerical value to the test objects, which indicates its location or order relative to its group. The Ordered value enables QTP to recognize it uniquely when the inbuilt properties are NOT sufficient to do so." }, { "code": null, "e": 2721, "s": 2638, "text": "There are three Ordinal Identifiers in QTP that can be used in different context −" }, { "code": null, "e": 2727, "s": 2721, "text": "Index" }, { "code": null, "e": 2736, "s": 2727, "text": "Location" }, { "code": null, "e": 2750, "s": 2736, "text": "Creation Time" }, { "code": null, "e": 2901, "s": 2750, "text": "An object appearing first in the page/Window will have a smaller Index value when compared to another object that comes later in the same page/Window." }, { "code": null, "e": 2969, "s": 2901, "text": "The value of index for the group of text boxes will be as follows −" }, { "code": null, "e": 3148, "s": 2969, "text": "The Location property works vertically from top to bottom and from left to right. Hence, for the same case, the value of location for the group of text boxes will be as follows −" }, { "code": null, "e": 3459, "s": 3148, "text": "The Creation Time property holds good only for web based application. When we open two browser sessions of the same website, QTP will not be able to recognize the window, as both the windows will have the same set of properties. Hence, we can use creation time with which QTP will be able to act on the window." }, { "code": null, "e": 3851, "s": 3459, "text": "'Will have CreationTime value = 0 \nSystemUtil.Run \"iexplore.exe\", \"http://www.google.com\" \n\n'Will have CreationTime value = 1 \nSystemUtil.Run \"iexplore.exe\", \"http://www.yahoo.com\" \n\n'Will have CreationTime value = 2 \nSystemUtil.Run \"iexplore.exe\", \"http://www.microsoft.com\" \n\n'Will have CreationTime value = 3 \nSystemUtil.Run \"iexplore.exe\", \"http://www.facebook.com\" " }, { "code": null, "e": 4049, "s": 3851, "text": "Hence, to work on a specific browser, we need to explicitly mention the Creation time in OR or we can use the description of objects, which we will see in detail in descriptive programming section." }, { "code": null, "e": 4304, "s": 4049, "text": "'Sync's www.google.com \nBrowser(\"creationtime:=\" ).Sync \n\n'Gets the RO text property of www.yahoo.com \nBrowser(\"creationtime:=1\").GetROProperty(\"text\") \n\n'Highlights microsoft.com \nBrowser(\"creationtime:=2\").Highlight " }, { "code": null, "e": 4338, "s": 4304, "text": "\n 108 Lectures \n 8 hours \n" }, { "code": null, "e": 4353, "s": 4338, "text": " Pavan Lalwani" }, { "code": null, "e": 4360, "s": 4353, "text": " Print" }, { "code": null, "e": 4371, "s": 4360, "text": " Add Notes" } ]
Left pad a String in Java with zeros
The following is our string − String str = "Tim"; Now take a StringBuilder object − StringBuilder strBuilder = new StringBuilder(); Perform left padding and extend the string length. We have set it till 20, that would include the current string as well. The zeros that will be padded comes on the left. Append the zeros here − while (strBuilder.length() + str.length() < 10) { strBuilder.append('0'); } The following is an example − Live Demo public class Demo { public static void main(String[] args) { String str = "Tim"; StringBuilder strBuilder = new StringBuilder(); while (strBuilder.length() + str.length() < 20) { strBuilder.append('0'); } // append strBuilder.append(str); String res = strBuilder.toString(); System.out.println(res); } } 0000000000000000Tim
[ { "code": null, "e": 1092, "s": 1062, "text": "The following is our string −" }, { "code": null, "e": 1112, "s": 1092, "text": "String str = \"Tim\";" }, { "code": null, "e": 1146, "s": 1112, "text": "Now take a StringBuilder object −" }, { "code": null, "e": 1194, "s": 1146, "text": "StringBuilder strBuilder = new StringBuilder();" }, { "code": null, "e": 1389, "s": 1194, "text": "Perform left padding and extend the string length. We have set it till 20, that would include the current string as well. The zeros that will be padded comes on the left. Append the zeros here −" }, { "code": null, "e": 1465, "s": 1389, "text": "while (strBuilder.length() + str.length() < 10) {\nstrBuilder.append('0');\n}" }, { "code": null, "e": 1495, "s": 1465, "text": "The following is an example −" }, { "code": null, "e": 1506, "s": 1495, "text": " Live Demo" }, { "code": null, "e": 1873, "s": 1506, "text": "public class Demo {\n public static void main(String[] args) {\n String str = \"Tim\";\n StringBuilder strBuilder = new StringBuilder();\n while (strBuilder.length() + str.length() < 20) {\n strBuilder.append('0');\n }\n // append\n strBuilder.append(str);\n String res = strBuilder.toString();\n System.out.println(res);\n }\n}" }, { "code": null, "e": 1893, "s": 1873, "text": "0000000000000000Tim" } ]
Function pointers in Java
From Java 8 onwards, the lambda expression is introduced which acts as function pointers. Lambda expressions are introduced in Java 8 and are touted to be the biggest feature of Java 8. Lambda expression facilitates functional programming and simplifies the development a lot. A lambda expression is characterized by the following syntax. parameter -> expression body Following are the important characteristics of a lambda expression. Optional type declaration − No need to declare the type of a parameter. The compiler can inference the same from the value of the parameter. Optional parenthesis around parameter − No need to declare a single parameter in parenthesis. For multiple parameters, parentheses are required. Optional curly braces − No need to use curly braces in expression body if the body contains a single statement. Optional return keyword − The compiler automatically returns the value if the body has a single expression to return the value. Curly braces are required to indicate that expression returns a value. Create the following Java program using any editor of your choice in, say, C:\> JAVA. Java8Tester.java Live Demo public class Java8Tester { public static void main(String args[]) { Java8Tester tester = new Java8Tester(); //with type declaration MathOperation addition = (int a, int b) -> a + b; //with out type declaration MathOperation subtraction = (a, b) -> a - b; //with return statement along with curly braces MathOperation multiplication = (int a, int b) -> { return a * b; }; //without return statement and without curly braces MathOperation division = (int a, int b) -> a / b; System.out.println("10 + 5 = " + tester.operate(10, 5, addition)); System.out.println("10 - 5 = " + tester.operate(10, 5, subtraction)); System.out.println("10 x 5 = " + tester.operate(10, 5, multiplication)); System.out.println("10 / 5 = " + tester.operate(10, 5, division)); //without parenthesis GreetingService greetService1 = message -> System.out.println("Hello " + message); //with parenthesis GreetingService greetService2 = (message) -> System.out.println("Hello " + message); greetService1.sayMessage("Mahesh"); greetService2.sayMessage("Suresh"); } interface MathOperation { int operation(int a, int b); } interface GreetingService { void sayMessage(String message); } private int operate(int a, int b, MathOperation mathOperation) { return mathOperation.operation(a, b); } } Compile the class using javac compiler as follows − C:\JAVA>javac Java8Tester.java Now run the Java8Tester as follows − C:\JAVA>java Java8Tester It should produce the following output − 10 + 5 = 15 10 - 5 = 5 10 x 5 = 50 10 / 5 = 2 Hello Mahesh Hello Suresh
[ { "code": null, "e": 1152, "s": 1062, "text": "From Java 8 onwards, the lambda expression is introduced which acts as function pointers." }, { "code": null, "e": 1339, "s": 1152, "text": "Lambda expressions are introduced in Java 8 and are touted to be the biggest feature of Java 8. Lambda expression facilitates functional programming and simplifies the development a lot." }, { "code": null, "e": 1401, "s": 1339, "text": "A lambda expression is characterized by the following syntax." }, { "code": null, "e": 1430, "s": 1401, "text": "parameter -> expression body" }, { "code": null, "e": 1498, "s": 1430, "text": "Following are the important characteristics of a lambda expression." }, { "code": null, "e": 1639, "s": 1498, "text": "Optional type declaration − No need to declare the type of a parameter. The compiler can inference the same from the value of the parameter." }, { "code": null, "e": 1784, "s": 1639, "text": "Optional parenthesis around parameter − No need to declare a single parameter in parenthesis. For multiple parameters, parentheses are required." }, { "code": null, "e": 1896, "s": 1784, "text": "Optional curly braces − No need to use curly braces in expression body if the body contains a single statement." }, { "code": null, "e": 2095, "s": 1896, "text": "Optional return keyword − The compiler automatically returns the value if the body has a single expression to return the value. Curly braces are required to indicate that expression returns a value." }, { "code": null, "e": 2181, "s": 2095, "text": "Create the following Java program using any editor of your choice in, say, C:\\> JAVA." }, { "code": null, "e": 2198, "s": 2181, "text": "Java8Tester.java" }, { "code": null, "e": 2208, "s": 2198, "text": "Live Demo" }, { "code": null, "e": 3645, "s": 2208, "text": "public class Java8Tester {\n public static void main(String args[]) {\n Java8Tester tester = new Java8Tester();\n //with type declaration MathOperation addition = (int a, int b) -> a + b;\n //with out type declaration MathOperation subtraction = (a, b) -> a - b;\n //with return statement along with curly braces MathOperation multiplication =\n (int a, int b) -> { return a * b; };\n //without return statement and without curly braces MathOperation division =\n (int a, int b) -> a / b;\n System.out.println(\"10 + 5 = \" + tester.operate(10, 5, addition));\n System.out.println(\"10 - 5 = \" + tester.operate(10, 5, subtraction));\n System.out.println(\"10 x 5 = \" + tester.operate(10, 5, multiplication));\n System.out.println(\"10 / 5 = \" + tester.operate(10, 5, division));\n //without parenthesis GreetingService greetService1 = message ->\n System.out.println(\"Hello \" + message);\n //with parenthesis GreetingService greetService2 = (message) ->\n System.out.println(\"Hello \" + message);\n greetService1.sayMessage(\"Mahesh\");\n greetService2.sayMessage(\"Suresh\");\n }\n\n interface MathOperation {\n int operation(int a, int b);\n }\n\n interface GreetingService {\n void sayMessage(String message);\n }\n\n private int operate(int a, int b, MathOperation mathOperation) {\n return mathOperation.operation(a, b);\n }\n}" }, { "code": null, "e": 3698, "s": 3645, "text": "Compile the class using javac compiler as follows − " }, { "code": null, "e": 3729, "s": 3698, "text": "C:\\JAVA>javac Java8Tester.java" }, { "code": null, "e": 3767, "s": 3729, "text": "Now run the Java8Tester as follows − " }, { "code": null, "e": 3792, "s": 3767, "text": "C:\\JAVA>java Java8Tester" }, { "code": null, "e": 3834, "s": 3792, "text": "It should produce the following output − " }, { "code": null, "e": 3906, "s": 3834, "text": "10 + 5 = 15\n10 - 5 = 5\n10 x 5 = 50\n10 / 5 = 2\nHello Mahesh\nHello Suresh" } ]
C++ Pointer Arithmetic
As you understood pointer is an address which is a numeric value; therefore, you can perform arithmetic operations on a pointer just as you can a numeric value. There are four arithmetic operators that can be used on pointers: ++, --, +, and - To understand pointer arithmetic, let us consider that ptr is an integer pointer which points to the address 1000. Assuming 32-bit integers, let us perform the following arithmetic operation on the pointer − ptr++ the ptr will point to the location 1004 because each time ptr is incremented, it will point to the next integer. This operation will move the pointer to next memory location without impacting actual value at the memory location. If ptr points to a character whose address is 1000, then above operation will point to the location 1001 because next character will be available at 1001. We prefer using a pointer in our program instead of an array because the variable pointer can be incremented, unlike the array name which cannot be incremented because it is a constant pointer. The following program increments the variable pointer to access each succeeding element of the array − #include <iostream> using namespace std; const int MAX = 3; int main () { int var[MAX] = {10, 100, 200}; int *ptr; // let us have array address in pointer. ptr = var; for (int i = 0; i < MAX; i++) { cout << "Address of var[" << i << "] = "; cout << ptr << endl; cout << "Value of var[" << i << "] = "; cout << *ptr << endl; // point to the next location ptr++; } return 0; } When the above code is compiled and executed, it produces result something as follows − Address of var[0] = 0xbfa088b0 Value of var[0] = 10 Address of var[1] = 0xbfa088b4 Value of var[1] = 100 Address of var[2] = 0xbfa088b8 Value of var[2] = 200 The same considerations apply to decrementing a pointer, which decreases its value by the number of bytes of its data type as shown below − #include <iostream> using namespace std; const int MAX = 3; int main () { int var[MAX] = {10, 100, 200}; int *ptr; // let us have address of the last element in pointer. ptr = &var[MAX-1]; for (int i = MAX; i > 0; i--) { cout << "Address of var[" << i << "] = "; cout << ptr << endl; cout << "Value of var[" << i << "] = "; cout << *ptr << endl; // point to the previous location ptr--; } return 0; } When the above code is compiled and executed, it produces result something as follows − Address of var[3] = 0xbfdb70f8 Value of var[3] = 200 Address of var[2] = 0xbfdb70f4 Value of var[2] = 100 Address of var[1] = 0xbfdb70f0 Value of var[1] = 10 Pointers may be compared by using relational operators, such as ==, <, and >. If p1 and p2 point to variables that are related to each other, such as elements of the same array, then p1 and p2 can be meaningfully compared. The following program modifies the previous example one by incrementing the variable pointer so long as the address to which it points is either less than or equal to the address of the last element of the array, which is &var[MAX - 1] − #include <iostream> using namespace std; const int MAX = 3; int main () { int var[MAX] = {10, 100, 200}; int *ptr; // let us have address of the first element in pointer. ptr = var; int i = 0; while ( ptr <= &var[MAX - 1] ) { cout << "Address of var[" << i << "] = "; cout << ptr << endl; cout << "Value of var[" << i << "] = "; cout << *ptr << endl; // point to the previous location ptr++; i++; } return 0; } When the above code is compiled and executed, it produces result something as follows − Address of var[0] = 0xbfce42d0 Value of var[0] = 10 Address of var[1] = 0xbfce42d4 Value of var[1] = 100 Address of var[2] = 0xbfce42d8 Value of var[2] = 200 154 Lectures 11.5 hours Arnab Chakraborty 14 Lectures 57 mins Kaushik Roy Chowdhury 30 Lectures 12.5 hours Frahaan Hussain 54 Lectures 3.5 hours Frahaan Hussain 77 Lectures 5.5 hours Frahaan Hussain 12 Lectures 3.5 hours Frahaan Hussain Print Add Notes Bookmark this page
[ { "code": null, "e": 2562, "s": 2318, "text": "As you understood pointer is an address which is a numeric value; therefore, you can perform arithmetic operations on a pointer just as you can a numeric value. There are four arithmetic operators that can be used on pointers: ++, --, +, and -" }, { "code": null, "e": 2770, "s": 2562, "text": "To understand pointer arithmetic, let us consider that ptr is an integer pointer which points to the address 1000. Assuming 32-bit integers, let us perform the following arithmetic operation on the pointer −" }, { "code": null, "e": 2777, "s": 2770, "text": "ptr++\n" }, { "code": null, "e": 3161, "s": 2777, "text": "the ptr will point to the location 1004 because each time ptr is incremented, it will point to the next integer. This operation will move the pointer to next memory location without impacting actual value at the memory location. If ptr points to a character whose address is 1000, then above operation will point to the location 1001 because next character will be available at 1001." }, { "code": null, "e": 3458, "s": 3161, "text": "We prefer using a pointer in our program instead of an array because the variable pointer can be incremented, unlike the array name which cannot be incremented because it is a constant pointer. The following program increments the variable pointer to access each succeeding element of the array −" }, { "code": null, "e": 3905, "s": 3458, "text": "#include <iostream>\n\nusing namespace std;\nconst int MAX = 3;\n\nint main () {\n int var[MAX] = {10, 100, 200};\n int *ptr;\n\n // let us have array address in pointer.\n ptr = var;\n \n for (int i = 0; i < MAX; i++) {\n cout << \"Address of var[\" << i << \"] = \";\n cout << ptr << endl;\n\n cout << \"Value of var[\" << i << \"] = \";\n cout << *ptr << endl;\n\n // point to the next location\n ptr++;\n }\n \n return 0;\n}" }, { "code": null, "e": 3993, "s": 3905, "text": "When the above code is compiled and executed, it produces result something as follows −" }, { "code": null, "e": 4152, "s": 3993, "text": "Address of var[0] = 0xbfa088b0\nValue of var[0] = 10\nAddress of var[1] = 0xbfa088b4\nValue of var[1] = 100\nAddress of var[2] = 0xbfa088b8\nValue of var[2] = 200\n" }, { "code": null, "e": 4292, "s": 4152, "text": "The same considerations apply to decrementing a pointer, which decreases its value by the number of bytes of its data type as shown below −" }, { "code": null, "e": 4765, "s": 4292, "text": "#include <iostream>\n\nusing namespace std;\nconst int MAX = 3;\n\nint main () {\n int var[MAX] = {10, 100, 200};\n int *ptr;\n\n // let us have address of the last element in pointer.\n ptr = &var[MAX-1];\n \n for (int i = MAX; i > 0; i--) {\n cout << \"Address of var[\" << i << \"] = \";\n cout << ptr << endl;\n\n cout << \"Value of var[\" << i << \"] = \";\n cout << *ptr << endl;\n\n // point to the previous location\n ptr--;\n }\n \n return 0;\n}" }, { "code": null, "e": 4853, "s": 4765, "text": "When the above code is compiled and executed, it produces result something as follows −" }, { "code": null, "e": 5012, "s": 4853, "text": "Address of var[3] = 0xbfdb70f8\nValue of var[3] = 200\nAddress of var[2] = 0xbfdb70f4\nValue of var[2] = 100\nAddress of var[1] = 0xbfdb70f0\nValue of var[1] = 10\n" }, { "code": null, "e": 5235, "s": 5012, "text": "Pointers may be compared by using relational operators, such as ==, <, and >. If p1 and p2 point to variables that are related to each other, such as elements of the same array, then p1 and p2 can be meaningfully compared." }, { "code": null, "e": 5473, "s": 5235, "text": "The following program modifies the previous example one by incrementing the variable pointer so long as the address to which it points is either less than or equal to the address of the last element of the array, which is &var[MAX - 1] −" }, { "code": null, "e": 5965, "s": 5473, "text": "#include <iostream>\n\nusing namespace std;\nconst int MAX = 3;\n\nint main () {\n int var[MAX] = {10, 100, 200};\n int *ptr;\n\n // let us have address of the first element in pointer.\n ptr = var;\n int i = 0;\n \n while ( ptr <= &var[MAX - 1] ) {\n cout << \"Address of var[\" << i << \"] = \";\n cout << ptr << endl;\n\n cout << \"Value of var[\" << i << \"] = \";\n cout << *ptr << endl;\n\n // point to the previous location\n ptr++;\n i++;\n }\n \n return 0;\n}" }, { "code": null, "e": 6053, "s": 5965, "text": "When the above code is compiled and executed, it produces result something as follows −" }, { "code": null, "e": 6212, "s": 6053, "text": "Address of var[0] = 0xbfce42d0\nValue of var[0] = 10\nAddress of var[1] = 0xbfce42d4\nValue of var[1] = 100\nAddress of var[2] = 0xbfce42d8\nValue of var[2] = 200\n" }, { "code": null, "e": 6249, "s": 6212, "text": "\n 154 Lectures \n 11.5 hours \n" }, { "code": null, "e": 6268, "s": 6249, "text": " Arnab Chakraborty" }, { "code": null, "e": 6300, "s": 6268, "text": "\n 14 Lectures \n 57 mins\n" }, { "code": null, "e": 6323, "s": 6300, "text": " Kaushik Roy Chowdhury" }, { "code": null, "e": 6359, "s": 6323, "text": "\n 30 Lectures \n 12.5 hours \n" }, { "code": null, "e": 6376, "s": 6359, "text": " Frahaan Hussain" }, { "code": null, "e": 6411, "s": 6376, "text": "\n 54 Lectures \n 3.5 hours \n" }, { "code": null, "e": 6428, "s": 6411, "text": " Frahaan Hussain" }, { "code": null, "e": 6463, "s": 6428, "text": "\n 77 Lectures \n 5.5 hours \n" }, { "code": null, "e": 6480, "s": 6463, "text": " Frahaan Hussain" }, { "code": null, "e": 6515, "s": 6480, "text": "\n 12 Lectures \n 3.5 hours \n" }, { "code": null, "e": 6532, "s": 6515, "text": " Frahaan Hussain" }, { "code": null, "e": 6539, "s": 6532, "text": " Print" }, { "code": null, "e": 6550, "s": 6539, "text": " Add Notes" } ]
How to Add Markers to a Graph Plot in Matplotlib with Python?
16 Nov, 2020 Prerequisite: Matplotlib In this article we will learn how to add markers to a Graph Plot in Matplotlib with Python. For that just see some concepts that we will use in our work. Matplotlib : Matplotlib is a tremendous visualization library in Python for 2D plots of arrays. Matplotlib may be a multi-platform data visualization library built on NumPy arrays and designed to figure with the broader SciPy stack. It was introduced by John Hunter within the year 2002. Graph Plot : A plot is a graphical technique for representing a data set, usually as a graph showing the relationship between two or more variables. Markers : The markers are shown in graph with different shapes and color to modify the meaning of graph. To generate a graph with a modified marker style, following steps need to be followed: Import packagesImport or create some dataDraw a graph plot.Set the marker by using marker feature. Import packages Import or create some data Draw a graph plot. Set the marker by using marker feature. Example 1: Python3 # importing packagesimport matplotlib.pyplot as plt # plot with markerplt.plot([2, 8, 7, 4, 7, 6, 2, 5, 9], marker='D')plt.show() Output : Example 2 : Python3 # importing packagesimport matplotlib.pyplot as plt # create datat = np.arange(0., 5., 0.2) # plot with markerplt.plot(t, t, 'r--', t, t**2, 'bs', t, t**3, 'g^')plt.show() Output : Example 3 : Python3 # importing packagesimport matplotlib.pyplot as pltimport numpy as np # create datax_values = np.linspace(0, 10, 20)y_values = np.sin(x_values)markers = ['>', '+', '.', ',', 'o', 'v', 'x', 'X', 'D', '|'] # apply markersfor i in range(20): plt.plot(x_values, y_values + i*0.2, markers[i % 10])plt.show() Output : Python-matplotlib Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Python Classes and Objects Python OOPs Concepts Introduction To PYTHON Python | os.path.join() method How to drop one or multiple columns in Pandas Dataframe How To Convert Python Dictionary To JSON? Check if element exists in list in Python Python | Get unique values from a list Python | datetime.timedelta() function
[ { "code": null, "e": 28, "s": 0, "text": "\n16 Nov, 2020" }, { "code": null, "e": 54, "s": 28, "text": "Prerequisite: Matplotlib " }, { "code": null, "e": 208, "s": 54, "text": "In this article we will learn how to add markers to a Graph Plot in Matplotlib with Python. For that just see some concepts that we will use in our work." }, { "code": null, "e": 496, "s": 208, "text": "Matplotlib : Matplotlib is a tremendous visualization library in Python for 2D plots of arrays. Matplotlib may be a multi-platform data visualization library built on NumPy arrays and designed to figure with the broader SciPy stack. It was introduced by John Hunter within the year 2002." }, { "code": null, "e": 645, "s": 496, "text": "Graph Plot : A plot is a graphical technique for representing a data set, usually as a graph showing the relationship between two or more variables." }, { "code": null, "e": 750, "s": 645, "text": "Markers : The markers are shown in graph with different shapes and color to modify the meaning of graph." }, { "code": null, "e": 837, "s": 750, "text": "To generate a graph with a modified marker style, following steps need to be followed:" }, { "code": null, "e": 936, "s": 837, "text": "Import packagesImport or create some dataDraw a graph plot.Set the marker by using marker feature." }, { "code": null, "e": 952, "s": 936, "text": "Import packages" }, { "code": null, "e": 979, "s": 952, "text": "Import or create some data" }, { "code": null, "e": 998, "s": 979, "text": "Draw a graph plot." }, { "code": null, "e": 1038, "s": 998, "text": "Set the marker by using marker feature." }, { "code": null, "e": 1049, "s": 1038, "text": "Example 1:" }, { "code": null, "e": 1057, "s": 1049, "text": "Python3" }, { "code": "# importing packagesimport matplotlib.pyplot as plt # plot with markerplt.plot([2, 8, 7, 4, 7, 6, 2, 5, 9], marker='D')plt.show()", "e": 1188, "s": 1057, "text": null }, { "code": null, "e": 1197, "s": 1188, "text": "Output :" }, { "code": null, "e": 1209, "s": 1197, "text": "Example 2 :" }, { "code": null, "e": 1217, "s": 1209, "text": "Python3" }, { "code": "# importing packagesimport matplotlib.pyplot as plt # create datat = np.arange(0., 5., 0.2) # plot with markerplt.plot(t, t, 'r--', t, t**2, 'bs', t, t**3, 'g^')plt.show()", "e": 1391, "s": 1217, "text": null }, { "code": null, "e": 1400, "s": 1391, "text": "Output :" }, { "code": null, "e": 1412, "s": 1400, "text": "Example 3 :" }, { "code": null, "e": 1420, "s": 1412, "text": "Python3" }, { "code": "# importing packagesimport matplotlib.pyplot as pltimport numpy as np # create datax_values = np.linspace(0, 10, 20)y_values = np.sin(x_values)markers = ['>', '+', '.', ',', 'o', 'v', 'x', 'X', 'D', '|'] # apply markersfor i in range(20): plt.plot(x_values, y_values + i*0.2, markers[i % 10])plt.show()", "e": 1728, "s": 1420, "text": null }, { "code": null, "e": 1737, "s": 1728, "text": "Output :" }, { "code": null, "e": 1755, "s": 1737, "text": "Python-matplotlib" }, { "code": null, "e": 1762, "s": 1755, "text": "Python" }, { "code": null, "e": 1860, "s": 1762, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1892, "s": 1860, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 1919, "s": 1892, "text": "Python Classes and Objects" }, { "code": null, "e": 1940, "s": 1919, "text": "Python OOPs Concepts" }, { "code": null, "e": 1963, "s": 1940, "text": "Introduction To PYTHON" }, { "code": null, "e": 1994, "s": 1963, "text": "Python | os.path.join() method" }, { "code": null, "e": 2050, "s": 1994, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 2092, "s": 2050, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 2134, "s": 2092, "text": "Check if element exists in list in Python" }, { "code": null, "e": 2173, "s": 2134, "text": "Python | Get unique values from a list" } ]
turtle.ycor() function in Python
21 Jul, 2020 The turtle module provides turtle graphics primitives, in both object-oriented and procedure-oriented ways. Because it uses Tkinter for the underlying graphics, it needs a version of Python installed with Tk support. This function is used to return the turtle’s y coordinate of the current position of turtle. It doesn’t require any argument. Syntax : turtle.ycor() Below is the implementation of the above method with an example : Example : Python3 # import packageimport turtle # check y coordinateprint(turtle.ycor())turtle.forward(100) # check y coordinateprint(turtle.ycor())turtle.right(45)turtle.forward(100) # check y coordinateprint(turtle.ycor())turtle.right(90)turtle.forward(100) # check y coordinateprint(turtle.ycor())turtle.right(45)turtle.forward(100) # check y coordinateprint(turtle.ycor()) Output : 0.0 0.0 -70.7106781187 -141.421356237 -141.421356237 Python-turtle Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n21 Jul, 2020" }, { "code": null, "e": 245, "s": 28, "text": "The turtle module provides turtle graphics primitives, in both object-oriented and procedure-oriented ways. Because it uses Tkinter for the underlying graphics, it needs a version of Python installed with Tk support." }, { "code": null, "e": 371, "s": 245, "text": "This function is used to return the turtle’s y coordinate of the current position of turtle. It doesn’t require any argument." }, { "code": null, "e": 380, "s": 371, "text": "Syntax :" }, { "code": null, "e": 395, "s": 380, "text": "turtle.ycor()\n" }, { "code": null, "e": 461, "s": 395, "text": "Below is the implementation of the above method with an example :" }, { "code": null, "e": 471, "s": 461, "text": "Example :" }, { "code": null, "e": 479, "s": 471, "text": "Python3" }, { "code": "# import packageimport turtle # check y coordinateprint(turtle.ycor())turtle.forward(100) # check y coordinateprint(turtle.ycor())turtle.right(45)turtle.forward(100) # check y coordinateprint(turtle.ycor())turtle.right(90)turtle.forward(100) # check y coordinateprint(turtle.ycor())turtle.right(45)turtle.forward(100) # check y coordinateprint(turtle.ycor())", "e": 845, "s": 479, "text": null }, { "code": null, "e": 854, "s": 845, "text": "Output :" }, { "code": null, "e": 908, "s": 854, "text": "0.0\n0.0\n-70.7106781187\n-141.421356237\n-141.421356237\n" }, { "code": null, "e": 922, "s": 908, "text": "Python-turtle" }, { "code": null, "e": 929, "s": 922, "text": "Python" } ]
Ruby | String hex Method
09 Dec, 2019 hex is a String class method in Ruby which is used to treats the leading characters from the given string as a string of hexadecimal digits (with an optional sign and an optional 0x) and returns the corresponding number. Zero is returned on error. Syntax: str.hex Parameters: Here, str is the given string. Returns: A corresponding number. Example 1: # Ruby program to demonstrate # the hex method # Taking a string and # using the methodputs "123678".hex puts "Ruby".hex Output: 1193592 0 Example 2: # Ruby program to demonstrate # the hex method # Taking a string and # using the methodputs "-87673".hex puts "0x876adc".hex Output: -554611 8874716 Ruby String-class Ruby-Methods Ruby Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n09 Dec, 2019" }, { "code": null, "e": 276, "s": 28, "text": "hex is a String class method in Ruby which is used to treats the leading characters from the given string as a string of hexadecimal digits (with an optional sign and an optional 0x) and returns the corresponding number. Zero is returned on error." }, { "code": null, "e": 292, "s": 276, "text": "Syntax: str.hex" }, { "code": null, "e": 335, "s": 292, "text": "Parameters: Here, str is the given string." }, { "code": null, "e": 368, "s": 335, "text": "Returns: A corresponding number." }, { "code": null, "e": 379, "s": 368, "text": "Example 1:" }, { "code": "# Ruby program to demonstrate # the hex method # Taking a string and # using the methodputs \"123678\".hex puts \"Ruby\".hex", "e": 522, "s": 379, "text": null }, { "code": null, "e": 530, "s": 522, "text": "Output:" }, { "code": null, "e": 541, "s": 530, "text": "1193592\n0\n" }, { "code": null, "e": 552, "s": 541, "text": "Example 2:" }, { "code": "# Ruby program to demonstrate # the hex method # Taking a string and # using the methodputs \"-87673\".hex puts \"0x876adc\".hex", "e": 699, "s": 552, "text": null }, { "code": null, "e": 707, "s": 699, "text": "Output:" }, { "code": null, "e": 724, "s": 707, "text": "-554611\n8874716\n" }, { "code": null, "e": 742, "s": 724, "text": "Ruby String-class" }, { "code": null, "e": 755, "s": 742, "text": "Ruby-Methods" }, { "code": null, "e": 760, "s": 755, "text": "Ruby" } ]
Height Checker in Python
Suppose a set of students have to be arranged in non-decreasing order of their heights for a photograph. If we have an array of students, we have to return the minimum number of students that are not present in correct position. So if the array is like [1, 1, 4, 2, 1, 3], then output will be 3. So students with height 4, 3 and the last 1 are not standing in the correct position. To solve this, we will follow these steps − answer := 0 let x := Array in sorted form ley y := Array for i := 0 to size of Array – 1 −if x[i] is not same as y[i], then increase answer by 1 if x[i] is not same as y[i], then increase answer by 1 return answer Let us see the following implementation to get better understanding − Live Demo class Solution(object): def heightChecker(self, heights): ans = 0 x = sorted(heights) y = heights for i in range(len(x)): if x[i]!=y[i]: ans+=1 return ans ob1 = Solution() print(ob1.heightChecker([1,2,4,2,1,3])) [1,1,4,2,1,3] 4
[ { "code": null, "e": 1444, "s": 1062, "text": "Suppose a set of students have to be arranged in non-decreasing order of their heights for a photograph. If we have an array of students, we have to return the minimum number of students that are not present in correct position. So if the array is like [1, 1, 4, 2, 1, 3], then output will be 3. So students with height 4, 3 and the last 1 are not standing in the correct position." }, { "code": null, "e": 1488, "s": 1444, "text": "To solve this, we will follow these steps −" }, { "code": null, "e": 1500, "s": 1488, "text": "answer := 0" }, { "code": null, "e": 1530, "s": 1500, "text": "let x := Array in sorted form" }, { "code": null, "e": 1545, "s": 1530, "text": "ley y := Array" }, { "code": null, "e": 1633, "s": 1545, "text": "for i := 0 to size of Array – 1 −if x[i] is not same as y[i], then increase answer by 1" }, { "code": null, "e": 1688, "s": 1633, "text": "if x[i] is not same as y[i], then increase answer by 1" }, { "code": null, "e": 1702, "s": 1688, "text": "return answer" }, { "code": null, "e": 1772, "s": 1702, "text": "Let us see the following implementation to get better understanding −" }, { "code": null, "e": 1783, "s": 1772, "text": " Live Demo" }, { "code": null, "e": 2049, "s": 1783, "text": "class Solution(object):\n def heightChecker(self, heights):\n ans = 0\n x = sorted(heights)\n y = heights\n for i in range(len(x)):\n if x[i]!=y[i]:\n ans+=1\n return ans\nob1 = Solution()\nprint(ob1.heightChecker([1,2,4,2,1,3]))" }, { "code": null, "e": 2063, "s": 2049, "text": "[1,1,4,2,1,3]" }, { "code": null, "e": 2065, "s": 2063, "text": "4" } ]
Bootstrap table-striped class
To implement the table-striped class in Bootstrap, you can try to run the following code: Live Demo <!DOCTYPE html> <html> <head> <title>Bootstrap Table</title> <meta name ="viewport" content = "width = device-width, initial-scale = 1"> <link rel = "stylesheet" href = "https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css"> <script src = "https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <script src = "https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/js/bootstrap.min.js"></script> </head> <body> <table class = "table table-striped"> <caption>Footballer Rank</caption> <thead> <tr> <th>Footballer</th> <th>Rank</th> <th>Country</th> </tr> </thead> </table> </body> </html>
[ { "code": null, "e": 1152, "s": 1062, "text": "To implement the table-striped class in Bootstrap, you can try to run the following code:" }, { "code": null, "e": 1162, "s": 1152, "text": "Live Demo" }, { "code": null, "e": 1937, "s": 1162, "text": "<!DOCTYPE html>\n<html>\n <head>\n <title>Bootstrap Table</title>\n <meta name =\"viewport\" content = \"width = device-width, initial-scale = 1\">\n <link rel = \"stylesheet\" href = \"https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css\">\n <script src = \"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js\"></script>\n <script src = \"https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/js/bootstrap.min.js\"></script>\n </head>\n <body>\n <table class = \"table table-striped\">\n <caption>Footballer Rank</caption>\n <thead>\n <tr>\n <th>Footballer</th>\n <th>Rank</th>\n <th>Country</th>\n </tr>\n </thead>\n </table>\n </body>\n</html>" } ]
C# | Finding the index of last element in the array - GeeksforGeeks
01 Feb, 2019 GetUpperBound() Method is used to find the index of the last element of the specified dimension in the array. Syntax: public int GetUpperBound (int dimension); Here, dimension is a zero-based dimension of the array whose upper bound needs to be determined. Return Value:The return type of this method is System.Int32. This method returns the index of the last element of the specified dimension in the array Or -1 if the specified dimension is empty. Exception: This method will give IndexOutOfRangeException if the value of dimension is less than zero, or equal or greater than Rank. Note: GetUpperBound(0) returns the last index in the first dimension of the array, and GetUpperBound(Rank – 1) returns the last index of the last dimension of the array. This method is an O(1) operation. Below programs illustrate the use of GetUpperBound() Method: Example 1: // C# program to illustrate the GetUpperBound(Int32)// method in 1-D arrayusing System; public class GFG { // Main method static public void Main() { // 1-D Array int[] value = {1, 2, 3, 4, 5, 6, 7}; // Get the index of the last element // in the given Array by using // GetUpperBound(Int32) method int myvalue = value.GetUpperBound(0); Console.WriteLine("Index: {0}", myvalue); }} Index: 6 Example 2: // C# program to find last index // value and rank of 2-D arrayusing System; public class GFG { // Main method static public void Main() { // 2-D char Array char[, ] value = { { 'a', 'b' }, { 'c', 'd' }, { 'e', 'f' }, { 'g', 'h' }, { 'i', 'j' } }; // Get the index of the last element // and the rank of the given Array int myvalue = value.GetUpperBound(0); Console.WriteLine("Dimension: {0}", value.Rank); Console.WriteLine("Index: {0}", myvalue); }} Dimension: 2 Index: 4 Reference: https://docs.microsoft.com/en-us/dotnet/api/system.array.getupperbound?view=netcore-2.1 CSharp-Arrays CSharp-method C# Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments C# | Method Overriding C# Dictionary with examples Difference between Ref and Out keywords in C# C# | Delegates Top 50 C# Interview Questions & Answers Introduction to .NET Framework C# | Constructors Extension Method in C# C# | Class and Object C# | Abstract Classes
[ { "code": null, "e": 24093, "s": 24065, "text": "\n01 Feb, 2019" }, { "code": null, "e": 24203, "s": 24093, "text": "GetUpperBound() Method is used to find the index of the last element of the specified dimension in the array." }, { "code": null, "e": 24211, "s": 24203, "text": "Syntax:" }, { "code": null, "e": 24253, "s": 24211, "text": "public int GetUpperBound (int dimension);" }, { "code": null, "e": 24350, "s": 24253, "text": "Here, dimension is a zero-based dimension of the array whose upper bound needs to be determined." }, { "code": null, "e": 24544, "s": 24350, "text": "Return Value:The return type of this method is System.Int32. This method returns the index of the last element of the specified dimension in the array Or -1 if the specified dimension is empty." }, { "code": null, "e": 24678, "s": 24544, "text": "Exception: This method will give IndexOutOfRangeException if the value of dimension is less than zero, or equal or greater than Rank." }, { "code": null, "e": 24882, "s": 24678, "text": "Note: GetUpperBound(0) returns the last index in the first dimension of the array, and GetUpperBound(Rank – 1) returns the last index of the last dimension of the array. This method is an O(1) operation." }, { "code": null, "e": 24943, "s": 24882, "text": "Below programs illustrate the use of GetUpperBound() Method:" }, { "code": null, "e": 24954, "s": 24943, "text": "Example 1:" }, { "code": "// C# program to illustrate the GetUpperBound(Int32)// method in 1-D arrayusing System; public class GFG { // Main method static public void Main() { // 1-D Array int[] value = {1, 2, 3, 4, 5, 6, 7}; // Get the index of the last element // in the given Array by using // GetUpperBound(Int32) method int myvalue = value.GetUpperBound(0); Console.WriteLine(\"Index: {0}\", myvalue); }}", "e": 25419, "s": 24954, "text": null }, { "code": null, "e": 25429, "s": 25419, "text": "Index: 6\n" }, { "code": null, "e": 25440, "s": 25429, "text": "Example 2:" }, { "code": "// C# program to find last index // value and rank of 2-D arrayusing System; public class GFG { // Main method static public void Main() { // 2-D char Array char[, ] value = { { 'a', 'b' }, { 'c', 'd' }, { 'e', 'f' }, { 'g', 'h' }, { 'i', 'j' } }; // Get the index of the last element // and the rank of the given Array int myvalue = value.GetUpperBound(0); Console.WriteLine(\"Dimension: {0}\", value.Rank); Console.WriteLine(\"Index: {0}\", myvalue); }}", "e": 26029, "s": 25440, "text": null }, { "code": null, "e": 26052, "s": 26029, "text": "Dimension: 2\nIndex: 4\n" }, { "code": null, "e": 26151, "s": 26052, "text": "Reference: https://docs.microsoft.com/en-us/dotnet/api/system.array.getupperbound?view=netcore-2.1" }, { "code": null, "e": 26165, "s": 26151, "text": "CSharp-Arrays" }, { "code": null, "e": 26179, "s": 26165, "text": "CSharp-method" }, { "code": null, "e": 26182, "s": 26179, "text": "C#" }, { "code": null, "e": 26280, "s": 26182, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26289, "s": 26280, "text": "Comments" }, { "code": null, "e": 26302, "s": 26289, "text": "Old Comments" }, { "code": null, "e": 26325, "s": 26302, "text": "C# | Method Overriding" }, { "code": null, "e": 26353, "s": 26325, "text": "C# Dictionary with examples" }, { "code": null, "e": 26399, "s": 26353, "text": "Difference between Ref and Out keywords in C#" }, { "code": null, "e": 26414, "s": 26399, "text": "C# | Delegates" }, { "code": null, "e": 26454, "s": 26414, "text": "Top 50 C# Interview Questions & Answers" }, { "code": null, "e": 26485, "s": 26454, "text": "Introduction to .NET Framework" }, { "code": null, "e": 26503, "s": 26485, "text": "C# | Constructors" }, { "code": null, "e": 26526, "s": 26503, "text": "Extension Method in C#" }, { "code": null, "e": 26548, "s": 26526, "text": "C# | Class and Object" } ]
Design Patterns - Bridge Pattern
Bridge is used when we need to decouple an abstraction from its implementation so that the two can vary independently. This type of design pattern comes under structural pattern as this pattern decouples implementation class and abstract class by providing a bridge structure between them. This pattern involves an interface which acts as a bridge which makes the functionality of concrete classes independent from interface implementer classes. Both types of classes can be altered structurally without affecting each other. We are demonstrating use of Bridge pattern via following example in which a circle can be drawn in different colors using same abstract class method but different bridge implementer classes. We have a DrawAPI interface which is acting as a bridge implementer and concrete classes RedCircle, GreenCircle implementing the DrawAPI interface. Shape is an abstract class and will use object of DrawAPI. BridgePatternDemo, our demo class will use Shape class to draw different colored circle. Create bridge implementer interface. DrawAPI.java public interface DrawAPI { public void drawCircle(int radius, int x, int y); } Create concrete bridge implementer classes implementing the DrawAPI interface. RedCircle.java public class RedCircle implements DrawAPI { @Override public void drawCircle(int radius, int x, int y) { System.out.println("Drawing Circle[ color: red, radius: " + radius + ", x: " + x + ", " + y + "]"); } } GreenCircle.java public class GreenCircle implements DrawAPI { @Override public void drawCircle(int radius, int x, int y) { System.out.println("Drawing Circle[ color: green, radius: " + radius + ", x: " + x + ", " + y + "]"); } } Create an abstract class Shape using the DrawAPI interface. Shape.java public abstract class Shape { protected DrawAPI drawAPI; protected Shape(DrawAPI drawAPI){ this.drawAPI = drawAPI; } public abstract void draw(); } Create concrete class implementing the Shape interface. Circle.java public class Circle extends Shape { private int x, y, radius; public Circle(int x, int y, int radius, DrawAPI drawAPI) { super(drawAPI); this.x = x; this.y = y; this.radius = radius; } public void draw() { drawAPI.drawCircle(radius,x,y); } } Use the Shape and DrawAPI classes to draw different colored circles. BridgePatternDemo.java public class BridgePatternDemo { public static void main(String[] args) { Shape redCircle = new Circle(100,100, 10, new RedCircle()); Shape greenCircle = new Circle(100,100, 10, new GreenCircle()); redCircle.draw(); greenCircle.draw(); } } Verify the output. Drawing Circle[ color: red, radius: 10, x: 100, 100] Drawing Circle[ color: green, radius: 10, x: 100, 100] 102 Lectures 10 hours Arnab Chakraborty 30 Lectures 3 hours Arnab Chakraborty 31 Lectures 4 hours Arnab Chakraborty 43 Lectures 1.5 hours Manoj Kumar 7 Lectures 1 hours Zach Miller 54 Lectures 4 hours Sasha Miller Print Add Notes Bookmark this page
[ { "code": null, "e": 3041, "s": 2751, "text": "Bridge is used when we need to decouple an abstraction from its implementation so that the two can vary independently. This type of design pattern comes under structural pattern as this pattern decouples implementation class and abstract class by providing a bridge structure between them." }, { "code": null, "e": 3277, "s": 3041, "text": "This pattern involves an interface which acts as a bridge which makes the functionality of concrete classes independent from interface implementer classes. Both types of classes can be altered structurally without affecting each other." }, { "code": null, "e": 3469, "s": 3277, "text": "We are demonstrating use of Bridge pattern via following example in which a circle can be drawn in different colors using same abstract class method but different bridge implementer classes. " }, { "code": null, "e": 3765, "s": 3469, "text": "We have a DrawAPI interface which is acting as a bridge implementer and concrete classes RedCircle, GreenCircle implementing the DrawAPI interface. Shape is an abstract class and will use object of DrawAPI. BridgePatternDemo, our demo class will use Shape class to draw different colored circle." }, { "code": null, "e": 3802, "s": 3765, "text": "Create bridge implementer interface." }, { "code": null, "e": 3815, "s": 3802, "text": "DrawAPI.java" }, { "code": null, "e": 3897, "s": 3815, "text": "public interface DrawAPI {\n public void drawCircle(int radius, int x, int y);\n}" }, { "code": null, "e": 3976, "s": 3897, "text": "Create concrete bridge implementer classes implementing the DrawAPI interface." }, { "code": null, "e": 3991, "s": 3976, "text": "RedCircle.java" }, { "code": null, "e": 4215, "s": 3991, "text": "public class RedCircle implements DrawAPI {\n @Override\n public void drawCircle(int radius, int x, int y) {\n System.out.println(\"Drawing Circle[ color: red, radius: \" + radius + \", x: \" + x + \", \" + y + \"]\");\n }\n}" }, { "code": null, "e": 4232, "s": 4215, "text": "GreenCircle.java" }, { "code": null, "e": 4460, "s": 4232, "text": "public class GreenCircle implements DrawAPI {\n @Override\n public void drawCircle(int radius, int x, int y) {\n System.out.println(\"Drawing Circle[ color: green, radius: \" + radius + \", x: \" + x + \", \" + y + \"]\");\n }\n}" }, { "code": null, "e": 4520, "s": 4460, "text": "Create an abstract class Shape using the DrawAPI interface." }, { "code": null, "e": 4531, "s": 4520, "text": "Shape.java" }, { "code": null, "e": 4702, "s": 4531, "text": "public abstract class Shape {\n protected DrawAPI drawAPI;\n \n protected Shape(DrawAPI drawAPI){\n this.drawAPI = drawAPI;\n }\n public abstract void draw();\t\n}" }, { "code": null, "e": 4758, "s": 4702, "text": "Create concrete class implementing the Shape interface." }, { "code": null, "e": 4770, "s": 4758, "text": "Circle.java" }, { "code": null, "e": 5063, "s": 4770, "text": "public class Circle extends Shape {\n private int x, y, radius;\n\n public Circle(int x, int y, int radius, DrawAPI drawAPI) {\n super(drawAPI);\n this.x = x; \n this.y = y; \n this.radius = radius;\n }\n\n public void draw() {\n drawAPI.drawCircle(radius,x,y);\n }\n}" }, { "code": null, "e": 5132, "s": 5063, "text": "Use the Shape and DrawAPI classes to draw different colored circles." }, { "code": null, "e": 5155, "s": 5132, "text": "BridgePatternDemo.java" }, { "code": null, "e": 5426, "s": 5155, "text": "public class BridgePatternDemo {\n public static void main(String[] args) {\n Shape redCircle = new Circle(100,100, 10, new RedCircle());\n Shape greenCircle = new Circle(100,100, 10, new GreenCircle());\n\n redCircle.draw();\n greenCircle.draw();\n }\n}" }, { "code": null, "e": 5445, "s": 5426, "text": "Verify the output." }, { "code": null, "e": 5555, "s": 5445, "text": "Drawing Circle[ color: red, radius: 10, x: 100, 100]\nDrawing Circle[ color: green, radius: 10, x: 100, 100]\n" }, { "code": null, "e": 5590, "s": 5555, "text": "\n 102 Lectures \n 10 hours \n" }, { "code": null, "e": 5609, "s": 5590, "text": " Arnab Chakraborty" }, { "code": null, "e": 5642, "s": 5609, "text": "\n 30 Lectures \n 3 hours \n" }, { "code": null, "e": 5661, "s": 5642, "text": " Arnab Chakraborty" }, { "code": null, "e": 5694, "s": 5661, "text": "\n 31 Lectures \n 4 hours \n" }, { "code": null, "e": 5713, "s": 5694, "text": " Arnab Chakraborty" }, { "code": null, "e": 5748, "s": 5713, "text": "\n 43 Lectures \n 1.5 hours \n" }, { "code": null, "e": 5761, "s": 5748, "text": " Manoj Kumar" }, { "code": null, "e": 5793, "s": 5761, "text": "\n 7 Lectures \n 1 hours \n" }, { "code": null, "e": 5806, "s": 5793, "text": " Zach Miller" }, { "code": null, "e": 5839, "s": 5806, "text": "\n 54 Lectures \n 4 hours \n" }, { "code": null, "e": 5853, "s": 5839, "text": " Sasha Miller" }, { "code": null, "e": 5860, "s": 5853, "text": " Print" }, { "code": null, "e": 5871, "s": 5860, "text": " Add Notes" } ]
How to retrieve the Azure VM Subscription Name using PowerShell?
Once you are connected to the Azure Account, there are possibilities that the Get-AzVM will display the VMs from all the Azure Subscriptions. To find the specific Azure VM Subscription name, we will first retrieve the details of the VM using the Get-AzVM and it has an ID property that contains the Subscription ID and from the subscription ID property, we can retrieve the name of the Azure Subscription Name. PS C:\> $azvm = Get-AzVM -Name TestMachine2k16 PS C:\> $subid = ($azvm.Id -split '/')[2] PS C:\> (Get-AzSubscription -SubscriptionId $subid).Name The above will retrieve the name of the subscription.
[ { "code": null, "e": 1204, "s": 1062, "text": "Once you are connected to the Azure Account, there are possibilities that the Get-AzVM will display the VMs from all the Azure Subscriptions." }, { "code": null, "e": 1473, "s": 1204, "text": "To find the specific Azure VM Subscription name, we will first retrieve the details of the VM using the Get-AzVM and it has an ID property that contains the Subscription ID and from the subscription ID property, we can retrieve the name of the Azure Subscription Name." }, { "code": null, "e": 1619, "s": 1473, "text": "PS C:\\> $azvm = Get-AzVM -Name TestMachine2k16\nPS C:\\> $subid = ($azvm.Id -split '/')[2]\nPS C:\\> (Get-AzSubscription -SubscriptionId $subid).Name" }, { "code": null, "e": 1673, "s": 1619, "text": "The above will retrieve the name of the subscription." } ]
HTML | Window createPopup() Method
11 Oct, 2019 The createPopup() method in html window is used to create a pop-up window. Syntax: window.createPopup() Example: <html> <head> <title> DOM createPopup() Method </title> <style> h1 { color: green; } </style></head> <head> <script type="text/javascript"> function show_popup() { var pop = window.createPopup() var popbody = pop.document.body popbody.style.backgroundColor = "lime" popbody.style.border = "solid black 1px" popbody.innerHTML = "I am the pop-up, Click outside to close." pop.show(150, 150, 200, 50, document.body) } </script></head> <body> <center> <h1> GeeksforGeeks </h1> <button onclick="show_popup()"> pop-up! </button> </center></body> </html> Output: Note: The Window createPopup() Method works before Internet Explorer 11. Supported browser: Google Chrome: NO Mozilla Firefox: NO Edge: NO Opera: NO Safari: NO shubham_singh HTML-Methods HTML Web Technologies HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. REST API (Introduction) Types of CSS (Cascading Style Sheet) HTTP headers | Content-Type Design a Tribute Page using HTML & CSS How to Insert Form Data into Database using PHP ? Installation of Node.js on Linux Difference between var, let and const keywords in JavaScript How to fetch data from an API in ReactJS ? Differences between Functional Components and Class Components in React Remove elements from a JavaScript Array
[ { "code": null, "e": 28, "s": 0, "text": "\n11 Oct, 2019" }, { "code": null, "e": 103, "s": 28, "text": "The createPopup() method in html window is used to create a pop-up window." }, { "code": null, "e": 111, "s": 103, "text": "Syntax:" }, { "code": null, "e": 132, "s": 111, "text": "window.createPopup()" }, { "code": null, "e": 141, "s": 132, "text": "Example:" }, { "code": "<html> <head> <title> DOM createPopup() Method </title> <style> h1 { color: green; } </style></head> <head> <script type=\"text/javascript\"> function show_popup() { var pop = window.createPopup() var popbody = pop.document.body popbody.style.backgroundColor = \"lime\" popbody.style.border = \"solid black 1px\" popbody.innerHTML = \"I am the pop-up, Click outside to close.\" pop.show(150, 150, 200, 50, document.body) } </script></head> <body> <center> <h1> GeeksforGeeks </h1> <button onclick=\"show_popup()\"> pop-up! </button> </center></body> </html>", "e": 881, "s": 141, "text": null }, { "code": null, "e": 889, "s": 881, "text": "Output:" }, { "code": null, "e": 962, "s": 889, "text": "Note: The Window createPopup() Method works before Internet Explorer 11." }, { "code": null, "e": 981, "s": 962, "text": "Supported browser:" }, { "code": null, "e": 999, "s": 981, "text": "Google Chrome: NO" }, { "code": null, "e": 1019, "s": 999, "text": "Mozilla Firefox: NO" }, { "code": null, "e": 1028, "s": 1019, "text": "Edge: NO" }, { "code": null, "e": 1038, "s": 1028, "text": "Opera: NO" }, { "code": null, "e": 1049, "s": 1038, "text": "Safari: NO" }, { "code": null, "e": 1063, "s": 1049, "text": "shubham_singh" }, { "code": null, "e": 1076, "s": 1063, "text": "HTML-Methods" }, { "code": null, "e": 1081, "s": 1076, "text": "HTML" }, { "code": null, "e": 1098, "s": 1081, "text": "Web Technologies" }, { "code": null, "e": 1103, "s": 1098, "text": "HTML" }, { "code": null, "e": 1201, "s": 1103, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1225, "s": 1201, "text": "REST API (Introduction)" }, { "code": null, "e": 1262, "s": 1225, "text": "Types of CSS (Cascading Style Sheet)" }, { "code": null, "e": 1290, "s": 1262, "text": "HTTP headers | Content-Type" }, { "code": null, "e": 1329, "s": 1290, "text": "Design a Tribute Page using HTML & CSS" }, { "code": null, "e": 1379, "s": 1329, "text": "How to Insert Form Data into Database using PHP ?" }, { "code": null, "e": 1412, "s": 1379, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 1473, "s": 1412, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 1516, "s": 1473, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 1588, "s": 1516, "text": "Differences between Functional Components and Class Components in React" } ]
Python | Get the substring from given string using list slicing
05 Jul, 2022 Given a string, write a Python program to get the substring from given string using list slicing. Let’s try to get this using different examples. A substring is a portion of a string. Python offers a variety of techniques for producing substrings, as well as for determining the index of a substring and more. Syntax: myString[start:stop:step] Parameter: start: It is the index of the list where slicing starts. stop: It is the index of the list where slicing ends. step: It allows you to select nth item within the range start to stop. Example 1: In this example, we will see how to take a substring from the end or from starting of the string. Python3 # Python3 code to demonstrate# to create a substring from a string # Initialising stringini_string = 'xbzefdgstb' # printing initial string and characterprint("initial_strings : ", ini_string) # creating substring from start of string# define length upto which substring requiredsstring_strt = ini_string[:2]sstring_end = ini_string[3:] # printing resultprint("print resultant substring from start", sstring_strt)print("print resultant substring from end", sstring_end) Output: initial_strings : xbzefdgstb print resultant substring from start xb print resultant substring from end efdgstb Example 2: In this example, we will see how to create a string by taking characters from a certain positional gap. Python3 # Python3 code to demonstrate# to create a substring from string # Initialising stringini_string = 'xbzefdgstb' # printing initial string and characterprint("initial_strings : ", ini_string) # creating substring by taking element# after certain position gap# define length upto which substring requiredsstring_alt = ini_string[::2]sstring_gap2 = ini_string[::3] # printing resultprint("print resultant substring from start", sstring_alt)print("print resultant substring from end", sstring_gap2) Output: initial_strings : xbzefdgstb print resultant substring from start xzfgt print resultant substring from end xegb Example 3: In this example, we are considering both cases of taking strings from the middle with some positional gap between characters. Python3 # Python3 code to demonstrate# to create a substring from string # Initialising stringini_string = 'xbzefdgstb' # printing initial string and characterprint ("initial_strings : ", ini_string) # creating substring by taking element# after certain position gap# in defined lengthsstring = ini_string[2:7:2] # printing resultprint ("print resultant substring", sstring) Output: initial_strings : xbzefdgstb print resultant substring zfg surajkumarguptaintern Python string-programs Python Python Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n05 Jul, 2022" }, { "code": null, "e": 174, "s": 28, "text": "Given a string, write a Python program to get the substring from given string using list slicing. Let’s try to get this using different examples." }, { "code": null, "e": 338, "s": 174, "text": "A substring is a portion of a string. Python offers a variety of techniques for producing substrings, as well as for determining the index of a substring and more." }, { "code": null, "e": 372, "s": 338, "text": "Syntax: myString[start:stop:step]" }, { "code": null, "e": 383, "s": 372, "text": "Parameter:" }, { "code": null, "e": 440, "s": 383, "text": "start: It is the index of the list where slicing starts." }, { "code": null, "e": 494, "s": 440, "text": "stop: It is the index of the list where slicing ends." }, { "code": null, "e": 565, "s": 494, "text": "step: It allows you to select nth item within the range start to stop." }, { "code": null, "e": 675, "s": 565, "text": "Example 1: In this example, we will see how to take a substring from the end or from starting of the string. " }, { "code": null, "e": 683, "s": 675, "text": "Python3" }, { "code": "# Python3 code to demonstrate# to create a substring from a string # Initialising stringini_string = 'xbzefdgstb' # printing initial string and characterprint(\"initial_strings : \", ini_string) # creating substring from start of string# define length upto which substring requiredsstring_strt = ini_string[:2]sstring_end = ini_string[3:] # printing resultprint(\"print resultant substring from start\", sstring_strt)print(\"print resultant substring from end\", sstring_end)", "e": 1153, "s": 683, "text": null }, { "code": null, "e": 1161, "s": 1153, "text": "Output:" }, { "code": null, "e": 1274, "s": 1161, "text": "initial_strings : xbzefdgstb\nprint resultant substring from start xb\nprint resultant substring from end efdgstb" }, { "code": null, "e": 1390, "s": 1274, "text": "Example 2: In this example, we will see how to create a string by taking characters from a certain positional gap. " }, { "code": null, "e": 1398, "s": 1390, "text": "Python3" }, { "code": "# Python3 code to demonstrate# to create a substring from string # Initialising stringini_string = 'xbzefdgstb' # printing initial string and characterprint(\"initial_strings : \", ini_string) # creating substring by taking element# after certain position gap# define length upto which substring requiredsstring_alt = ini_string[::2]sstring_gap2 = ini_string[::3] # printing resultprint(\"print resultant substring from start\", sstring_alt)print(\"print resultant substring from end\", sstring_gap2)", "e": 1893, "s": 1398, "text": null }, { "code": null, "e": 1901, "s": 1893, "text": "Output:" }, { "code": null, "e": 2014, "s": 1901, "text": "initial_strings : xbzefdgstb\nprint resultant substring from start xzfgt\nprint resultant substring from end xegb" }, { "code": null, "e": 2152, "s": 2014, "text": "Example 3: In this example, we are considering both cases of taking strings from the middle with some positional gap between characters. " }, { "code": null, "e": 2160, "s": 2152, "text": "Python3" }, { "code": "# Python3 code to demonstrate# to create a substring from string # Initialising stringini_string = 'xbzefdgstb' # printing initial string and characterprint (\"initial_strings : \", ini_string) # creating substring by taking element# after certain position gap# in defined lengthsstring = ini_string[2:7:2] # printing resultprint (\"print resultant substring\", sstring)", "e": 2527, "s": 2160, "text": null }, { "code": null, "e": 2535, "s": 2527, "text": "Output:" }, { "code": null, "e": 2595, "s": 2535, "text": "initial_strings : xbzefdgstb\nprint resultant substring zfg" }, { "code": null, "e": 2617, "s": 2595, "text": "surajkumarguptaintern" }, { "code": null, "e": 2640, "s": 2617, "text": "Python string-programs" }, { "code": null, "e": 2647, "s": 2640, "text": "Python" }, { "code": null, "e": 2663, "s": 2647, "text": "Python Programs" } ]
Connect Nodes at same Level (Level Order Traversal)
24 Jun, 2022 Write a function to connect all the adjacent nodes at the same level in a binary tree. Example: Input Tree A / \ B C / \ \ D E F Output Tree A--->NULL / \ B-->C-->NULL / \ \ D-->E-->F-->NULL We have already discussed O(n^2) time and O approach in Connect nodes at same level as morris traversal in worst case can be O(n) and calling it to set right pointer can result in O(n^2) time complexity.In this post, We have discussed Level Order Traversal with NULL markers which are needed to mark levels in tree. C++ Java Python3 C# Javascript // Connect nodes at same level using level order// traversal.#include <bits/stdc++.h>using namespace std; struct Node { int data; struct Node* left, *right, *nextRight;}; // Sets nextRight of all nodes of a treevoid connect(struct Node* root){ queue<Node*> q; q.push(root); // null marker to represent end of current level q.push(NULL); // Do Level order of tree using NULL markers while (!q.empty()) { Node *p = q.front(); q.pop(); if (p != NULL) { // next element in queue represents next // node at current Level p->nextRight = q.front(); // push left and right children of current // node if (p->left) q.push(p->left); if (p->right) q.push(p->right); } // if queue is not empty, push NULL to mark // nodes at this level are visited else if (!q.empty()) q.push(NULL); }} /* UTILITY FUNCTIONS *//* Helper function that allocates a new node with the given data and NULL left and right pointers. */struct Node* newnode(int data){ struct Node* node = (struct Node*) malloc(sizeof(struct Node)); node->data = data; node->left = node->right = node->nextRight = NULL; return (node);} /* Driver program to test above functions*/int main(){ /* Constructed binary tree is 10 / \ 8 2 / \ 3 90 */ struct Node* root = newnode(10); root->left = newnode(8); root->right = newnode(2); root->left->left = newnode(3); root->right->right = newnode(90); // Populates nextRight pointer in all nodes connect(root); // Let us check the values of nextRight pointers printf("Following are populated nextRight pointers in \n" "the tree (-1 is printed if there is no nextRight) \n"); printf("nextRight of %d is %d \n", root->data, root->nextRight ? root->nextRight->data : -1); printf("nextRight of %d is %d \n", root->left->data, root->left->nextRight ? root->left->nextRight->data : -1); printf("nextRight of %d is %d \n", root->right->data, root->right->nextRight ? root->right->nextRight->data : -1); printf("nextRight of %d is %d \n", root->left->left->data, root->left->left->nextRight ? root->left->left->nextRight->data : -1); printf("nextRight of %d is %d \n", root->right->right->data, root->right->right->nextRight ? root->right->right->nextRight->data : -1); return 0;} // Connect nodes at same level using level order// traversal.import java.util.LinkedList;import java.util.Queue;public class Connect_node_same_level { // Node class static class Node { int data; Node left, right, nextRight; Node(int data){ this.data = data; left = null; right = null; nextRight = null; } }; // Sets nextRight of all nodes of a tree static void connect(Node root) { Queue<Node> q = new LinkedList<Node>(); q.add(root); // null marker to represent end of current level q.add(null); // Do Level order of tree using NULL markers while (!q.isEmpty()) { Node p = q.peek(); q.remove(); if (p != null) { // next element in queue represents next // node at current Level p.nextRight = q.peek(); // push left and right children of current // node if (p.left != null) q.add(p.left); if (p.right != null) q.add(p.right); } // if queue is not empty, push NULL to mark // nodes at this level are visited else if (!q.isEmpty()) q.add(null); } } /* Driver program to test above functions*/ public static void main(String args[]) { /* Constructed binary tree is 10 / \ 8 2 / \ 3 90 */ Node root = new Node(10); root.left = new Node(8); root.right = new Node(2); root.left.left = new Node(3); root.right.right = new Node(90); // Populates nextRight pointer in all nodes connect(root); // Let us check the values of nextRight pointers System.out.println("Following are populated nextRight pointers in \n" + "the tree (-1 is printed if there is no nextRight)"); System.out.println("nextRight of "+ root.data +" is "+ ((root.nextRight != null) ? root.nextRight.data : -1)); System.out.println("nextRight of "+ root.left.data+" is "+ ((root.left.nextRight != null) ? root.left.nextRight.data : -1)); System.out.println("nextRight of "+ root.right.data+" is "+ ((root.right.nextRight != null) ? root.right.nextRight.data : -1)); System.out.println("nextRight of "+ root.left.left.data+" is "+ ((root.left.left.nextRight != null) ? root.left.left.nextRight.data : -1)); System.out.println("nextRight of "+ root.right.right.data+" is "+ ((root.right.right.nextRight != null) ? root.right.right.nextRight.data : -1)); }} // This code is contributed by Sumit Ghosh #! /usr/bin/env python3 # connect nodes at same level using level order traversalimport sys class Node: def __init__(self, data): self.data = data self.left = None self.right = None self.nextRight = None def __str__(self): return '{}'.format(self.data) def printLevelByLevel(root): # print level by level if root: node = root while node: print('{}'.format(node.data), end=' ') node = node.nextRight print() if root.left: printLevelByLevel(root.left) else: printLevelByLevel(root.right) def inorder(root): if root: inorder(root.left) print(root.data, end=' ') inorder(root.right) def connect(root): # set nextRight of all nodes of a tree queue = [] queue.append(root) # null marker to represent end of current level queue.append(None) # do level order of tree using None markers while queue: p = queue.pop(0) if p: # next element in queue represents # next node at current level p.nextRight = queue[0] # pus left and right children of current node if p.left: queue.append(p.left) if p.right: queue.append(p.right) else if queue: queue.append(None) def main(): """Driver program to test above functions. Constructed binary tree is 10 / \ 8 2 / \ 3 90 """ root = Node(10) root.left = Node(8) root.right = Node(2) root.left.left = Node(3) root.right.right = Node(90) # Populates nextRight pointer in all nodes connect(root) # Let us check the values of nextRight pointers print("Following are populated nextRight pointers in \n" "the tree (-1 is printed if there is no nextRight) \n") if(root.nextRight != None): print("nextRight of %d is %d \n" %(root.data,root.nextRight.data)) else: print("nextRight of %d is %d \n" %(root.data,-1)) if(root.left.nextRight != None): print("nextRight of %d is %d \n" %(root.left.data,root.left.nextRight.data)) else: print("nextRight of %d is %d \n" %(root.left.data,-1)) if(root.right.nextRight != None): print("nextRight of %d is %d \n" %(root.right.data,root.right.nextRight.data)) else: print("nextRight of %d is %d \n" %(root.right.data,-1)) if(root.left.left.nextRight != None): print("nextRight of %d is %d \n" %(root.left.left.data,root.left.left.nextRight.data)) else: print("nextRight of %d is %d \n" %(root.left.left.data,-1)) if(root.right.right.nextRight != None): print("nextRight of %d is %d \n" %(root.right.right.data,root.right.right.nextRight.data)) else: print("nextRight of %d is %d \n" %(root.right.right.data,-1)) print() if __name__ == "__main__": main() # This code is contributed by Ram Basnet // Connect nodes at same level using level order// traversal.using System;using System.Collections.Generic; public class Connect_node_same_level{ // Node class class Node { public int data; public Node left, right, nextRight; public Node(int data) { this.data = data; left = null; right = null; nextRight = null; } }; // Sets nextRight of all nodes of a tree static void connect(Node root) { Queue<Node> q = new Queue<Node>(); q.Enqueue(root); // null marker to represent end of current level q.Enqueue(null); // Do Level order of tree using NULL markers while (q.Count!=0) { Node p = q.Peek(); q.Dequeue(); if (p != null) { // next element in queue represents next // node at current Level p.nextRight = q.Peek(); // push left and right children of current // node if (p.left != null) q.Enqueue(p.left); if (p.right != null) q.Enqueue(p.right); } // if queue is not empty, push NULL to mark // nodes at this level are visited else if (q.Count!=0) q.Enqueue(null); } } /* Driver code*/ public static void Main() { /* Constructed binary tree is 10 / \ 8 2 / \ 3 90 */ Node root = new Node(10); root.left = new Node(8); root.right = new Node(2); root.left.left = new Node(3); root.right.right = new Node(90); // Populates nextRight pointer in all nodes connect(root); // Let us check the values of nextRight pointers Console.WriteLine("Following are populated nextRight pointers in \n" + "the tree (-1 is printed if there is no nextRight)"); Console.WriteLine("nextRight of "+ root.data +" is "+ ((root.nextRight != null) ? root.nextRight.data : -1)); Console.WriteLine("nextRight of "+ root.left.data+" is "+ ((root.left.nextRight != null) ? root.left.nextRight.data : -1)); Console.WriteLine("nextRight of "+ root.right.data+" is "+ ((root.right.nextRight != null) ? root.right.nextRight.data : -1)); Console.WriteLine("nextRight of "+ root.left.left.data+" is "+ ((root.left.left.nextRight != null) ? root.left.left.nextRight.data : -1)); Console.WriteLine("nextRight of "+ root.right.right.data+" is "+ ((root.right.right.nextRight != null) ? root.right.right.nextRight.data : -1)); }} /* This code is contributed by Rajput-Ji*/ <script> // Connect nodes at same level using level order traversal. // A Binary Tree Node class Node { constructor(data, nextRight) { this.left = null; this.right = null; this.data = data; this.nextRight = nextRight; } } // Sets nextRight of all nodes of a tree function connect(root) { let q = []; q.push(root); // null marker to represent end of current level q.push(null); // Do Level order of tree using NULL markers while (q.length > 0) { let p = q[0]; q.shift(); if (p != null) { // next element in queue represents next // node at current Level p.nextRight = q[0]; // push left and right children of current // node if (p.left != null) q.push(p.left); if (p.right != null) q.push(p.right); } // if queue is not empty, push NULL to mark // nodes at this level are visited else if (q.length > 0) q.push(null); } } /* Constructed binary tree is 10 / \ 8 2 / \ 3 90 */ let root = new Node(10); root.left = new Node(8); root.right = new Node(2); root.left.left = new Node(3); root.right.right = new Node(90); // Populates nextRight pointer in all nodes connect(root); // Let us check the values of nextRight pointers document.write("Following are populated nextRight pointers in " + "</br>" + "the tree (-1 is printed if there is no nextRight)" + "</br>"); document.write("nextRight of "+ root.data +" is "+ ((root.nextRight != null) ? root.nextRight.data : -1) + "</br>"); document.write("nextRight of "+ root.left.data+" is "+ ((root.left.nextRight != null) ? root.left.nextRight.data : -1) + "</br>"); document.write("nextRight of "+ root.right.data+" is "+ ((root.right.nextRight != null) ? root.right.nextRight.data : -1) + "</br>"); document.write("nextRight of "+ root.left.left.data+" is "+ ((root.left.left.nextRight != null) ? root.left.left.nextRight.data : -1) + "</br>"); document.write("nextRight of "+ root.right.right.data+" is "+ ((root.right.right.nextRight != null) ? root.right.right.nextRight.data : -1) + "</br>"); // This code is contributed by divyesh072019.</script> Output: Following are populated nextRight pointers in the tree (-1 is printed if there is no nextRight) nextRight of 10 is -1 nextRight of 8 is 2 nextRight of 2 is -1 nextRight of 3 is 90 nextRight of 90 is -1 Time complexity :O(n) where n is the number of nodes Auxiliary Space : O(n) for queue Alternate Implementation: We can also follow the implementation discussed in Print level order traversal line by line | Set 1. We keep connecting nodes of same level by keeping track of previous visited node of same level. Implementation : https://ide.geeksforgeeks.org/gV1Oc2Thanks to Akilan Sengottaiyan for suggesting this alternate implementation. This article is contributed by Abhishek Rajput. 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. Rajput-Ji divyesh072019 chhabradhanvi surinderdawra388 technophpfij Adobe Amazon Boomerang Commerce Flipkart Google Microsoft Ola Cabs Oracle OYO Rooms tree-level-order Xome Tree Flipkart Amazon Microsoft OYO Rooms Ola Cabs Oracle Adobe Google Boomerang Commerce Xome Tree Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Introduction to Data Structures Introduction to Tree Data Structure What is Data Structure: Types, Classifications and Applications Binary Tree | Set 3 (Types of Binary Tree) Lowest Common Ancestor in a Binary Tree | Set 1 Binary Tree | Set 2 (Properties) Diameter of a Binary Tree Decision Tree Diagonal Traversal of Binary Tree Insertion in a Binary Tree in level order
[ { "code": null, "e": 54, "s": 26, "text": "\n24 Jun, 2022" }, { "code": null, "e": 141, "s": 54, "text": "Write a function to connect all the adjacent nodes at the same level in a binary tree." }, { "code": null, "e": 151, "s": 141, "text": "Example: " }, { "code": null, "e": 308, "s": 151, "text": "Input Tree\n A\n / \\\n B C\n / \\ \\\n D E F\n\n\nOutput Tree\n A--->NULL\n / \\\n B-->C-->NULL\n / \\ \\\n D-->E-->F-->NULL" }, { "code": null, "e": 625, "s": 308, "text": "We have already discussed O(n^2) time and O approach in Connect nodes at same level as morris traversal in worst case can be O(n) and calling it to set right pointer can result in O(n^2) time complexity.In this post, We have discussed Level Order Traversal with NULL markers which are needed to mark levels in tree. " }, { "code": null, "e": 629, "s": 625, "text": "C++" }, { "code": null, "e": 634, "s": 629, "text": "Java" }, { "code": null, "e": 642, "s": 634, "text": "Python3" }, { "code": null, "e": 645, "s": 642, "text": "C#" }, { "code": null, "e": 656, "s": 645, "text": "Javascript" }, { "code": "// Connect nodes at same level using level order// traversal.#include <bits/stdc++.h>using namespace std; struct Node { int data; struct Node* left, *right, *nextRight;}; // Sets nextRight of all nodes of a treevoid connect(struct Node* root){ queue<Node*> q; q.push(root); // null marker to represent end of current level q.push(NULL); // Do Level order of tree using NULL markers while (!q.empty()) { Node *p = q.front(); q.pop(); if (p != NULL) { // next element in queue represents next // node at current Level p->nextRight = q.front(); // push left and right children of current // node if (p->left) q.push(p->left); if (p->right) q.push(p->right); } // if queue is not empty, push NULL to mark // nodes at this level are visited else if (!q.empty()) q.push(NULL); }} /* UTILITY FUNCTIONS *//* Helper function that allocates a new node with the given data and NULL left and right pointers. */struct Node* newnode(int data){ struct Node* node = (struct Node*) malloc(sizeof(struct Node)); node->data = data; node->left = node->right = node->nextRight = NULL; return (node);} /* Driver program to test above functions*/int main(){ /* Constructed binary tree is 10 / \\ 8 2 / \\ 3 90 */ struct Node* root = newnode(10); root->left = newnode(8); root->right = newnode(2); root->left->left = newnode(3); root->right->right = newnode(90); // Populates nextRight pointer in all nodes connect(root); // Let us check the values of nextRight pointers printf(\"Following are populated nextRight pointers in \\n\" \"the tree (-1 is printed if there is no nextRight) \\n\"); printf(\"nextRight of %d is %d \\n\", root->data, root->nextRight ? root->nextRight->data : -1); printf(\"nextRight of %d is %d \\n\", root->left->data, root->left->nextRight ? root->left->nextRight->data : -1); printf(\"nextRight of %d is %d \\n\", root->right->data, root->right->nextRight ? root->right->nextRight->data : -1); printf(\"nextRight of %d is %d \\n\", root->left->left->data, root->left->left->nextRight ? root->left->left->nextRight->data : -1); printf(\"nextRight of %d is %d \\n\", root->right->right->data, root->right->right->nextRight ? root->right->right->nextRight->data : -1); return 0;}", "e": 3207, "s": 656, "text": null }, { "code": "// Connect nodes at same level using level order// traversal.import java.util.LinkedList;import java.util.Queue;public class Connect_node_same_level { // Node class static class Node { int data; Node left, right, nextRight; Node(int data){ this.data = data; left = null; right = null; nextRight = null; } }; // Sets nextRight of all nodes of a tree static void connect(Node root) { Queue<Node> q = new LinkedList<Node>(); q.add(root); // null marker to represent end of current level q.add(null); // Do Level order of tree using NULL markers while (!q.isEmpty()) { Node p = q.peek(); q.remove(); if (p != null) { // next element in queue represents next // node at current Level p.nextRight = q.peek(); // push left and right children of current // node if (p.left != null) q.add(p.left); if (p.right != null) q.add(p.right); } // if queue is not empty, push NULL to mark // nodes at this level are visited else if (!q.isEmpty()) q.add(null); } } /* Driver program to test above functions*/ public static void main(String args[]) { /* Constructed binary tree is 10 / \\ 8 2 / \\ 3 90 */ Node root = new Node(10); root.left = new Node(8); root.right = new Node(2); root.left.left = new Node(3); root.right.right = new Node(90); // Populates nextRight pointer in all nodes connect(root); // Let us check the values of nextRight pointers System.out.println(\"Following are populated nextRight pointers in \\n\" + \"the tree (-1 is printed if there is no nextRight)\"); System.out.println(\"nextRight of \"+ root.data +\" is \"+ ((root.nextRight != null) ? root.nextRight.data : -1)); System.out.println(\"nextRight of \"+ root.left.data+\" is \"+ ((root.left.nextRight != null) ? root.left.nextRight.data : -1)); System.out.println(\"nextRight of \"+ root.right.data+\" is \"+ ((root.right.nextRight != null) ? root.right.nextRight.data : -1)); System.out.println(\"nextRight of \"+ root.left.left.data+\" is \"+ ((root.left.left.nextRight != null) ? root.left.left.nextRight.data : -1)); System.out.println(\"nextRight of \"+ root.right.right.data+\" is \"+ ((root.right.right.nextRight != null) ? root.right.right.nextRight.data : -1)); }} // This code is contributed by Sumit Ghosh", "e": 6070, "s": 3207, "text": null }, { "code": "#! /usr/bin/env python3 # connect nodes at same level using level order traversalimport sys class Node: def __init__(self, data): self.data = data self.left = None self.right = None self.nextRight = None def __str__(self): return '{}'.format(self.data) def printLevelByLevel(root): # print level by level if root: node = root while node: print('{}'.format(node.data), end=' ') node = node.nextRight print() if root.left: printLevelByLevel(root.left) else: printLevelByLevel(root.right) def inorder(root): if root: inorder(root.left) print(root.data, end=' ') inorder(root.right) def connect(root): # set nextRight of all nodes of a tree queue = [] queue.append(root) # null marker to represent end of current level queue.append(None) # do level order of tree using None markers while queue: p = queue.pop(0) if p: # next element in queue represents # next node at current level p.nextRight = queue[0] # pus left and right children of current node if p.left: queue.append(p.left) if p.right: queue.append(p.right) else if queue: queue.append(None) def main(): \"\"\"Driver program to test above functions. Constructed binary tree is 10 / \\ 8 2 / \\ 3 90 \"\"\" root = Node(10) root.left = Node(8) root.right = Node(2) root.left.left = Node(3) root.right.right = Node(90) # Populates nextRight pointer in all nodes connect(root) # Let us check the values of nextRight pointers print(\"Following are populated nextRight pointers in \\n\" \"the tree (-1 is printed if there is no nextRight) \\n\") if(root.nextRight != None): print(\"nextRight of %d is %d \\n\" %(root.data,root.nextRight.data)) else: print(\"nextRight of %d is %d \\n\" %(root.data,-1)) if(root.left.nextRight != None): print(\"nextRight of %d is %d \\n\" %(root.left.data,root.left.nextRight.data)) else: print(\"nextRight of %d is %d \\n\" %(root.left.data,-1)) if(root.right.nextRight != None): print(\"nextRight of %d is %d \\n\" %(root.right.data,root.right.nextRight.data)) else: print(\"nextRight of %d is %d \\n\" %(root.right.data,-1)) if(root.left.left.nextRight != None): print(\"nextRight of %d is %d \\n\" %(root.left.left.data,root.left.left.nextRight.data)) else: print(\"nextRight of %d is %d \\n\" %(root.left.left.data,-1)) if(root.right.right.nextRight != None): print(\"nextRight of %d is %d \\n\" %(root.right.right.data,root.right.right.nextRight.data)) else: print(\"nextRight of %d is %d \\n\" %(root.right.right.data,-1)) print() if __name__ == \"__main__\": main() # This code is contributed by Ram Basnet", "e": 9073, "s": 6070, "text": null }, { "code": "// Connect nodes at same level using level order// traversal.using System;using System.Collections.Generic; public class Connect_node_same_level{ // Node class class Node { public int data; public Node left, right, nextRight; public Node(int data) { this.data = data; left = null; right = null; nextRight = null; } }; // Sets nextRight of all nodes of a tree static void connect(Node root) { Queue<Node> q = new Queue<Node>(); q.Enqueue(root); // null marker to represent end of current level q.Enqueue(null); // Do Level order of tree using NULL markers while (q.Count!=0) { Node p = q.Peek(); q.Dequeue(); if (p != null) { // next element in queue represents next // node at current Level p.nextRight = q.Peek(); // push left and right children of current // node if (p.left != null) q.Enqueue(p.left); if (p.right != null) q.Enqueue(p.right); } // if queue is not empty, push NULL to mark // nodes at this level are visited else if (q.Count!=0) q.Enqueue(null); } } /* Driver code*/ public static void Main() { /* Constructed binary tree is 10 / \\ 8 2 / \\ 3 90 */ Node root = new Node(10); root.left = new Node(8); root.right = new Node(2); root.left.left = new Node(3); root.right.right = new Node(90); // Populates nextRight pointer in all nodes connect(root); // Let us check the values of nextRight pointers Console.WriteLine(\"Following are populated nextRight pointers in \\n\" + \"the tree (-1 is printed if there is no nextRight)\"); Console.WriteLine(\"nextRight of \"+ root.data +\" is \"+ ((root.nextRight != null) ? root.nextRight.data : -1)); Console.WriteLine(\"nextRight of \"+ root.left.data+\" is \"+ ((root.left.nextRight != null) ? root.left.nextRight.data : -1)); Console.WriteLine(\"nextRight of \"+ root.right.data+\" is \"+ ((root.right.nextRight != null) ? root.right.nextRight.data : -1)); Console.WriteLine(\"nextRight of \"+ root.left.left.data+\" is \"+ ((root.left.left.nextRight != null) ? root.left.left.nextRight.data : -1)); Console.WriteLine(\"nextRight of \"+ root.right.right.data+\" is \"+ ((root.right.right.nextRight != null) ? root.right.right.nextRight.data : -1)); }} /* This code is contributed by Rajput-Ji*/", "e": 11901, "s": 9073, "text": null }, { "code": "<script> // Connect nodes at same level using level order traversal. // A Binary Tree Node class Node { constructor(data, nextRight) { this.left = null; this.right = null; this.data = data; this.nextRight = nextRight; } } // Sets nextRight of all nodes of a tree function connect(root) { let q = []; q.push(root); // null marker to represent end of current level q.push(null); // Do Level order of tree using NULL markers while (q.length > 0) { let p = q[0]; q.shift(); if (p != null) { // next element in queue represents next // node at current Level p.nextRight = q[0]; // push left and right children of current // node if (p.left != null) q.push(p.left); if (p.right != null) q.push(p.right); } // if queue is not empty, push NULL to mark // nodes at this level are visited else if (q.length > 0) q.push(null); } } /* Constructed binary tree is 10 / \\ 8 2 / \\ 3 90 */ let root = new Node(10); root.left = new Node(8); root.right = new Node(2); root.left.left = new Node(3); root.right.right = new Node(90); // Populates nextRight pointer in all nodes connect(root); // Let us check the values of nextRight pointers document.write(\"Following are populated nextRight pointers in \" + \"</br>\" + \"the tree (-1 is printed if there is no nextRight)\" + \"</br>\"); document.write(\"nextRight of \"+ root.data +\" is \"+ ((root.nextRight != null) ? root.nextRight.data : -1) + \"</br>\"); document.write(\"nextRight of \"+ root.left.data+\" is \"+ ((root.left.nextRight != null) ? root.left.nextRight.data : -1) + \"</br>\"); document.write(\"nextRight of \"+ root.right.data+\" is \"+ ((root.right.nextRight != null) ? root.right.nextRight.data : -1) + \"</br>\"); document.write(\"nextRight of \"+ root.left.left.data+\" is \"+ ((root.left.left.nextRight != null) ? root.left.left.nextRight.data : -1) + \"</br>\"); document.write(\"nextRight of \"+ root.right.right.data+\" is \"+ ((root.right.right.nextRight != null) ? root.right.right.nextRight.data : -1) + \"</br>\"); // This code is contributed by divyesh072019.</script>", "e": 14580, "s": 11901, "text": null }, { "code": null, "e": 14589, "s": 14580, "text": "Output: " }, { "code": null, "e": 14798, "s": 14589, "text": "Following are populated nextRight pointers in \nthe tree (-1 is printed if there is no nextRight) \nnextRight of 10 is -1 \nnextRight of 8 is 2 \nnextRight of 2 is -1 \nnextRight of 3 is 90 \nnextRight of 90 is -1 " }, { "code": null, "e": 14851, "s": 14798, "text": "Time complexity :O(n) where n is the number of nodes" }, { "code": null, "e": 14885, "s": 14851, "text": "Auxiliary Space : O(n) for queue " }, { "code": null, "e": 15109, "s": 14885, "text": "Alternate Implementation: We can also follow the implementation discussed in Print level order traversal line by line | Set 1. We keep connecting nodes of same level by keeping track of previous visited node of same level. " }, { "code": null, "e": 15238, "s": 15109, "text": "Implementation : https://ide.geeksforgeeks.org/gV1Oc2Thanks to Akilan Sengottaiyan for suggesting this alternate implementation." }, { "code": null, "e": 15662, "s": 15238, "text": "This article is contributed by Abhishek Rajput. 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": 15672, "s": 15662, "text": "Rajput-Ji" }, { "code": null, "e": 15686, "s": 15672, "text": "divyesh072019" }, { "code": null, "e": 15700, "s": 15686, "text": "chhabradhanvi" }, { "code": null, "e": 15717, "s": 15700, "text": "surinderdawra388" }, { "code": null, "e": 15730, "s": 15717, "text": "technophpfij" }, { "code": null, "e": 15736, "s": 15730, "text": "Adobe" }, { "code": null, "e": 15743, "s": 15736, "text": "Amazon" }, { "code": null, "e": 15762, "s": 15743, "text": "Boomerang Commerce" }, { "code": null, "e": 15771, "s": 15762, "text": "Flipkart" }, { "code": null, "e": 15778, "s": 15771, "text": "Google" }, { "code": null, "e": 15788, "s": 15778, "text": "Microsoft" }, { "code": null, "e": 15797, "s": 15788, "text": "Ola Cabs" }, { "code": null, "e": 15804, "s": 15797, "text": "Oracle" }, { "code": null, "e": 15814, "s": 15804, "text": "OYO Rooms" }, { "code": null, "e": 15831, "s": 15814, "text": "tree-level-order" }, { "code": null, "e": 15836, "s": 15831, "text": "Xome" }, { "code": null, "e": 15841, "s": 15836, "text": "Tree" }, { "code": null, "e": 15850, "s": 15841, "text": "Flipkart" }, { "code": null, "e": 15857, "s": 15850, "text": "Amazon" }, { "code": null, "e": 15867, "s": 15857, "text": "Microsoft" }, { "code": null, "e": 15877, "s": 15867, "text": "OYO Rooms" }, { "code": null, "e": 15886, "s": 15877, "text": "Ola Cabs" }, { "code": null, "e": 15893, "s": 15886, "text": "Oracle" }, { "code": null, "e": 15899, "s": 15893, "text": "Adobe" }, { "code": null, "e": 15906, "s": 15899, "text": "Google" }, { "code": null, "e": 15925, "s": 15906, "text": "Boomerang Commerce" }, { "code": null, "e": 15930, "s": 15925, "text": "Xome" }, { "code": null, "e": 15935, "s": 15930, "text": "Tree" }, { "code": null, "e": 16033, "s": 15935, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 16065, "s": 16033, "text": "Introduction to Data Structures" }, { "code": null, "e": 16101, "s": 16065, "text": "Introduction to Tree Data Structure" }, { "code": null, "e": 16165, "s": 16101, "text": "What is Data Structure: Types, Classifications and Applications" }, { "code": null, "e": 16208, "s": 16165, "text": "Binary Tree | Set 3 (Types of Binary Tree)" }, { "code": null, "e": 16256, "s": 16208, "text": "Lowest Common Ancestor in a Binary Tree | Set 1" }, { "code": null, "e": 16289, "s": 16256, "text": "Binary Tree | Set 2 (Properties)" }, { "code": null, "e": 16315, "s": 16289, "text": "Diameter of a Binary Tree" }, { "code": null, "e": 16329, "s": 16315, "text": "Decision Tree" }, { "code": null, "e": 16363, "s": 16329, "text": "Diagonal Traversal of Binary Tree" } ]
C# | IsNullOrWhiteSpace() Method
31 Jan, 2019 In C#, IsNullOrWhiteSpace() is a string method. It is used to check whether the specified string is null or contains only white-space characters. A string will be null if it has not been assigned a value or has explicitly been assigned a value of null. Syntax: public static bool IsNullOrWhiteSpace(String str) Explanation: This method will take a parameter which is of type System.String and this method will return a boolean value. If the method’s parameter list is null or String.Empty, or only contains white-space characters then return True otherwise return False. Example: Input : str = null // initialize by null value String.IsNullOrWhiteSpace(str) Output: True Input : str = " " // initialize by whitespace String.IsNullOrWhiteSpace(str) Output: True Program: To demonstrate the working of the IsNullOrWhiteSpace() Method : // C# program to illustrate // IsNullOrWhiteSpace() Methodusing System;class Geeks { // Main Method public static void Main(string[] args) { string s1 = null; // for null value always return true bool b1 = String.IsNullOrWhiteSpace(s1); Console.WriteLine(b1); string s2 = " "; // for whitespace value always return true bool b2 = String.IsNullOrWhiteSpace(s2); Console.WriteLine(b2); string s4 = " \n "; // for new line value return true bool b4 = String.IsNullOrWhiteSpace(s4); Console.WriteLine(b4); string s5 = "\t"; // for tab value return true bool b5 = String.IsNullOrWhiteSpace(s5); Console.WriteLine(b5); string s6 = "\r"; // for carriage Return value return true bool b6 = String.IsNullOrWhiteSpace(s6); Console.WriteLine(b6); string s7 = "GFG"; // for s7 it return False bool b7 = String.IsNullOrWhiteSpace(s7); Console.WriteLine(b7); }} True True True True True False Note: There is a alternative code of IsNullOrWhiteSpace() method as follows: return String.IsNullOrEmpty(str) || str.Trim().Length == 0; Program: To demonstrate IsNullOrEmpty() method’s alternative // C# program to illustrate the // similar code for IsNullOrWhiteSpace()using System;class Geeks { // similar code to // IsNullOrWhiteSpace() public static bool check(string str) { return(String.IsNullOrEmpty(str) || str.Trim().Length == 0) ? true : false; } // Main Method public static void Main(string[] args) { string s1 = "GeeksforGeeks"; string s2 = " "; string s3 = null; string s4 = " \n "; bool b1 = check(s1); bool b2 = check(s2); bool b3 = check(s3); bool b4 = check(s4); // To display result Console.WriteLine(b1); Console.WriteLine(b2); Console.WriteLine(b3); Console.WriteLine(b4); }} False True True True Reference: https://msdn.microsoft.com/en-us/library/system.string.isnullorwhitespace CSharp-method CSharp-string C# Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n31 Jan, 2019" }, { "code": null, "e": 281, "s": 28, "text": "In C#, IsNullOrWhiteSpace() is a string method. It is used to check whether the specified string is null or contains only white-space characters. A string will be null if it has not been assigned a value or has explicitly been assigned a value of null." }, { "code": null, "e": 289, "s": 281, "text": "Syntax:" }, { "code": null, "e": 342, "s": 289, "text": "public static bool IsNullOrWhiteSpace(String str) \n" }, { "code": null, "e": 602, "s": 342, "text": "Explanation: This method will take a parameter which is of type System.String and this method will return a boolean value. If the method’s parameter list is null or String.Empty, or only contains white-space characters then return True otherwise return False." }, { "code": null, "e": 611, "s": 602, "text": "Example:" }, { "code": null, "e": 821, "s": 611, "text": "Input : str = null // initialize by null value\n String.IsNullOrWhiteSpace(str)\nOutput: True\n\nInput : str = \" \" // initialize by whitespace\n String.IsNullOrWhiteSpace(str)\nOutput: True\n" }, { "code": null, "e": 894, "s": 821, "text": "Program: To demonstrate the working of the IsNullOrWhiteSpace() Method :" }, { "code": "// C# program to illustrate // IsNullOrWhiteSpace() Methodusing System;class Geeks { // Main Method public static void Main(string[] args) { string s1 = null; // for null value always return true bool b1 = String.IsNullOrWhiteSpace(s1); Console.WriteLine(b1); string s2 = \" \"; // for whitespace value always return true bool b2 = String.IsNullOrWhiteSpace(s2); Console.WriteLine(b2); string s4 = \" \\n \"; // for new line value return true bool b4 = String.IsNullOrWhiteSpace(s4); Console.WriteLine(b4); string s5 = \"\\t\"; // for tab value return true bool b5 = String.IsNullOrWhiteSpace(s5); Console.WriteLine(b5); string s6 = \"\\r\"; // for carriage Return value return true bool b6 = String.IsNullOrWhiteSpace(s6); Console.WriteLine(b6); string s7 = \"GFG\"; // for s7 it return False bool b7 = String.IsNullOrWhiteSpace(s7); Console.WriteLine(b7); }}", "e": 1948, "s": 894, "text": null }, { "code": null, "e": 1980, "s": 1948, "text": "True\nTrue\nTrue\nTrue\nTrue\nFalse\n" }, { "code": null, "e": 2057, "s": 1980, "text": "Note: There is a alternative code of IsNullOrWhiteSpace() method as follows:" }, { "code": null, "e": 2118, "s": 2057, "text": "return String.IsNullOrEmpty(str) || str.Trim().Length == 0;\n" }, { "code": null, "e": 2179, "s": 2118, "text": "Program: To demonstrate IsNullOrEmpty() method’s alternative" }, { "code": "// C# program to illustrate the // similar code for IsNullOrWhiteSpace()using System;class Geeks { // similar code to // IsNullOrWhiteSpace() public static bool check(string str) { return(String.IsNullOrEmpty(str) || str.Trim().Length == 0) ? true : false; } // Main Method public static void Main(string[] args) { string s1 = \"GeeksforGeeks\"; string s2 = \" \"; string s3 = null; string s4 = \" \\n \"; bool b1 = check(s1); bool b2 = check(s2); bool b3 = check(s3); bool b4 = check(s4); // To display result Console.WriteLine(b1); Console.WriteLine(b2); Console.WriteLine(b3); Console.WriteLine(b4); }}", "e": 2927, "s": 2179, "text": null }, { "code": null, "e": 2949, "s": 2927, "text": "False\nTrue\nTrue\nTrue\n" }, { "code": null, "e": 3034, "s": 2949, "text": "Reference: https://msdn.microsoft.com/en-us/library/system.string.isnullorwhitespace" }, { "code": null, "e": 3048, "s": 3034, "text": "CSharp-method" }, { "code": null, "e": 3062, "s": 3048, "text": "CSharp-string" }, { "code": null, "e": 3065, "s": 3062, "text": "C#" } ]
How to clear session storage data with specified session storage item ?
22 Jan, 2021 In this article, we are going to learn how we can clear the session storage of a browser using JavaScript by getting the specified session storage item. We can achieve this by using Window sessionStorage( ) property. The Window sessionStorage() property is used for saving key/value pairs in a web browser. It stores the key/value pairs in a browser for only one session and the data expires as soon as a new session is loaded. Syntax: window.sessionStorage We can get specified session storage using the getItem() method. sessionStorage.getItem('GFG_Item') We can clear the session storage by using the clear() method. sessionStorage.clear() Example: HTML <!DOCTYPE html><html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content= "width=device-width, initial-scale=1.0"> <style> body { text-align: center; } h1 { color: green; } </style></head> <body style="text-align: center;"> <h1 style="color: green;"> GeeksforGeeks </h1> <h4> How to clear session storage data with getting the specified session storage item? </h4> <input type="text" id="text"> <button onclick="display()"> Display my item </button> <p id="display"></p> <button onclick="isEmpty()"> Checking if Empty </button> <p id="isEmpty"></p> <script> // Setting items in the local storage sessionStorage.setItem('item1', 'Kotlin'); sessionStorage.setItem('item2', 'Flutter'); sessionStorage.setItem('item3', 'React'); function display() { // Getting the text value of input field let item = document.getElementById('text').value; // Getting particular item from the // session storage let displayItem = sessionStorage.getItem(item); // Checking if key exists or not in // the session storage if (displayItem == null) // If key doesn't exist { document.getElementById('display') .innerText = 'Key does not exist'; } else { // If it exists document.getElementById('display') .innerText = displayItem; // Clearing the session storage sessionStorage.clear(); } } // Checking if session storage is empty function isEmpty() { // If session storage is empty if (sessionStorage.length == 0) document.getElementById('isEmpty') .innerText = 'It is empty'; else document.getElementById('isEmpty') .innerText = 'It is not empty'; } </script></body> </html> Output: CSS-Misc HTML-Misc JavaScript-Misc Picked CSS HTML JavaScript Web Technologies HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Design a Tribute Page using HTML & CSS How to set space between the flexbox ? Build a Survey Form using HTML and CSS Design a web page using HTML and CSS Form validation using jQuery REST API (Introduction) Hide or show elements in HTML using display property How to set the default value for an HTML <select> element ? How to set input type date in dd-mm-yyyy format using HTML ? Design a Tribute Page using HTML & CSS
[ { "code": null, "e": 28, "s": 0, "text": "\n22 Jan, 2021" }, { "code": null, "e": 181, "s": 28, "text": "In this article, we are going to learn how we can clear the session storage of a browser using JavaScript by getting the specified session storage item." }, { "code": null, "e": 456, "s": 181, "text": "We can achieve this by using Window sessionStorage( ) property. The Window sessionStorage() property is used for saving key/value pairs in a web browser. It stores the key/value pairs in a browser for only one session and the data expires as soon as a new session is loaded." }, { "code": null, "e": 464, "s": 456, "text": "Syntax:" }, { "code": null, "e": 486, "s": 464, "text": "window.sessionStorage" }, { "code": null, "e": 551, "s": 486, "text": "We can get specified session storage using the getItem() method." }, { "code": null, "e": 586, "s": 551, "text": "sessionStorage.getItem('GFG_Item')" }, { "code": null, "e": 648, "s": 586, "text": "We can clear the session storage by using the clear() method." }, { "code": null, "e": 671, "s": 648, "text": "sessionStorage.clear()" }, { "code": null, "e": 680, "s": 671, "text": "Example:" }, { "code": null, "e": 685, "s": 680, "text": "HTML" }, { "code": "<!DOCTYPE html><html lang=\"en\"> <head> <meta charset=\"UTF-8\"> <meta name=\"viewport\" content= \"width=device-width, initial-scale=1.0\"> <style> body { text-align: center; } h1 { color: green; } </style></head> <body style=\"text-align: center;\"> <h1 style=\"color: green;\"> GeeksforGeeks </h1> <h4> How to clear session storage data with getting the specified session storage item? </h4> <input type=\"text\" id=\"text\"> <button onclick=\"display()\"> Display my item </button> <p id=\"display\"></p> <button onclick=\"isEmpty()\"> Checking if Empty </button> <p id=\"isEmpty\"></p> <script> // Setting items in the local storage sessionStorage.setItem('item1', 'Kotlin'); sessionStorage.setItem('item2', 'Flutter'); sessionStorage.setItem('item3', 'React'); function display() { // Getting the text value of input field let item = document.getElementById('text').value; // Getting particular item from the // session storage let displayItem = sessionStorage.getItem(item); // Checking if key exists or not in // the session storage if (displayItem == null) // If key doesn't exist { document.getElementById('display') .innerText = 'Key does not exist'; } else { // If it exists document.getElementById('display') .innerText = displayItem; // Clearing the session storage sessionStorage.clear(); } } // Checking if session storage is empty function isEmpty() { // If session storage is empty if (sessionStorage.length == 0) document.getElementById('isEmpty') .innerText = 'It is empty'; else document.getElementById('isEmpty') .innerText = 'It is not empty'; } </script></body> </html>", "e": 2875, "s": 685, "text": null }, { "code": null, "e": 2883, "s": 2875, "text": "Output:" }, { "code": null, "e": 2892, "s": 2883, "text": "CSS-Misc" }, { "code": null, "e": 2902, "s": 2892, "text": "HTML-Misc" }, { "code": null, "e": 2918, "s": 2902, "text": "JavaScript-Misc" }, { "code": null, "e": 2925, "s": 2918, "text": "Picked" }, { "code": null, "e": 2929, "s": 2925, "text": "CSS" }, { "code": null, "e": 2934, "s": 2929, "text": "HTML" }, { "code": null, "e": 2945, "s": 2934, "text": "JavaScript" }, { "code": null, "e": 2962, "s": 2945, "text": "Web Technologies" }, { "code": null, "e": 2967, "s": 2962, "text": "HTML" }, { "code": null, "e": 3065, "s": 2967, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3104, "s": 3065, "text": "Design a Tribute Page using HTML & CSS" }, { "code": null, "e": 3143, "s": 3104, "text": "How to set space between the flexbox ?" }, { "code": null, "e": 3182, "s": 3143, "text": "Build a Survey Form using HTML and CSS" }, { "code": null, "e": 3219, "s": 3182, "text": "Design a web page using HTML and CSS" }, { "code": null, "e": 3248, "s": 3219, "text": "Form validation using jQuery" }, { "code": null, "e": 3272, "s": 3248, "text": "REST API (Introduction)" }, { "code": null, "e": 3325, "s": 3272, "text": "Hide or show elements in HTML using display property" }, { "code": null, "e": 3385, "s": 3325, "text": "How to set the default value for an HTML <select> element ?" }, { "code": null, "e": 3446, "s": 3385, "text": "How to set input type date in dd-mm-yyyy format using HTML ?" } ]
Javascript Program To Check For Balanced Brackets In An Expression (Well-Formedness) Using Stack
14 Dec, 2021 Given an expression string exp, write a program to examine whether the pairs and the orders of “{“, “}”, “(“, “)”, “[“, “]” are correct in exp. Example: Input: exp = “[()]{}{[()()]()}” Output: Balanced Input: exp = “[(])” Output: Not Balanced Algorithm: Declare a character stack S. Now traverse the expression string exp. If the current character is a starting bracket (‘(‘ or ‘{‘ or ‘[‘) then push it to stack.If the current character is a closing bracket (‘)’ or ‘}’ or ‘]’) then pop from stack and if the popped character is the matching starting bracket then fine else brackets are not balanced. If the current character is a starting bracket (‘(‘ or ‘{‘ or ‘[‘) then push it to stack.If the current character is a closing bracket (‘)’ or ‘}’ or ‘]’) then pop from stack and if the popped character is the matching starting bracket then fine else brackets are not balanced. If the current character is a starting bracket (‘(‘ or ‘{‘ or ‘[‘) then push it to stack. If the current character is a closing bracket (‘)’ or ‘}’ or ‘]’) then pop from stack and if the popped character is the matching starting bracket then fine else brackets are not balanced. After complete traversal, if there is some starting bracket left in stack then “not balanced” Below image is a dry run of the above approach: Below is the implementation of the above approach: Javascript <script> // Javascript program for checking// balanced brackets // Function to check if brackets are balancedfunction areBracketsBalanced(expr){ // Using ArrayDeque is faster // than using Stack class let stack = []; // Traversing the Expression for(let i = 0; i < expr.length; i++) { let x = expr[i]; if (x == '(' || x == '[' || x == '{') { // Push the element in the stack stack.push(x); continue; } // If current character is not opening // bracket, then it must be closing. // So stack cannot be empty at this point. if (stack.length == 0) return false; let check; switch (x){ case ')': check = stack.pop(); if (check == '{' || check == '[') return false; break; case '}': check = stack.pop(); if (check == '(' || check == '[') return false; break; case ']': check = stack.pop(); if (check == '(' || check == '{') return false; break; } } // Check Empty Stack return (stack.length == 0);} // Driver codelet expr = "([{}])"; // Function callif (areBracketsBalanced(expr)) document.write("Balanced ");else document.write("Not Balanced "); // This code is contributed by rag2127 </script> Balanced Time Complexity: O(n) Auxiliary Space: O(n) for stack. Please refer complete article on Check for Balanced Brackets in an expression (well-formedness) using Stack for more details! Amazon Hike Oracle Parentheses-Problems Snapdeal Walmart Wipro Yatra.com Zoho Stack Strings Zoho Amazon Snapdeal Hike Oracle Walmart Wipro Yatra.com Strings Stack Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Introduction to Data Structures What is Data Structure: Types, Classifications and Applications Design a stack with operations on middle element How to efficiently implement k stacks in a single array? Real-time application of Data Structures Write a program to reverse an array or string Reverse a string in Java Write a program to print all permutations of a given string C++ Data Types Different Methods to Reverse a String in C++
[ { "code": null, "e": 28, "s": 0, "text": "\n14 Dec, 2021" }, { "code": null, "e": 172, "s": 28, "text": "Given an expression string exp, write a program to examine whether the pairs and the orders of “{“, “}”, “(“, “)”, “[“, “]” are correct in exp." }, { "code": null, "e": 182, "s": 172, "text": "Example: " }, { "code": null, "e": 231, "s": 182, "text": "Input: exp = “[()]{}{[()()]()}” Output: Balanced" }, { "code": null, "e": 273, "s": 231, "text": "Input: exp = “[(])” Output: Not Balanced " }, { "code": null, "e": 285, "s": 273, "text": "Algorithm: " }, { "code": null, "e": 314, "s": 285, "text": "Declare a character stack S." }, { "code": null, "e": 632, "s": 314, "text": "Now traverse the expression string exp. If the current character is a starting bracket (‘(‘ or ‘{‘ or ‘[‘) then push it to stack.If the current character is a closing bracket (‘)’ or ‘}’ or ‘]’) then pop from stack and if the popped character is the matching starting bracket then fine else brackets are not balanced." }, { "code": null, "e": 910, "s": 632, "text": "If the current character is a starting bracket (‘(‘ or ‘{‘ or ‘[‘) then push it to stack.If the current character is a closing bracket (‘)’ or ‘}’ or ‘]’) then pop from stack and if the popped character is the matching starting bracket then fine else brackets are not balanced." }, { "code": null, "e": 1000, "s": 910, "text": "If the current character is a starting bracket (‘(‘ or ‘{‘ or ‘[‘) then push it to stack." }, { "code": null, "e": 1189, "s": 1000, "text": "If the current character is a closing bracket (‘)’ or ‘}’ or ‘]’) then pop from stack and if the popped character is the matching starting bracket then fine else brackets are not balanced." }, { "code": null, "e": 1283, "s": 1189, "text": "After complete traversal, if there is some starting bracket left in stack then “not balanced”" }, { "code": null, "e": 1331, "s": 1283, "text": "Below image is a dry run of the above approach:" }, { "code": null, "e": 1382, "s": 1331, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 1393, "s": 1382, "text": "Javascript" }, { "code": "<script> // Javascript program for checking// balanced brackets // Function to check if brackets are balancedfunction areBracketsBalanced(expr){ // Using ArrayDeque is faster // than using Stack class let stack = []; // Traversing the Expression for(let i = 0; i < expr.length; i++) { let x = expr[i]; if (x == '(' || x == '[' || x == '{') { // Push the element in the stack stack.push(x); continue; } // If current character is not opening // bracket, then it must be closing. // So stack cannot be empty at this point. if (stack.length == 0) return false; let check; switch (x){ case ')': check = stack.pop(); if (check == '{' || check == '[') return false; break; case '}': check = stack.pop(); if (check == '(' || check == '[') return false; break; case ']': check = stack.pop(); if (check == '(' || check == '{') return false; break; } } // Check Empty Stack return (stack.length == 0);} // Driver codelet expr = \"([{}])\"; // Function callif (areBracketsBalanced(expr)) document.write(\"Balanced \");else document.write(\"Not Balanced \"); // This code is contributed by rag2127 </script>", "e": 2855, "s": 1393, "text": null }, { "code": null, "e": 2864, "s": 2855, "text": "Balanced" }, { "code": null, "e": 2920, "s": 2864, "text": "Time Complexity: O(n) Auxiliary Space: O(n) for stack. " }, { "code": null, "e": 3046, "s": 2920, "text": "Please refer complete article on Check for Balanced Brackets in an expression (well-formedness) using Stack for more details!" }, { "code": null, "e": 3053, "s": 3046, "text": "Amazon" }, { "code": null, "e": 3058, "s": 3053, "text": "Hike" }, { "code": null, "e": 3065, "s": 3058, "text": "Oracle" }, { "code": null, "e": 3086, "s": 3065, "text": "Parentheses-Problems" }, { "code": null, "e": 3095, "s": 3086, "text": "Snapdeal" }, { "code": null, "e": 3103, "s": 3095, "text": "Walmart" }, { "code": null, "e": 3109, "s": 3103, "text": "Wipro" }, { "code": null, "e": 3119, "s": 3109, "text": "Yatra.com" }, { "code": null, "e": 3124, "s": 3119, "text": "Zoho" }, { "code": null, "e": 3130, "s": 3124, "text": "Stack" }, { "code": null, "e": 3138, "s": 3130, "text": "Strings" }, { "code": null, "e": 3143, "s": 3138, "text": "Zoho" }, { "code": null, "e": 3150, "s": 3143, "text": "Amazon" }, { "code": null, "e": 3159, "s": 3150, "text": "Snapdeal" }, { "code": null, "e": 3164, "s": 3159, "text": "Hike" }, { "code": null, "e": 3171, "s": 3164, "text": "Oracle" }, { "code": null, "e": 3179, "s": 3171, "text": "Walmart" }, { "code": null, "e": 3185, "s": 3179, "text": "Wipro" }, { "code": null, "e": 3195, "s": 3185, "text": "Yatra.com" }, { "code": null, "e": 3203, "s": 3195, "text": "Strings" }, { "code": null, "e": 3209, "s": 3203, "text": "Stack" }, { "code": null, "e": 3307, "s": 3209, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3339, "s": 3307, "text": "Introduction to Data Structures" }, { "code": null, "e": 3403, "s": 3339, "text": "What is Data Structure: Types, Classifications and Applications" }, { "code": null, "e": 3452, "s": 3403, "text": "Design a stack with operations on middle element" }, { "code": null, "e": 3509, "s": 3452, "text": "How to efficiently implement k stacks in a single array?" }, { "code": null, "e": 3550, "s": 3509, "text": "Real-time application of Data Structures" }, { "code": null, "e": 3596, "s": 3550, "text": "Write a program to reverse an array or string" }, { "code": null, "e": 3621, "s": 3596, "text": "Reverse a string in Java" }, { "code": null, "e": 3681, "s": 3621, "text": "Write a program to print all permutations of a given string" }, { "code": null, "e": 3696, "s": 3681, "text": "C++ Data Types" } ]
JavaScript Course | Task Tracker Project
13 Jun, 2022 Previous article: JavaScript Course | Objects in JavaScriptProject Introduction In this final article of this course, we will learn how to make a simple javascript application where we can add tasks, delete tasks and edit them too. Pure(Vanilla) JavaScript has been used and we will also make use of DOM manipulation a lot so one of the main prerequisites is HTML | DOM. Project Structure index.html styles.css list.js index.html HTML <!DOCTYPE html><html><head> <title>Task Tracker</title> <link rel="stylesheet" href="styles.css" type="text/css" media="screen" charset="utf-8"></head> <body> <div class="container"> <p> <label for="new-task" class="middle">Add Task</label> <input id="new-task" type="text"><button>Add Task</button> </p> <h3 class="middle">Todo</h3> <ul id="incomplete-tasks"> </ul> <h3 class="middle">Completed Tasks</h3> <ul id="completed-tasks"> </ul> </div> <script type="text/javascript" src="list.js"></script> </body> </html> Explanation: The above HTML code contains simple list tags and one text field which we will populate with text when we add, delete tasks. Certain classes are assigned which we make use of while getting that particular element by DOM or by styling it inside the styles.css file. All the above content is inside a div with class ‘container’ that has its own styling and attributes. styles.css CSS /* Basic Style */body { background: #ecf0f1; color: #333; font-family: Lato, sans-serif;} .container { display: block; width: 500px; margin: 50px auto 0;} ul { margin: 0; padding: 0;} li * { float: left;} li,h3 { clear: both; list-style: none;} input,button { outline: none;} button { background: none; border: 0px; color: #888; font-size: 15px; width: 100px; margin: 10px 0 0; font-family: Lato, sans-serif; cursor: pointer;} button:hover { color: #333;} /* Heading */h3,label[for='new-task'] { color: #333; font-weight: 700; font-size: 15px; border-bottom: 2px solid #333; padding: 30px 0 10px; margin: 0; text-transform: uppercase;} input[type="text"] { margin: 0; font-size: 18px; line-height: 18px; height: 18px; padding: 10px; border: 1px solid #ddd; background: #fff; border-radius: 6px; font-family: Lato, sans-serif; color: #888;} input[type="text"]:focus { color: #333;} .middle { text-align: center;} /* New Task */label[for='new-task'] { display: block; margin: 0 0 20px;} input#new-task { float: right; width: 318px;} p>button:hover { color: #0FC57C;} /* Task list */li { overflow: hidden; padding: 20px 0; border-bottom: 1px solid #eee;} li>input[type="checkbox"] { margin: 0 10px; position: relative; top: 15px;} li>label { font-size: 18px; line-height: 40px; width: 237px; padding: 0 0 0 11px;} li>input[type="text"] { width: 226px;} li>.delete:hover { color: #CF2323;} /* Completed */#completed-tasks label { text-decoration: line-through; color: #888;} /* Edit Task */ul li input[type=text] { display: none;} ul li.editMode input[type=text] { display: block;} ul li.editMode label { display: none;} Note: The above HTML and CSS files are for the presentation part mainly. list.js Javascript // Add a new task.let taskInput = document.getElementById("new-task"); // first buttonlet addButton = document.getElementsByTagName("button")[0]; // ul of #incomplete-taskslet incompleteTaskHolder = document.getElementById("incomplete-tasks"); // completed-taskslet completedTasksHolder = document.getElementById("completed-tasks"); /*---- Part 1 ----*/// function to create new task itemlet createNewTaskElement = function (taskString) { let listItem = document.createElement("li"); // input (checkbox) let checkBox = document.createElement("input"); // checkbox // label let label = document.createElement("label"); // label // input (text) let editInput = document.createElement("input"); // text // button.edit let editButton = document.createElement("button"); // edit button // button.delete let deleteButton = document.createElement("button"); // delete button label.innerText = taskString; // Each elements, needs appending checkBox.type = "checkbox"; editInput.type = "text"; // innerText encodes special characters, HTML does not. editButton.innerText = "Edit"; editButton.className = "edit"; deleteButton.innerText = "Delete"; deleteButton.className = "delete"; // and appending. listItem.appendChild(checkBox); listItem.appendChild(label); listItem.appendChild(editInput); listItem.appendChild(editButton); listItem.appendChild(deleteButton); return listItem;}/*---- Part 2 ----*/let addTask = function () { console.log("Add Task..."); let listItem = createNewTaskElement(taskInput.value); if (taskInput.value == "") { return; } // Append listItem to incompleteTaskHolder incompleteTaskHolder.appendChild(listItem); bindTaskEvents(listItem, taskCompleted); taskInput.value = ""; } /*---- Part 3 ----*/let editTask = function () { console.log("Edit Task..."); console.log("Change 'edit' to 'save'"); let listItem = this.parentNode; let editInput = listItem.querySelector('input[type=text]'); let label = listItem.querySelector("label"); let containsClass = listItem.classList.contains("editMode"); // If class of the parent is .editmode if (containsClass) { label.innerText = editInput.value; } else { editInput.value = label.innerText; } listItem.classList.toggle("editMode");} /*---- Part 4 ----*/let deleteTask = function () { console.log("Delete Task..."); let listItem = this.parentNode; let ul = listItem.parentNode; // Remove the parent list item from the ul. ul.removeChild(listItem); } /*---- Part 5 ----*/ let taskCompleted = function () { console.log("Complete Task..."); // Append the task list item to the #completed-tasks let listItem = this.parentNode; completedTasksHolder.appendChild(listItem); bindTaskEvents(listItem, taskIncomplete); } /*---- Part 6 ----*/let taskIncomplete = function () { console.log("Incomplete Task..."); // Mark task as incomplete. let listItem = this.parentNode; incompleteTaskHolder.appendChild(listItem); bindTaskEvents(listItem, taskCompleted);} /*---- Part 7 ----*/addButton.onclick = addTask;addButton.addEventListener("click", addTask); let bindTaskEvents = function (taskListItem, checkBoxEventHandler) { console.log("bind list item events"); // select ListItems children let checkBox = taskListItem.querySelector("input[type=checkbox]"); let editButton = taskListItem.querySelector("button.edit"); let deleteButton = taskListItem.querySelector("button.delete"); // Bind editTask to edit button. editButton.onclick = editTask; // Bind deleteTask to delete button. deleteButton.onclick = deleteTask; // Bind taskCompleted to checkBoxEventHandler. checkBox.onchange = checkBoxEventHandler;} /*---- Part 8 ----*/// cycle over incompleteTaskHolder ul list items// for each list itemfor (let i = 0; i < incompleteTaskHolder.children.length; i++) { // bind events to list items children(tasksCompleted) bindTaskEvents(incompleteTaskHolder.children[i], taskCompleted);} // cycle over completedTasksHolder ul list itemsfor (let i = 0; i < completedTasksHolder.children.length; i++) { // bind events to list items children(tasksIncompleted) bindTaskEvents(completedTasksHolder.children[i], taskIncomplete);} Explanation Part 1 The way this function works is that it takes the ‘inputString’ i.e the text that we pass inside the HTML text field as a task and then it creates several elements using DOM properties and append them specific classes. After appending we insert all the elements inside the list as listItems.Part 2 This addTask function is called when we click the button ‘addButton'(line 115) and then inside it we create a listItem with the value the user entered and then check the value, as it must not be an empty string then we simply add the above value inside the ‘inputTaskHolder’ and finally setting the value inside it as an empty string before calling the ‘bindFunction’. Part 3 This code function is used to edit an existing task and we do so keeping track of the parent node and then a simple if-else check that whether the ‘editMode’ button is clicked or not, if clicked then simply assign the value of the label innerText to value inside the editInput, if not then vice versa. Then after editing, we toggle the value of the ‘editMode’ as we have edited. Part 4 In this part we delete a task and the way we do it by making use of the parent node of the current node and then storing the parent of the parent node and then simply deleting the child of this node. Part 5 In this function we mark the task as complete by simply appending the child of the parent node inside the completeTaskHolder element and then calling the bindFunction. Part 6 In this function we mark the task as incomplete by simply appending the child of the parent node inside the inCompleteTaskHolder element and then calling the bindFunction. Part 7 In this part we call the BindFunction where we respond to the several user interaction activities and make several buttons work. Part 8 In this final section we iterate over several parts binding children with the help of for loop inside the incomplete and complete TaskHolder element. Part 1 The way this function works is that it takes the ‘inputString’ i.e the text that we pass inside the HTML text field as a task and then it creates several elements using DOM properties and append them specific classes. After appending we insert all the elements inside the list as listItems. The way this function works is that it takes the ‘inputString’ i.e the text that we pass inside the HTML text field as a task and then it creates several elements using DOM properties and append them specific classes. After appending we insert all the elements inside the list as listItems. Part 2 This addTask function is called when we click the button ‘addButton'(line 115) and then inside it we create a listItem with the value the user entered and then check the value, as it must not be an empty string then we simply add the above value inside the ‘inputTaskHolder’ and finally setting the value inside it as an empty string before calling the ‘bindFunction’. This addTask function is called when we click the button ‘addButton'(line 115) and then inside it we create a listItem with the value the user entered and then check the value, as it must not be an empty string then we simply add the above value inside the ‘inputTaskHolder’ and finally setting the value inside it as an empty string before calling the ‘bindFunction’. Part 3 This code function is used to edit an existing task and we do so keeping track of the parent node and then a simple if-else check that whether the ‘editMode’ button is clicked or not, if clicked then simply assign the value of the label innerText to value inside the editInput, if not then vice versa. Then after editing, we toggle the value of the ‘editMode’ as we have edited. This code function is used to edit an existing task and we do so keeping track of the parent node and then a simple if-else check that whether the ‘editMode’ button is clicked or not, if clicked then simply assign the value of the label innerText to value inside the editInput, if not then vice versa. Then after editing, we toggle the value of the ‘editMode’ as we have edited. Part 4 In this part we delete a task and the way we do it by making use of the parent node of the current node and then storing the parent of the parent node and then simply deleting the child of this node. In this part we delete a task and the way we do it by making use of the parent node of the current node and then storing the parent of the parent node and then simply deleting the child of this node. Part 5 In this function we mark the task as complete by simply appending the child of the parent node inside the completeTaskHolder element and then calling the bindFunction. In this function we mark the task as complete by simply appending the child of the parent node inside the completeTaskHolder element and then calling the bindFunction. Part 6 In this function we mark the task as incomplete by simply appending the child of the parent node inside the inCompleteTaskHolder element and then calling the bindFunction. In this function we mark the task as incomplete by simply appending the child of the parent node inside the inCompleteTaskHolder element and then calling the bindFunction. Part 7 In this part we call the BindFunction where we respond to the several user interaction activities and make several buttons work. In this part we call the BindFunction where we respond to the several user interaction activities and make several buttons work. Part 8 In this final section we iterate over several parts binding children with the help of for loop inside the incomplete and complete TaskHolder element. In this final section we iterate over several parts binding children with the help of for loop inside the incomplete and complete TaskHolder element. Output:(Before adding any task) Output:(After adding task) Output:(After Completing the task) Next article: JavaScript Course | Practice Quiz-3 sagar0719kumar gabaa406 vinayedula JavaScript-Course 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": 52, "s": 24, "text": "\n13 Jun, 2022" }, { "code": null, "e": 424, "s": 52, "text": "Previous article: JavaScript Course | Objects in JavaScriptProject Introduction In this final article of this course, we will learn how to make a simple javascript application where we can add tasks, delete tasks and edit them too. Pure(Vanilla) JavaScript has been used and we will also make use of DOM manipulation a lot so one of the main prerequisites is HTML | DOM. " }, { "code": null, "e": 443, "s": 424, "text": "Project Structure " }, { "code": null, "e": 473, "s": 443, "text": "index.html styles.css list.js" }, { "code": null, "e": 485, "s": 473, "text": "index.html " }, { "code": null, "e": 490, "s": 485, "text": "HTML" }, { "code": "<!DOCTYPE html><html><head> <title>Task Tracker</title> <link rel=\"stylesheet\" href=\"styles.css\" type=\"text/css\" media=\"screen\" charset=\"utf-8\"></head> <body> <div class=\"container\"> <p> <label for=\"new-task\" class=\"middle\">Add Task</label> <input id=\"new-task\" type=\"text\"><button>Add Task</button> </p> <h3 class=\"middle\">Todo</h3> <ul id=\"incomplete-tasks\"> </ul> <h3 class=\"middle\">Completed Tasks</h3> <ul id=\"completed-tasks\"> </ul> </div> <script type=\"text/javascript\" src=\"list.js\"></script> </body> </html>", "e": 1054, "s": 490, "text": null }, { "code": null, "e": 1436, "s": 1054, "text": "Explanation: The above HTML code contains simple list tags and one text field which we will populate with text when we add, delete tasks. Certain classes are assigned which we make use of while getting that particular element by DOM or by styling it inside the styles.css file. All the above content is inside a div with class ‘container’ that has its own styling and attributes. " }, { "code": null, "e": 1448, "s": 1436, "text": "styles.css " }, { "code": null, "e": 1452, "s": 1448, "text": "CSS" }, { "code": "/* Basic Style */body { background: #ecf0f1; color: #333; font-family: Lato, sans-serif;} .container { display: block; width: 500px; margin: 50px auto 0;} ul { margin: 0; padding: 0;} li * { float: left;} li,h3 { clear: both; list-style: none;} input,button { outline: none;} button { background: none; border: 0px; color: #888; font-size: 15px; width: 100px; margin: 10px 0 0; font-family: Lato, sans-serif; cursor: pointer;} button:hover { color: #333;} /* Heading */h3,label[for='new-task'] { color: #333; font-weight: 700; font-size: 15px; border-bottom: 2px solid #333; padding: 30px 0 10px; margin: 0; text-transform: uppercase;} input[type=\"text\"] { margin: 0; font-size: 18px; line-height: 18px; height: 18px; padding: 10px; border: 1px solid #ddd; background: #fff; border-radius: 6px; font-family: Lato, sans-serif; color: #888;} input[type=\"text\"]:focus { color: #333;} .middle { text-align: center;} /* New Task */label[for='new-task'] { display: block; margin: 0 0 20px;} input#new-task { float: right; width: 318px;} p>button:hover { color: #0FC57C;} /* Task list */li { overflow: hidden; padding: 20px 0; border-bottom: 1px solid #eee;} li>input[type=\"checkbox\"] { margin: 0 10px; position: relative; top: 15px;} li>label { font-size: 18px; line-height: 40px; width: 237px; padding: 0 0 0 11px;} li>input[type=\"text\"] { width: 226px;} li>.delete:hover { color: #CF2323;} /* Completed */#completed-tasks label { text-decoration: line-through; color: #888;} /* Edit Task */ul li input[type=text] { display: none;} ul li.editMode input[type=text] { display: block;} ul li.editMode label { display: none;}", "e": 3132, "s": 1452, "text": null }, { "code": null, "e": 3206, "s": 3132, "text": "Note: The above HTML and CSS files are for the presentation part mainly. " }, { "code": null, "e": 3215, "s": 3206, "text": "list.js " }, { "code": null, "e": 3226, "s": 3215, "text": "Javascript" }, { "code": "// Add a new task.let taskInput = document.getElementById(\"new-task\"); // first buttonlet addButton = document.getElementsByTagName(\"button\")[0]; // ul of #incomplete-taskslet incompleteTaskHolder = document.getElementById(\"incomplete-tasks\"); // completed-taskslet completedTasksHolder = document.getElementById(\"completed-tasks\"); /*---- Part 1 ----*/// function to create new task itemlet createNewTaskElement = function (taskString) { let listItem = document.createElement(\"li\"); // input (checkbox) let checkBox = document.createElement(\"input\"); // checkbox // label let label = document.createElement(\"label\"); // label // input (text) let editInput = document.createElement(\"input\"); // text // button.edit let editButton = document.createElement(\"button\"); // edit button // button.delete let deleteButton = document.createElement(\"button\"); // delete button label.innerText = taskString; // Each elements, needs appending checkBox.type = \"checkbox\"; editInput.type = \"text\"; // innerText encodes special characters, HTML does not. editButton.innerText = \"Edit\"; editButton.className = \"edit\"; deleteButton.innerText = \"Delete\"; deleteButton.className = \"delete\"; // and appending. listItem.appendChild(checkBox); listItem.appendChild(label); listItem.appendChild(editInput); listItem.appendChild(editButton); listItem.appendChild(deleteButton); return listItem;}/*---- Part 2 ----*/let addTask = function () { console.log(\"Add Task...\"); let listItem = createNewTaskElement(taskInput.value); if (taskInput.value == \"\") { return; } // Append listItem to incompleteTaskHolder incompleteTaskHolder.appendChild(listItem); bindTaskEvents(listItem, taskCompleted); taskInput.value = \"\"; } /*---- Part 3 ----*/let editTask = function () { console.log(\"Edit Task...\"); console.log(\"Change 'edit' to 'save'\"); let listItem = this.parentNode; let editInput = listItem.querySelector('input[type=text]'); let label = listItem.querySelector(\"label\"); let containsClass = listItem.classList.contains(\"editMode\"); // If class of the parent is .editmode if (containsClass) { label.innerText = editInput.value; } else { editInput.value = label.innerText; } listItem.classList.toggle(\"editMode\");} /*---- Part 4 ----*/let deleteTask = function () { console.log(\"Delete Task...\"); let listItem = this.parentNode; let ul = listItem.parentNode; // Remove the parent list item from the ul. ul.removeChild(listItem); } /*---- Part 5 ----*/ let taskCompleted = function () { console.log(\"Complete Task...\"); // Append the task list item to the #completed-tasks let listItem = this.parentNode; completedTasksHolder.appendChild(listItem); bindTaskEvents(listItem, taskIncomplete); } /*---- Part 6 ----*/let taskIncomplete = function () { console.log(\"Incomplete Task...\"); // Mark task as incomplete. let listItem = this.parentNode; incompleteTaskHolder.appendChild(listItem); bindTaskEvents(listItem, taskCompleted);} /*---- Part 7 ----*/addButton.onclick = addTask;addButton.addEventListener(\"click\", addTask); let bindTaskEvents = function (taskListItem, checkBoxEventHandler) { console.log(\"bind list item events\"); // select ListItems children let checkBox = taskListItem.querySelector(\"input[type=checkbox]\"); let editButton = taskListItem.querySelector(\"button.edit\"); let deleteButton = taskListItem.querySelector(\"button.delete\"); // Bind editTask to edit button. editButton.onclick = editTask; // Bind deleteTask to delete button. deleteButton.onclick = deleteTask; // Bind taskCompleted to checkBoxEventHandler. checkBox.onchange = checkBoxEventHandler;} /*---- Part 8 ----*/// cycle over incompleteTaskHolder ul list items// for each list itemfor (let i = 0; i < incompleteTaskHolder.children.length; i++) { // bind events to list items children(tasksCompleted) bindTaskEvents(incompleteTaskHolder.children[i], taskCompleted);} // cycle over completedTasksHolder ul list itemsfor (let i = 0; i < completedTasksHolder.children.length; i++) { // bind events to list items children(tasksIncompleted) bindTaskEvents(completedTasksHolder.children[i], taskIncomplete);}", "e": 7591, "s": 3226, "text": null }, { "code": null, "e": 7604, "s": 7591, "text": "Explanation " }, { "code": null, "e": 9524, "s": 7604, "text": "Part 1 The way this function works is that it takes the ‘inputString’ i.e the text that we pass inside the HTML text field as a task and then it creates several elements using DOM properties and append them specific classes. After appending we insert all the elements inside the list as listItems.Part 2 This addTask function is called when we click the button ‘addButton'(line 115) and then inside it we create a listItem with the value the user entered and then check the value, as it must not be an empty string then we simply add the above value inside the ‘inputTaskHolder’ and finally setting the value inside it as an empty string before calling the ‘bindFunction’. Part 3 This code function is used to edit an existing task and we do so keeping track of the parent node and then a simple if-else check that whether the ‘editMode’ button is clicked or not, if clicked then simply assign the value of the label innerText to value inside the editInput, if not then vice versa. Then after editing, we toggle the value of the ‘editMode’ as we have edited. Part 4 In this part we delete a task and the way we do it by making use of the parent node of the current node and then storing the parent of the parent node and then simply deleting the child of this node. Part 5 In this function we mark the task as complete by simply appending the child of the parent node inside the completeTaskHolder element and then calling the bindFunction. Part 6 In this function we mark the task as incomplete by simply appending the child of the parent node inside the inCompleteTaskHolder element and then calling the bindFunction. Part 7 In this part we call the BindFunction where we respond to the several user interaction activities and make several buttons work. Part 8 In this final section we iterate over several parts binding children with the help of for loop inside the incomplete and complete TaskHolder element. " }, { "code": null, "e": 9822, "s": 9524, "text": "Part 1 The way this function works is that it takes the ‘inputString’ i.e the text that we pass inside the HTML text field as a task and then it creates several elements using DOM properties and append them specific classes. After appending we insert all the elements inside the list as listItems." }, { "code": null, "e": 10113, "s": 9822, "text": "The way this function works is that it takes the ‘inputString’ i.e the text that we pass inside the HTML text field as a task and then it creates several elements using DOM properties and append them specific classes. After appending we insert all the elements inside the list as listItems." }, { "code": null, "e": 10491, "s": 10113, "text": "Part 2 This addTask function is called when we click the button ‘addButton'(line 115) and then inside it we create a listItem with the value the user entered and then check the value, as it must not be an empty string then we simply add the above value inside the ‘inputTaskHolder’ and finally setting the value inside it as an empty string before calling the ‘bindFunction’. " }, { "code": null, "e": 10862, "s": 10491, "text": "This addTask function is called when we click the button ‘addButton'(line 115) and then inside it we create a listItem with the value the user entered and then check the value, as it must not be an empty string then we simply add the above value inside the ‘inputTaskHolder’ and finally setting the value inside it as an empty string before calling the ‘bindFunction’. " }, { "code": null, "e": 11250, "s": 10862, "text": "Part 3 This code function is used to edit an existing task and we do so keeping track of the parent node and then a simple if-else check that whether the ‘editMode’ button is clicked or not, if clicked then simply assign the value of the label innerText to value inside the editInput, if not then vice versa. Then after editing, we toggle the value of the ‘editMode’ as we have edited. " }, { "code": null, "e": 11631, "s": 11250, "text": "This code function is used to edit an existing task and we do so keeping track of the parent node and then a simple if-else check that whether the ‘editMode’ button is clicked or not, if clicked then simply assign the value of the label innerText to value inside the editInput, if not then vice versa. Then after editing, we toggle the value of the ‘editMode’ as we have edited. " }, { "code": null, "e": 11840, "s": 11631, "text": "Part 4 In this part we delete a task and the way we do it by making use of the parent node of the current node and then storing the parent of the parent node and then simply deleting the child of this node. " }, { "code": null, "e": 12042, "s": 11840, "text": "In this part we delete a task and the way we do it by making use of the parent node of the current node and then storing the parent of the parent node and then simply deleting the child of this node. " }, { "code": null, "e": 12219, "s": 12042, "text": "Part 5 In this function we mark the task as complete by simply appending the child of the parent node inside the completeTaskHolder element and then calling the bindFunction. " }, { "code": null, "e": 12389, "s": 12219, "text": "In this function we mark the task as complete by simply appending the child of the parent node inside the completeTaskHolder element and then calling the bindFunction. " }, { "code": null, "e": 12570, "s": 12389, "text": "Part 6 In this function we mark the task as incomplete by simply appending the child of the parent node inside the inCompleteTaskHolder element and then calling the bindFunction. " }, { "code": null, "e": 12744, "s": 12570, "text": "In this function we mark the task as incomplete by simply appending the child of the parent node inside the inCompleteTaskHolder element and then calling the bindFunction. " }, { "code": null, "e": 12882, "s": 12744, "text": "Part 7 In this part we call the BindFunction where we respond to the several user interaction activities and make several buttons work. " }, { "code": null, "e": 13013, "s": 12882, "text": "In this part we call the BindFunction where we respond to the several user interaction activities and make several buttons work. " }, { "code": null, "e": 13171, "s": 13013, "text": "Part 8 In this final section we iterate over several parts binding children with the help of for loop inside the incomplete and complete TaskHolder element. " }, { "code": null, "e": 13322, "s": 13171, "text": "In this final section we iterate over several parts binding children with the help of for loop inside the incomplete and complete TaskHolder element. " }, { "code": null, "e": 13355, "s": 13322, "text": "Output:(Before adding any task) " }, { "code": null, "e": 13383, "s": 13355, "text": "Output:(After adding task) " }, { "code": null, "e": 13419, "s": 13383, "text": "Output:(After Completing the task) " }, { "code": null, "e": 13470, "s": 13419, "text": "Next article: JavaScript Course | Practice Quiz-3 " }, { "code": null, "e": 13485, "s": 13470, "text": "sagar0719kumar" }, { "code": null, "e": 13494, "s": 13485, "text": "gabaa406" }, { "code": null, "e": 13505, "s": 13494, "text": "vinayedula" }, { "code": null, "e": 13523, "s": 13505, "text": "JavaScript-Course" }, { "code": null, "e": 13534, "s": 13523, "text": "JavaScript" }, { "code": null, "e": 13551, "s": 13534, "text": "Web Technologies" }, { "code": null, "e": 13649, "s": 13551, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 13710, "s": 13649, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 13782, "s": 13710, "text": "Differences between Functional Components and Class Components in React" }, { "code": null, "e": 13822, "s": 13782, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 13874, "s": 13822, "text": "How to append HTML code to a div using JavaScript ?" }, { "code": null, "e": 13915, "s": 13874, "text": "Difference Between PUT and PATCH Request" }, { "code": null, "e": 13977, "s": 13915, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 14010, "s": 13977, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 14071, "s": 14010, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 14121, "s": 14071, "text": "How to insert spaces/tabs in text using HTML/CSS?" } ]
Introduction to XPath
11 May, 2022 XPath(XML Path) is an expression which is used to find the element or say node in the XML document. In Selenium it is commonly used to find the web elements. Example: //input[@id = 'fakebox-input'] In this example, We are locating the ‘input’ element whose ‘id’ is equal to ‘fakebox-input’ XML Code: html <?xml version="1.0" encoding="UTF-8"?><bookstore> <book category = "Math"> <title lang="en">IIT Mathematics</title> <author>A Das Gupta</author> </book> <book category = "Chemistry"> <title lang="en"> Inorganic chemistry for JEE</title> <author>V K Jaiswal</author> </book> </bookstore> The XML Code is a tree like structure as we can see in the above XML, the code starts with the bookstore node that has a child node book and it is followed by an attribute category whose value is ‘Math’. The book node has 2 child node i.e. title and author. To select the author element of the chemistry book, the following XPath will be used: /bookstore/book[@category='Chemistry']/author Syntax of XPath: //tagname[@attribute = ‘value’] XPath Expressions: Types of XPath: Absolute XPath Relative Xpath Absolute XPath: Absolute XPath uses the root element of the HTML/XML code and followed by all the elements which are necessary to reach the desired element. It starts with the forward slash ‘/’ . Generally, Absolute XPath is not recommended because in future any of the web element when added or removed then Absolute XPath changes. Example: /html[1]/body[1]/div[6]/div[1]/div[3]/div[1]/div[1]/div[1]/div[3]/ul[1]/li[2]/a[1] Relative XPath; In this, XPath begins with the double forward slash ‘//’ which means it can search the element anywhere in the Webpage. Generally Relative Xpath is preferred as they are not complete path from Root node. Example: //input[@id = 'fakebox-input'] If you want to learn how to make XPath identify webelements, Then open the webpage in chrome browser and inspect the element by right click on the webpage and after that press ‘ctrl+f’ to find the webelements using XPath. You can also use the chrome extension like ‘chropath’ to find the xpath for a webelement. Commonly Used XPath Functions: contains() Start-With() Text() contains(): This Function is used to select the node whose specified attribute value contains the specified string provided in the function argument. Example: //input[contains(@id, 'fakebox')] starts-with(): This function is used to select the node whose specified attribute value starts with the specified string value provided in the function arguments. Example: //input[starts-with(@id, 'fakebox')] text(): This function is used to find the node having the exact match with the specified string value in the function. Example: //div Uses of AND and OR in XPath AND and OR are used to combine two or more conditions to find the node. Example: //input[@value = 'Log In' or @type = 'submit'] Similarly, We can apply AND operator in XPath. mitalibhola94 HTML and XML selenium 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": "\n11 May, 2022" }, { "code": null, "e": 195, "s": 28, "text": "XPath(XML Path) is an expression which is used to find the element or say node in the XML document. In Selenium it is commonly used to find the web elements. Example:" }, { "code": null, "e": 226, "s": 195, "text": "//input[@id = 'fakebox-input']" }, { "code": null, "e": 330, "s": 226, "text": "In this example, We are locating the ‘input’ element whose ‘id’ is equal to ‘fakebox-input’ XML Code: " }, { "code": null, "e": 335, "s": 330, "text": "html" }, { "code": "<?xml version=\"1.0\" encoding=\"UTF-8\"?><bookstore> <book category = \"Math\"> <title lang=\"en\">IIT Mathematics</title> <author>A Das Gupta</author> </book> <book category = \"Chemistry\"> <title lang=\"en\"> Inorganic chemistry for JEE</title> <author>V K Jaiswal</author> </book> </bookstore>", "e": 643, "s": 335, "text": null }, { "code": null, "e": 987, "s": 643, "text": "The XML Code is a tree like structure as we can see in the above XML, the code starts with the bookstore node that has a child node book and it is followed by an attribute category whose value is ‘Math’. The book node has 2 child node i.e. title and author. To select the author element of the chemistry book, the following XPath will be used:" }, { "code": null, "e": 1033, "s": 987, "text": "/bookstore/book[@category='Chemistry']/author" }, { "code": null, "e": 1050, "s": 1033, "text": "Syntax of XPath:" }, { "code": null, "e": 1082, "s": 1050, "text": "//tagname[@attribute = ‘value’]" }, { "code": null, "e": 1101, "s": 1082, "text": "XPath Expressions:" }, { "code": null, "e": 1117, "s": 1101, "text": "Types of XPath:" }, { "code": null, "e": 1132, "s": 1117, "text": "Absolute XPath" }, { "code": null, "e": 1147, "s": 1132, "text": "Relative Xpath" }, { "code": null, "e": 1480, "s": 1147, "text": "Absolute XPath: Absolute XPath uses the root element of the HTML/XML code and followed by all the elements which are necessary to reach the desired element. It starts with the forward slash ‘/’ . Generally, Absolute XPath is not recommended because in future any of the web element when added or removed then Absolute XPath changes." }, { "code": null, "e": 1489, "s": 1480, "text": "Example:" }, { "code": null, "e": 1572, "s": 1489, "text": "/html[1]/body[1]/div[6]/div[1]/div[3]/div[1]/div[1]/div[1]/div[3]/ul[1]/li[2]/a[1]" }, { "code": null, "e": 1792, "s": 1572, "text": "Relative XPath; In this, XPath begins with the double forward slash ‘//’ which means it can search the element anywhere in the Webpage. Generally Relative Xpath is preferred as they are not complete path from Root node." }, { "code": null, "e": 1801, "s": 1792, "text": "Example:" }, { "code": null, "e": 1832, "s": 1801, "text": "//input[@id = 'fakebox-input']" }, { "code": null, "e": 2175, "s": 1832, "text": "If you want to learn how to make XPath identify webelements, Then open the webpage in chrome browser and inspect the element by right click on the webpage and after that press ‘ctrl+f’ to find the webelements using XPath. You can also use the chrome extension like ‘chropath’ to find the xpath for a webelement. Commonly Used XPath Functions:" }, { "code": null, "e": 2186, "s": 2175, "text": "contains()" }, { "code": null, "e": 2199, "s": 2186, "text": "Start-With()" }, { "code": null, "e": 2206, "s": 2199, "text": "Text()" }, { "code": null, "e": 2365, "s": 2206, "text": "contains(): This Function is used to select the node whose specified attribute value contains the specified string provided in the function argument. Example:" }, { "code": null, "e": 2399, "s": 2365, "text": "//input[contains(@id, 'fakebox')]" }, { "code": null, "e": 2572, "s": 2399, "text": " starts-with(): This function is used to select the node whose specified attribute value starts with the specified string value provided in the function arguments. Example:" }, { "code": null, "e": 2609, "s": 2572, "text": "//input[starts-with(@id, 'fakebox')]" }, { "code": null, "e": 2738, "s": 2609, "text": " text(): This function is used to find the node having the exact match with the specified string value in the function. Example:" }, { "code": null, "e": 2744, "s": 2738, "text": "//div" }, { "code": null, "e": 2854, "s": 2744, "text": " Uses of AND and OR in XPath AND and OR are used to combine two or more conditions to find the node. Example:" }, { "code": null, "e": 2901, "s": 2854, "text": "//input[@value = 'Log In' or @type = 'submit']" }, { "code": null, "e": 2949, "s": 2901, "text": " Similarly, We can apply AND operator in XPath." }, { "code": null, "e": 2963, "s": 2949, "text": "mitalibhola94" }, { "code": null, "e": 2976, "s": 2963, "text": "HTML and XML" }, { "code": null, "e": 2985, "s": 2976, "text": "selenium" }, { "code": null, "e": 3002, "s": 2985, "text": "Web Technologies" } ]
Python – seaborn.pointplot() method
01 Aug, 2020 Seaborn is an amazing visualization library for statistical graphics plotting in Python. It provides beautiful default styles and color palettes to make statistical plots more attractive. It is built on the top of matplotlib library and also closely integrated to the data structures from pandas. This method is used to show point estimates and confidence intervals using scatter plot glyphs. A point plot represents an estimate of central tendency for a numeric variable by the position of scatter plot points and provides some indication of the uncertainty around that estimate using error bars. This function always treats one of the variables as categorical and draws data at ordinal positions (0, 1, ... n) on the relevant axis, even when the data has a numeric or date type. Syntax: seaborn.pointplot(x=None, y=None, hue=None, data=None, order=None,hue_order=None, estimator=<function mean at 0x00000193E305E828>, ci=95, n_boot=1000, units=None, markers=’o’, linestyles=’-‘, dodge=False, join=True, scale=1, orient=None, color=None, palette=None, errwidth=None, capsize=None, ax=None, **kwargs) Parameters: The description of some main parameters are given below: x, y: Inputs for plotting long-form data. hue: (optional) column name for color encoding. data: dataframe as a Dataset for plotting. markers: (optional) Markers to use for each of the ‘hue’ levels. linestyles: (optional) Line styles to use for each of the ‘hue’ levels. dodge: (optional) Amount to separate the points for each level of the ‘hue’ variable along the categorical axis. color: (optional) Color for all the elements, or seed for a gradient palette. capsize: (optional) Width of the ‘caps’ on error bars. Return: The Axes object with the plot drawn onto it. Below is the implementation of above method: Example 1: Python3 # importing required packagesimport seaborn as snsimport matplotlib.pyplot as plt # loading datasetdata = sns.load_dataset("tips") # draw pointplotsns.pointplot(x = "sex", y = "total_bill", data = data)# show the plotplt.show()# This code is contributed # by Deepanshu Rustagi. Output: Example 2: Python3 # importing required packagesimport seaborn as snsimport matplotlib.pyplot as plt # loading datasetdata = sns.load_dataset("tips") # draw pointplot with# hue = smokersns.pointplot(x = "sex", y = "total_bill", hue = "smoker", data = data)# show the plotplt.show()# This code is contributed # by Deepanshu Rustagi. Output : Example 3: Python3 # importing required packagesimport seaborn as snsimport matplotlib.pyplot as plt # loading datasetdata = sns.load_dataset("tips") # draw pointplotsns.pointplot(x = "size", y = "total_bill", linestyles = '-.', markers = '^', hue = "sex", data = data)# show the plotplt.show() # This code is contributed # by Deepanshu Rustagi. Output: Python-Seaborn Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Python Classes and Objects Python | os.path.join() method Introduction To PYTHON Python OOPs Concepts How to drop one or multiple columns in Pandas Dataframe How To Convert Python Dictionary To JSON? Check if element exists in list in Python Python | Get unique values from a list Create a directory in Python
[ { "code": null, "e": 28, "s": 0, "text": "\n01 Aug, 2020" }, { "code": null, "e": 325, "s": 28, "text": "Seaborn is an amazing visualization library for statistical graphics plotting in Python. It provides beautiful default styles and color palettes to make statistical plots more attractive. It is built on the top of matplotlib library and also closely integrated to the data structures from pandas." }, { "code": null, "e": 626, "s": 325, "text": "This method is used to show point estimates and confidence intervals using scatter plot glyphs. A point plot represents an estimate of central tendency for a numeric variable by the position of scatter plot points and provides some indication of the uncertainty around that estimate using error bars." }, { "code": null, "e": 809, "s": 626, "text": "This function always treats one of the variables as categorical and draws data at ordinal positions (0, 1, ... n) on the relevant axis, even when the data has a numeric or date type." }, { "code": null, "e": 1129, "s": 809, "text": "Syntax: seaborn.pointplot(x=None, y=None, hue=None, data=None, order=None,hue_order=None, estimator=<function mean at 0x00000193E305E828>, ci=95, n_boot=1000, units=None, markers=’o’, linestyles=’-‘, dodge=False, join=True, scale=1, orient=None, color=None, palette=None, errwidth=None, capsize=None, ax=None, **kwargs)" }, { "code": null, "e": 1198, "s": 1129, "text": "Parameters: The description of some main parameters are given below:" }, { "code": null, "e": 1240, "s": 1198, "text": "x, y: Inputs for plotting long-form data." }, { "code": null, "e": 1288, "s": 1240, "text": "hue: (optional) column name for color encoding." }, { "code": null, "e": 1331, "s": 1288, "text": "data: dataframe as a Dataset for plotting." }, { "code": null, "e": 1396, "s": 1331, "text": "markers: (optional) Markers to use for each of the ‘hue’ levels." }, { "code": null, "e": 1468, "s": 1396, "text": "linestyles: (optional) Line styles to use for each of the ‘hue’ levels." }, { "code": null, "e": 1581, "s": 1468, "text": "dodge: (optional) Amount to separate the points for each level of the ‘hue’ variable along the categorical axis." }, { "code": null, "e": 1659, "s": 1581, "text": "color: (optional) Color for all the elements, or seed for a gradient palette." }, { "code": null, "e": 1714, "s": 1659, "text": "capsize: (optional) Width of the ‘caps’ on error bars." }, { "code": null, "e": 1767, "s": 1714, "text": "Return: The Axes object with the plot drawn onto it." }, { "code": null, "e": 1812, "s": 1767, "text": "Below is the implementation of above method:" }, { "code": null, "e": 1823, "s": 1812, "text": "Example 1:" }, { "code": null, "e": 1831, "s": 1823, "text": "Python3" }, { "code": "# importing required packagesimport seaborn as snsimport matplotlib.pyplot as plt # loading datasetdata = sns.load_dataset(\"tips\") # draw pointplotsns.pointplot(x = \"sex\", y = \"total_bill\", data = data)# show the plotplt.show()# This code is contributed # by Deepanshu Rustagi.", "e": 2137, "s": 1831, "text": null }, { "code": null, "e": 2145, "s": 2137, "text": "Output:" }, { "code": null, "e": 2156, "s": 2145, "text": "Example 2:" }, { "code": null, "e": 2164, "s": 2156, "text": "Python3" }, { "code": "# importing required packagesimport seaborn as snsimport matplotlib.pyplot as plt # loading datasetdata = sns.load_dataset(\"tips\") # draw pointplot with# hue = smokersns.pointplot(x = \"sex\", y = \"total_bill\", hue = \"smoker\", data = data)# show the plotplt.show()# This code is contributed # by Deepanshu Rustagi.", "e": 2518, "s": 2164, "text": null }, { "code": null, "e": 2527, "s": 2518, "text": "Output :" }, { "code": null, "e": 2538, "s": 2527, "text": "Example 3:" }, { "code": null, "e": 2546, "s": 2538, "text": "Python3" }, { "code": "# importing required packagesimport seaborn as snsimport matplotlib.pyplot as plt # loading datasetdata = sns.load_dataset(\"tips\") # draw pointplotsns.pointplot(x = \"size\", y = \"total_bill\", linestyles = '-.', markers = '^', hue = \"sex\", data = data)# show the plotplt.show() # This code is contributed # by Deepanshu Rustagi.", "e": 2941, "s": 2546, "text": null }, { "code": null, "e": 2949, "s": 2941, "text": "Output:" }, { "code": null, "e": 2964, "s": 2949, "text": "Python-Seaborn" }, { "code": null, "e": 2971, "s": 2964, "text": "Python" }, { "code": null, "e": 3069, "s": 2971, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3101, "s": 3069, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 3128, "s": 3101, "text": "Python Classes and Objects" }, { "code": null, "e": 3159, "s": 3128, "text": "Python | os.path.join() method" }, { "code": null, "e": 3182, "s": 3159, "text": "Introduction To PYTHON" }, { "code": null, "e": 3203, "s": 3182, "text": "Python OOPs Concepts" }, { "code": null, "e": 3259, "s": 3203, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 3301, "s": 3259, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 3343, "s": 3301, "text": "Check if element exists in list in Python" }, { "code": null, "e": 3382, "s": 3343, "text": "Python | Get unique values from a list" } ]
What are the differences between LESS and SASS ?
25 Jul, 2021 This article aims to emphasize the key features & differences between the two CSS pre-processors, LESS and SASS. Before diving directly into the difference section, first, let’s talk about these two pre-processors. If you don’t know the basics of this pre-processor, then please refer to LESS & SASS. LESS: It is a Leaner Style Sheet that is dynamic in nature and efficiently enables customization and reusability. LESS supports cross-browser friendly. It is JavaScript-based and has very precise error reporting along with indicating the exact location of the error. It helps in readability and reusability by letting users create properties like variables and mixins to create dynamic and reusable values throughout the project. It uses Preboot.less to implement mixins. Example: LESS @selector: box; //using variables .@{selector} { font-weight: semi-bold; line-weight: 20px;} CSS Output: CSS .box { font-weight: semi-bold; line-weight: 20px;} SASS: It is a Syntactically Awesome Style Sheet that supports all version compatible extensions to CSS that increases code reusability. It is implemented using Ruby and actively reports errors made in syntax. It uses compass extension to implement mixins and also enables a user to implement their own functions. It lets users create code reusabilities like variables and mixins as well. Example: SASS a { color: white; // Nesting &:hover { text-decoration: none; } :not(&) { text-decoration: underline; }} CSS Output: CSS a { color: white;}a:hover { text-decoration: none;}:not(a) { text-decoration: underline;} Similarities They are similar when it comes to syntax.LESS: @color: white; /*@color is a LESS variable*/ #header { color: @color; }SASS: $color: white; /* $color is a SASS variable */ #header { color: $color; }We can use properties like mixins and variables in SASS and LESS both. They are similar when it comes to syntax.LESS: @color: white; /*@color is a LESS variable*/ #header { color: @color; }SASS: $color: white; /* $color is a SASS variable */ #header { color: $color; } They are similar when it comes to syntax. LESS: @color: white; /*@color is a LESS variable*/ #header { color: @color; } LESS: @color: white; /*@color is a LESS variable*/ #header { color: @color; } SASS: $color: white; /* $color is a SASS variable */ #header { color: $color; } SASS: $color: white; /* $color is a SASS variable */ #header { color: $color; } We can use properties like mixins and variables in SASS and LESS both. We can use properties like mixins and variables in SASS and LESS both. Differences between SASS & LESS: SASS LESS Example: For mixins LESS: LESS .margined { margin-bottom: 1rem; margin-top: 2rem;}#box h1 { font: Roboto, sans-serif; .margined;}.cont a { color: blue; .margined;} CSS Output: CSS #box h1 { font: Roboto, sans-serif; margin-bottom: 1rem; margin-top: 2rem;}.cont a { color: blue; margin-bottom: 1rem; margin-top: 2rem;} SASS: SASS @mixin margined { margin-bottom: 1rem; margin-top: 2rem;}#box h1 { @include margined; font: Roboto, sans-serif;}.cont a { @include margined; color: blue;} CSS Output: CSS #box h1 { margin-bottom: 1rem; margin-top: 2rem; font: Roboto, sans-serif;}.cont a { margin-bottom: 1rem; margin-top: 2rem; color: blue;} CSS-Questions Picked SASS CSS 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": "\n25 Jul, 2021" }, { "code": null, "e": 329, "s": 28, "text": "This article aims to emphasize the key features & differences between the two CSS pre-processors, LESS and SASS. Before diving directly into the difference section, first, let’s talk about these two pre-processors. If you don’t know the basics of this pre-processor, then please refer to LESS & SASS." }, { "code": null, "e": 801, "s": 329, "text": "LESS: It is a Leaner Style Sheet that is dynamic in nature and efficiently enables customization and reusability. LESS supports cross-browser friendly. It is JavaScript-based and has very precise error reporting along with indicating the exact location of the error. It helps in readability and reusability by letting users create properties like variables and mixins to create dynamic and reusable values throughout the project. It uses Preboot.less to implement mixins." }, { "code": null, "e": 810, "s": 801, "text": "Example:" }, { "code": null, "e": 815, "s": 810, "text": "LESS" }, { "code": "@selector: box; //using variables .@{selector} { font-weight: semi-bold; line-weight: 20px;}", "e": 911, "s": 815, "text": null }, { "code": null, "e": 925, "s": 913, "text": "CSS Output:" }, { "code": null, "e": 929, "s": 925, "text": "CSS" }, { "code": ".box { font-weight: semi-bold; line-weight: 20px;}", "e": 980, "s": 929, "text": null }, { "code": null, "e": 1368, "s": 980, "text": "SASS: It is a Syntactically Awesome Style Sheet that supports all version compatible extensions to CSS that increases code reusability. It is implemented using Ruby and actively reports errors made in syntax. It uses compass extension to implement mixins and also enables a user to implement their own functions. It lets users create code reusabilities like variables and mixins as well." }, { "code": null, "e": 1377, "s": 1368, "text": "Example:" }, { "code": null, "e": 1382, "s": 1377, "text": "SASS" }, { "code": "a { color: white; // Nesting &:hover { text-decoration: none; } :not(&) { text-decoration: underline; }}", "e": 1503, "s": 1382, "text": null }, { "code": null, "e": 1515, "s": 1503, "text": "CSS Output:" }, { "code": null, "e": 1519, "s": 1515, "text": "CSS" }, { "code": "a { color: white;}a:hover { text-decoration: none;}:not(a) { text-decoration: underline;}", "e": 1612, "s": 1519, "text": null }, { "code": null, "e": 1626, "s": 1612, "text": " Similarities" }, { "code": null, "e": 1898, "s": 1626, "text": "They are similar when it comes to syntax.LESS: @color: white; /*@color is a LESS variable*/\n#header {\n color: @color;\n}SASS: $color: white; /* $color is a SASS variable */\n#header {\n color: $color;\n}We can use properties like mixins and variables in SASS and LESS both." }, { "code": null, "e": 2100, "s": 1898, "text": "They are similar when it comes to syntax.LESS: @color: white; /*@color is a LESS variable*/\n#header {\n color: @color;\n}SASS: $color: white; /* $color is a SASS variable */\n#header {\n color: $color;\n}" }, { "code": null, "e": 2142, "s": 2100, "text": "They are similar when it comes to syntax." }, { "code": null, "e": 2222, "s": 2142, "text": "LESS: @color: white; /*@color is a LESS variable*/\n#header {\n color: @color;\n}" }, { "code": null, "e": 2228, "s": 2222, "text": "LESS:" }, { "code": null, "e": 2303, "s": 2228, "text": " @color: white; /*@color is a LESS variable*/\n#header {\n color: @color;\n}" }, { "code": null, "e": 2385, "s": 2303, "text": "SASS: $color: white; /* $color is a SASS variable */\n#header {\n color: $color;\n}" }, { "code": null, "e": 2391, "s": 2385, "text": "SASS:" }, { "code": null, "e": 2468, "s": 2391, "text": " $color: white; /* $color is a SASS variable */\n#header {\n color: $color;\n}" }, { "code": null, "e": 2539, "s": 2468, "text": "We can use properties like mixins and variables in SASS and LESS both." }, { "code": null, "e": 2610, "s": 2539, "text": "We can use properties like mixins and variables in SASS and LESS both." }, { "code": null, "e": 2643, "s": 2610, "text": "Differences between SASS & LESS:" }, { "code": null, "e": 2648, "s": 2643, "text": "SASS" }, { "code": null, "e": 2653, "s": 2648, "text": "LESS" }, { "code": null, "e": 2675, "s": 2655, "text": "Example: For mixins" }, { "code": null, "e": 2681, "s": 2675, "text": "LESS:" }, { "code": null, "e": 2686, "s": 2681, "text": "LESS" }, { "code": ".margined { margin-bottom: 1rem; margin-top: 2rem;}#box h1 { font: Roboto, sans-serif; .margined;}.cont a { color: blue; .margined;}", "e": 2825, "s": 2686, "text": null }, { "code": null, "e": 2837, "s": 2825, "text": "CSS Output:" }, { "code": null, "e": 2841, "s": 2837, "text": "CSS" }, { "code": "#box h1 { font: Roboto, sans-serif; margin-bottom: 1rem; margin-top: 2rem;}.cont a { color: blue; margin-bottom: 1rem; margin-top: 2rem;}", "e": 2985, "s": 2841, "text": null }, { "code": null, "e": 2991, "s": 2985, "text": "SASS:" }, { "code": null, "e": 2996, "s": 2991, "text": "SASS" }, { "code": "@mixin margined { margin-bottom: 1rem; margin-top: 2rem;}#box h1 { @include margined; font: Roboto, sans-serif;}.cont a { @include margined; color: blue;}", "e": 3157, "s": 2996, "text": null }, { "code": null, "e": 3169, "s": 3157, "text": "CSS Output:" }, { "code": null, "e": 3173, "s": 3169, "text": "CSS" }, { "code": "#box h1 { margin-bottom: 1rem; margin-top: 2rem; font: Roboto, sans-serif;}.cont a { margin-bottom: 1rem; margin-top: 2rem; color: blue;}", "e": 3317, "s": 3173, "text": null }, { "code": null, "e": 3331, "s": 3317, "text": "CSS-Questions" }, { "code": null, "e": 3338, "s": 3331, "text": "Picked" }, { "code": null, "e": 3343, "s": 3338, "text": "SASS" }, { "code": null, "e": 3347, "s": 3343, "text": "CSS" }, { "code": null, "e": 3364, "s": 3347, "text": "Web Technologies" } ]
Import and Export in Node.js
19 Aug, 2020 Importing and exporting files are important parts of any programming language. Importing functions or modules enhances the reusability of code. When the application grows in size, maintaining a single file with all the functions and logic becomes difficult. It also hinders the process of debugging. Therefore, it is good practice to create separate files for specific functions and later import them as per requirement. Node.js also allows importing and exporting functions and modules. Functions in one module can be imported and called in other modules saving the effort to copy function definitions into the other files. The module can be edited or debugged separately making it easier to add or remove features. Steps to include functions from other files: Creating a Module: Modules are created in Node.js are JavaScript files. Every time a new file with .js extension is created, it becomes a module.Exporting a Module: Filename: func.jsfunction add(x, y) { return x + y;} function subtract(x, y) { return x - y;} // Adding the code below to allow importing// the functions in other filesmodule.exports = { add }Importing a Module: We need to import the module to use the functions defined in the imported module in another file. The result returned by require() is stored in a variable which is used to invoke the functions using the dot notation.Filename: main.js// Importing the func.js module // The ./ says that the func module// is in the same directory as // the main.js fileconst f = require('./func'); // Require returns an object with add()// and stores it in the f variable // which is used to invoke the required const result = f.add(10, 5); console.log('The result is:', result);Output:The result is: 15 Creating a Module: Modules are created in Node.js are JavaScript files. Every time a new file with .js extension is created, it becomes a module. Exporting a Module: Filename: func.jsfunction add(x, y) { return x + y;} function subtract(x, y) { return x - y;} // Adding the code below to allow importing// the functions in other filesmodule.exports = { add } function add(x, y) { return x + y;} function subtract(x, y) { return x - y;} // Adding the code below to allow importing// the functions in other filesmodule.exports = { add } Importing a Module: We need to import the module to use the functions defined in the imported module in another file. The result returned by require() is stored in a variable which is used to invoke the functions using the dot notation.Filename: main.js// Importing the func.js module // The ./ says that the func module// is in the same directory as // the main.js fileconst f = require('./func'); // Require returns an object with add()// and stores it in the f variable // which is used to invoke the required const result = f.add(10, 5); console.log('The result is:', result);Output:The result is: 15 // Importing the func.js module // The ./ says that the func module// is in the same directory as // the main.js fileconst f = require('./func'); // Require returns an object with add()// and stores it in the f variable // which is used to invoke the required const result = f.add(10, 5); console.log('The result is:', result); Output: The result is: 15 Importing multiple functions from local file: Filename: func.js function add(x, y) { return x + y;} function subtract(x, y) { return x - y;} module.exports = { add, subtract}; Filename: main.js const f = require('./func'); console.log(f.add(4, 4));console.log(f.subtract(8, 4)); We can also use the destructuring syntax to unpack the properties of the object returned by require() function and store them in respective variables. const { add, subtract} = require('./func');console.log(add(4, 4)); console.log(subtract(8, 4)); Output: 8 4 Other ways to export a module Defining the functions inside module.exports object.module.exports = { add: function (x, y) { return x + y; }, subtract: function (x, y) { return x - y; },}; module.exports = { add: function (x, y) { return x + y; }, subtract: function (x, y) { return x - y; },}; Defining each function independently as a method of module.exportsmodule.exports.add = function (x, y) { return x + y;}; module.exports.subtract = function (x, y) { return x - y;}; module.exports.add = function (x, y) { return x + y;}; module.exports.subtract = function (x, y) { return x - y;}; Importing a module from a directory: Importing lib.js file inside the directory, by prefixing lib.js with the directory name. const lib = require('./mod/lib'); console.log(lib.add(6, 4));console.log(lib.subtract(12, 4)); There are three types of modules in Node.js Importing from local module: These modules are created by the user and can be imported as:const var = require('./filename.js'); // OR const var = require('./path/filename.js'); Importing from core modules: These modules are inbuilt in Node.js and can be imported as:const var = require('fs');Importing from third party modules: These modules are installed using a package manager such as npm. Examples of third party modules are express, mongoose, nodemon, etc. These are imported as:const express = require('express'); Importing from local module: These modules are created by the user and can be imported as:const var = require('./filename.js'); // OR const var = require('./path/filename.js'); const var = require('./filename.js'); // OR const var = require('./path/filename.js'); Importing from core modules: These modules are inbuilt in Node.js and can be imported as:const var = require('fs'); const var = require('fs'); Importing from third party modules: These modules are installed using a package manager such as npm. Examples of third party modules are express, mongoose, nodemon, etc. These are imported as:const express = require('express'); const express = require('express'); Thus above are few examples to import and export functions from different files in Node.js . Node.js-Misc Node.js Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n19 Aug, 2020" }, { "code": null, "e": 473, "s": 52, "text": "Importing and exporting files are important parts of any programming language. Importing functions or modules enhances the reusability of code. When the application grows in size, maintaining a single file with all the functions and logic becomes difficult. It also hinders the process of debugging. Therefore, it is good practice to create separate files for specific functions and later import them as per requirement." }, { "code": null, "e": 769, "s": 473, "text": "Node.js also allows importing and exporting functions and modules. Functions in one module can be imported and called in other modules saving the effort to copy function definitions into the other files. The module can be edited or debugged separately making it easier to add or remove features." }, { "code": null, "e": 814, "s": 769, "text": "Steps to include functions from other files:" }, { "code": null, "e": 1787, "s": 814, "text": "Creating a Module: Modules are created in Node.js are JavaScript files. Every time a new file with .js extension is created, it becomes a module.Exporting a Module: Filename: func.jsfunction add(x, y) { return x + y;} function subtract(x, y) { return x - y;} // Adding the code below to allow importing// the functions in other filesmodule.exports = { add }Importing a Module: We need to import the module to use the functions defined in the imported module in another file. The result returned by require() is stored in a variable which is used to invoke the functions using the dot notation.Filename: main.js// Importing the func.js module // The ./ says that the func module// is in the same directory as // the main.js fileconst f = require('./func'); // Require returns an object with add()// and stores it in the f variable // which is used to invoke the required const result = f.add(10, 5); console.log('The result is:', result);Output:The result is: 15" }, { "code": null, "e": 1933, "s": 1787, "text": "Creating a Module: Modules are created in Node.js are JavaScript files. Every time a new file with .js extension is created, it becomes a module." }, { "code": null, "e": 2152, "s": 1933, "text": "Exporting a Module: Filename: func.jsfunction add(x, y) { return x + y;} function subtract(x, y) { return x - y;} // Adding the code below to allow importing// the functions in other filesmodule.exports = { add }" }, { "code": "function add(x, y) { return x + y;} function subtract(x, y) { return x - y;} // Adding the code below to allow importing// the functions in other filesmodule.exports = { add }", "e": 2334, "s": 2152, "text": null }, { "code": null, "e": 2944, "s": 2334, "text": "Importing a Module: We need to import the module to use the functions defined in the imported module in another file. The result returned by require() is stored in a variable which is used to invoke the functions using the dot notation.Filename: main.js// Importing the func.js module // The ./ says that the func module// is in the same directory as // the main.js fileconst f = require('./func'); // Require returns an object with add()// and stores it in the f variable // which is used to invoke the required const result = f.add(10, 5); console.log('The result is:', result);Output:The result is: 15" }, { "code": "// Importing the func.js module // The ./ says that the func module// is in the same directory as // the main.js fileconst f = require('./func'); // Require returns an object with add()// and stores it in the f variable // which is used to invoke the required const result = f.add(10, 5); console.log('The result is:', result);", "e": 3277, "s": 2944, "text": null }, { "code": null, "e": 3285, "s": 3277, "text": "Output:" }, { "code": null, "e": 3303, "s": 3285, "text": "The result is: 15" }, { "code": null, "e": 3367, "s": 3303, "text": "Importing multiple functions from local file: Filename: func.js" }, { "code": "function add(x, y) { return x + y;} function subtract(x, y) { return x - y;} module.exports = { add, subtract};", "e": 3483, "s": 3367, "text": null }, { "code": null, "e": 3501, "s": 3483, "text": "Filename: main.js" }, { "code": "const f = require('./func'); console.log(f.add(4, 4));console.log(f.subtract(8, 4));", "e": 3587, "s": 3501, "text": null }, { "code": null, "e": 3738, "s": 3587, "text": "We can also use the destructuring syntax to unpack the properties of the object returned by require() function and store them in respective variables." }, { "code": "const { add, subtract} = require('./func');console.log(add(4, 4)); console.log(subtract(8, 4)); ", "e": 3835, "s": 3738, "text": null }, { "code": null, "e": 3843, "s": 3835, "text": "Output:" }, { "code": null, "e": 3848, "s": 3843, "text": "8\n4\n" }, { "code": null, "e": 3878, "s": 3848, "text": "Other ways to export a module" }, { "code": null, "e": 4048, "s": 3878, "text": "Defining the functions inside module.exports object.module.exports = { add: function (x, y) { return x + y; }, subtract: function (x, y) { return x - y; },};" }, { "code": "module.exports = { add: function (x, y) { return x + y; }, subtract: function (x, y) { return x - y; },};", "e": 4166, "s": 4048, "text": null }, { "code": null, "e": 4352, "s": 4166, "text": "Defining each function independently as a method of module.exportsmodule.exports.add = function (x, y) { return x + y;}; module.exports.subtract = function (x, y) { return x - y;};" }, { "code": "module.exports.add = function (x, y) { return x + y;}; module.exports.subtract = function (x, y) { return x - y;};", "e": 4472, "s": 4352, "text": null }, { "code": null, "e": 4598, "s": 4472, "text": "Importing a module from a directory: Importing lib.js file inside the directory, by prefixing lib.js with the directory name." }, { "code": "const lib = require('./mod/lib'); console.log(lib.add(6, 4));console.log(lib.subtract(12, 4));", "e": 4694, "s": 4598, "text": null }, { "code": null, "e": 4738, "s": 4694, "text": "There are three types of modules in Node.js" }, { "code": null, "e": 5258, "s": 4738, "text": "Importing from local module: These modules are created by the user and can be imported as:const var = require('./filename.js'); // OR\nconst var = require('./path/filename.js');\nImporting from core modules: These modules are inbuilt in Node.js and can be imported as:const var = require('fs');Importing from third party modules: These modules are installed using a package manager such as npm. Examples of third party modules are express, mongoose, nodemon, etc. These are imported as:const express = require('express');" }, { "code": null, "e": 5436, "s": 5258, "text": "Importing from local module: These modules are created by the user and can be imported as:const var = require('./filename.js'); // OR\nconst var = require('./path/filename.js');\n" }, { "code": null, "e": 5524, "s": 5436, "text": "const var = require('./filename.js'); // OR\nconst var = require('./path/filename.js');\n" }, { "code": null, "e": 5640, "s": 5524, "text": "Importing from core modules: These modules are inbuilt in Node.js and can be imported as:const var = require('fs');" }, { "code": null, "e": 5667, "s": 5640, "text": "const var = require('fs');" }, { "code": null, "e": 5895, "s": 5667, "text": "Importing from third party modules: These modules are installed using a package manager such as npm. Examples of third party modules are express, mongoose, nodemon, etc. These are imported as:const express = require('express');" }, { "code": null, "e": 5931, "s": 5895, "text": "const express = require('express');" }, { "code": null, "e": 6024, "s": 5931, "text": "Thus above are few examples to import and export functions from different files in Node.js ." }, { "code": null, "e": 6037, "s": 6024, "text": "Node.js-Misc" }, { "code": null, "e": 6045, "s": 6037, "text": "Node.js" }, { "code": null, "e": 6062, "s": 6045, "text": "Web Technologies" } ]
Build Your First Interactive Data Science Web App with Streamlit | by Yong Cui | Towards Data Science
Web applications are one of the most convenient ways to showcase your data science work. Building web applications can be daunting to many data scientists if they don’t have any web development experience. However, with the streamlit framework, web applications are no longer difficult for data scientists — if you know Python, you can build interactive web apps with streamlit — this awesome framework does the hard lift to make and layout web elements for us under the hood. We’ll simply focus on the data part. To install the streamlit framework, use the pip tool. pip install streamlit Once it’s installed, you can check its version. streamlit --version If you have streamlit installed correctly, you can run the demo app by running the following. In the app, you’ll have an opportunity to see various possibilities that you can do with the streamlit framework. streamlit hello In the demo app, you’ll find out that there are so many cool features supported by the streamlit framework, and these features are commonly needed by data scientists. In this article, I’d like to provide a short tutorial on getting started with this awesome web framework. I bet that if you know Python, it will take you just a few hours to have a reasonable understanding of this tool. If you want to follow along with this tutorial, you can find the script on the GitHub page here. For the purpose of this tutorial, we’ll be using the Titanic dataset to showcase some common streamlit techniques with a focus on interactive widgets. Where applicable, I’ll also integrate some optional widgets such that you’ll be learning more along the way. At its core, each streamlit web app is a Python script. At the top of the file, we import the necessary dependencies. In this case, we’ll be using multiple modules, as shown below. import pandas as pdimport timeimport streamlit as stimport plotly.express as px In terms of the dataset, we’ll use the titanic dataset, which we will download from the internet. One notable feature is the use of the decorator st.cache, which will increase the web responsiveness because of the cache of the data that have been fetched previously. In this case, the titanic dataset will be fetched just once and with the refresh of the web page, it won’t be fetched again. Relatedly, it should be noted that the script will run again once there is any change in your code, so taking advantage of the caching feature is essential to improve the user experience. To view the data, we can simply run st.dataframe(titanic_data), and you’ll see something like below. In streamlit, there are several ways to put headings to your web page. To put a title to your page, you can run: st.title(“My First Streamlit App”). To add additional headers at two different levels, you can use st.header() and st.subheader(). Alternatively, you can take advantage of the markdown feature, you can add headers like st.markdown(“#Just like a header”) and st.markdown(“#Just like a subheader”). Besides headings, an important organizational element in streamlit is the sidebar, where you can add configuration elements that modify the elements shown on the main page. To add a sidebar, you simply add st.sidebar to your script. Notably, you’ll be likely to add more elements to the sidebar. Thus, instead of using st.sidebar to refer to the sidebar, it’s a good idea to create a reference to the sidebar, something like sidebar = st.sidebar. To collect users’ responses, we have several options for creating multi-choice widgets. The first widget is the radio button. You’ll see something like below. Note that, the selected option will be the actual value of the displayed options instead of the selected numeric index. In this case, it will be the text. The second widget is the selectbox, which provides a drop-down list from which you can make your choice. The code will be like this. selected_sex = st.selectbox("Select Sex", titanic_data['sex'].unique())st.write(f"Selected Option: {selected_sex!r}") The interaction will be like the below. When you require users to enter multiple choices, you should use the multiselect widget, as shown below. selected_decks = st.multiselect("Select Decks", titanic_data['deck'].unique())st.write("Selected Decks:", selected_decks) For this widget, you’ll see something like below. When you need to collect numbers as input, we can use the number_input widget. As always, you can name the widget and set a value to the widget. In the code, I also included a “notification” feature in streamlit. When you want to show an error message, you use st.error(), while to show a successful message, you use st.success(). Another included feature is the use of columns (st.beta_columns), which is useful when you have parallel widgets that are closely related to each other. In this case, it’s reasonable to group two widgets that collect minimum and maximum ages together. With the code above, we’ll see a widget shown below. In addition to this widget, streamlit also provides a slider widget that allows the user to specify a number input without keying anything. Here’s the code. With the slider widget, you specify the widget’s name. In the meantime, you set the minimum and maximum values. Besides the slider widget, the above code includes another feature called an expander (st.beta_expander). This feature is useful when you want to hide some optional widgets. You can specify if you want the expander to be expanded by default. The following figure shows you such an interactive slider widget. To collect text data, we can use the text_input and the text_area widgets. The major difference is that the text_input widget is good for collecting a short text string, while the text_area widget is preferred if you want to collect a large amount of text data. The above code shows you how to display these widgets. I also included two extra features. One is the code displaying widget (st.echo), which will show the code included within the with statement in addition to the widget. The other feature is an Easter egg, which is to launch a bunch of balloons (st.balloons). See the figure below for such a feature. Progress BarSometimes, if your app works on a large amount of data and the wait time is longer than that a user can expect, it’s a good idea to provide a progress bar. The code is shown below. This is what the progress bar looks like in the app. MarkdownStreamlit supports markdown entries, which create a lot of possibilities for us. To use this feature, you’ll simply use st.markdown. To learn more about the markdown syntax, you can go to GitHub. Here’s some commonly used examples. PlotsIf your app wants to show plots, streamlit natively supports many third-party figures. Here’s a list that is taken from its official documentation. write(mpl_fig): Displays a Matplotlib figure.write(altair): Displays an Altair chart.write(graphviz): Displays a Graphviz graph.write(plotly_fig): Displays a Plotly figure.write(bokeh_fig): Displays a Bokeh figure. The following figure shows you a figure made with Plotly. In this article, we reviewed some useful features that you should include in your interactive web app. As you can see, streamlit provides a variety of features that allow you to collect numbers, texts, multi-choice options, and display code, markdown, and figures. With streamlit, you pretty much have no worries about the web elements. You’ll just need to focus on building the content of the web app.
[ { "code": null, "e": 686, "s": 172, "text": "Web applications are one of the most convenient ways to showcase your data science work. Building web applications can be daunting to many data scientists if they don’t have any web development experience. However, with the streamlit framework, web applications are no longer difficult for data scientists — if you know Python, you can build interactive web apps with streamlit — this awesome framework does the hard lift to make and layout web elements for us under the hood. We’ll simply focus on the data part." }, { "code": null, "e": 740, "s": 686, "text": "To install the streamlit framework, use the pip tool." }, { "code": null, "e": 762, "s": 740, "text": "pip install streamlit" }, { "code": null, "e": 810, "s": 762, "text": "Once it’s installed, you can check its version." }, { "code": null, "e": 830, "s": 810, "text": "streamlit --version" }, { "code": null, "e": 1038, "s": 830, "text": "If you have streamlit installed correctly, you can run the demo app by running the following. In the app, you’ll have an opportunity to see various possibilities that you can do with the streamlit framework." }, { "code": null, "e": 1054, "s": 1038, "text": "streamlit hello" }, { "code": null, "e": 1441, "s": 1054, "text": "In the demo app, you’ll find out that there are so many cool features supported by the streamlit framework, and these features are commonly needed by data scientists. In this article, I’d like to provide a short tutorial on getting started with this awesome web framework. I bet that if you know Python, it will take you just a few hours to have a reasonable understanding of this tool." }, { "code": null, "e": 1689, "s": 1441, "text": "If you want to follow along with this tutorial, you can find the script on the GitHub page here. For the purpose of this tutorial, we’ll be using the Titanic dataset to showcase some common streamlit techniques with a focus on interactive widgets." }, { "code": null, "e": 1798, "s": 1689, "text": "Where applicable, I’ll also integrate some optional widgets such that you’ll be learning more along the way." }, { "code": null, "e": 1979, "s": 1798, "text": "At its core, each streamlit web app is a Python script. At the top of the file, we import the necessary dependencies. In this case, we’ll be using multiple modules, as shown below." }, { "code": null, "e": 2059, "s": 1979, "text": "import pandas as pdimport timeimport streamlit as stimport plotly.express as px" }, { "code": null, "e": 2157, "s": 2059, "text": "In terms of the dataset, we’ll use the titanic dataset, which we will download from the internet." }, { "code": null, "e": 2639, "s": 2157, "text": "One notable feature is the use of the decorator st.cache, which will increase the web responsiveness because of the cache of the data that have been fetched previously. In this case, the titanic dataset will be fetched just once and with the refresh of the web page, it won’t be fetched again. Relatedly, it should be noted that the script will run again once there is any change in your code, so taking advantage of the caching feature is essential to improve the user experience." }, { "code": null, "e": 2740, "s": 2639, "text": "To view the data, we can simply run st.dataframe(titanic_data), and you’ll see something like below." }, { "code": null, "e": 2889, "s": 2740, "text": "In streamlit, there are several ways to put headings to your web page. To put a title to your page, you can run: st.title(“My First Streamlit App”)." }, { "code": null, "e": 2984, "s": 2889, "text": "To add additional headers at two different levels, you can use st.header() and st.subheader()." }, { "code": null, "e": 3150, "s": 2984, "text": "Alternatively, you can take advantage of the markdown feature, you can add headers like st.markdown(“#Just like a header”) and st.markdown(“#Just like a subheader”)." }, { "code": null, "e": 3597, "s": 3150, "text": "Besides headings, an important organizational element in streamlit is the sidebar, where you can add configuration elements that modify the elements shown on the main page. To add a sidebar, you simply add st.sidebar to your script. Notably, you’ll be likely to add more elements to the sidebar. Thus, instead of using st.sidebar to refer to the sidebar, it’s a good idea to create a reference to the sidebar, something like sidebar = st.sidebar." }, { "code": null, "e": 3723, "s": 3597, "text": "To collect users’ responses, we have several options for creating multi-choice widgets. The first widget is the radio button." }, { "code": null, "e": 3911, "s": 3723, "text": "You’ll see something like below. Note that, the selected option will be the actual value of the displayed options instead of the selected numeric index. In this case, it will be the text." }, { "code": null, "e": 4044, "s": 3911, "text": "The second widget is the selectbox, which provides a drop-down list from which you can make your choice. The code will be like this." }, { "code": null, "e": 4162, "s": 4044, "text": "selected_sex = st.selectbox(\"Select Sex\", titanic_data['sex'].unique())st.write(f\"Selected Option: {selected_sex!r}\")" }, { "code": null, "e": 4202, "s": 4162, "text": "The interaction will be like the below." }, { "code": null, "e": 4307, "s": 4202, "text": "When you require users to enter multiple choices, you should use the multiselect widget, as shown below." }, { "code": null, "e": 4429, "s": 4307, "text": "selected_decks = st.multiselect(\"Select Decks\", titanic_data['deck'].unique())st.write(\"Selected Decks:\", selected_decks)" }, { "code": null, "e": 4479, "s": 4429, "text": "For this widget, you’ll see something like below." }, { "code": null, "e": 4624, "s": 4479, "text": "When you need to collect numbers as input, we can use the number_input widget. As always, you can name the widget and set a value to the widget." }, { "code": null, "e": 5062, "s": 4624, "text": "In the code, I also included a “notification” feature in streamlit. When you want to show an error message, you use st.error(), while to show a successful message, you use st.success(). Another included feature is the use of columns (st.beta_columns), which is useful when you have parallel widgets that are closely related to each other. In this case, it’s reasonable to group two widgets that collect minimum and maximum ages together." }, { "code": null, "e": 5115, "s": 5062, "text": "With the code above, we’ll see a widget shown below." }, { "code": null, "e": 5272, "s": 5115, "text": "In addition to this widget, streamlit also provides a slider widget that allows the user to specify a number input without keying anything. Here’s the code." }, { "code": null, "e": 5626, "s": 5272, "text": "With the slider widget, you specify the widget’s name. In the meantime, you set the minimum and maximum values. Besides the slider widget, the above code includes another feature called an expander (st.beta_expander). This feature is useful when you want to hide some optional widgets. You can specify if you want the expander to be expanded by default." }, { "code": null, "e": 5692, "s": 5626, "text": "The following figure shows you such an interactive slider widget." }, { "code": null, "e": 5954, "s": 5692, "text": "To collect text data, we can use the text_input and the text_area widgets. The major difference is that the text_input widget is good for collecting a short text string, while the text_area widget is preferred if you want to collect a large amount of text data." }, { "code": null, "e": 6308, "s": 5954, "text": "The above code shows you how to display these widgets. I also included two extra features. One is the code displaying widget (st.echo), which will show the code included within the with statement in addition to the widget. The other feature is an Easter egg, which is to launch a bunch of balloons (st.balloons). See the figure below for such a feature." }, { "code": null, "e": 6501, "s": 6308, "text": "Progress BarSometimes, if your app works on a large amount of data and the wait time is longer than that a user can expect, it’s a good idea to provide a progress bar. The code is shown below." }, { "code": null, "e": 6554, "s": 6501, "text": "This is what the progress bar looks like in the app." }, { "code": null, "e": 6758, "s": 6554, "text": "MarkdownStreamlit supports markdown entries, which create a lot of possibilities for us. To use this feature, you’ll simply use st.markdown. To learn more about the markdown syntax, you can go to GitHub." }, { "code": null, "e": 6794, "s": 6758, "text": "Here’s some commonly used examples." }, { "code": null, "e": 6947, "s": 6794, "text": "PlotsIf your app wants to show plots, streamlit natively supports many third-party figures. Here’s a list that is taken from its official documentation." }, { "code": null, "e": 7162, "s": 6947, "text": "write(mpl_fig): Displays a Matplotlib figure.write(altair): Displays an Altair chart.write(graphviz): Displays a Graphviz graph.write(plotly_fig): Displays a Plotly figure.write(bokeh_fig): Displays a Bokeh figure." }, { "code": null, "e": 7220, "s": 7162, "text": "The following figure shows you a figure made with Plotly." } ]
GCD and LCM of two numbers in Java
Following is an example which computes find LCM and GCD of two given numbers. import java.util.Scanner; public class LCM_GCD { public static void lcm(int a, int b){ int max, step, lcm = 0; if(a > b){ max = step = a; } else{ max = step = b; } while(a!= 0) { if(max%a == 0 && max%b == 0) { lcm = max; break; } max += step; } System.out.println("LCM of given numbers is :: "+lcm); } public static void gcd(int a,int b){ int i, hcf = 0; for(i = 1; i <= a || i <= b; i++) { if( a%i == 0 && b%i == 0 ) hcf = i; } System.out.println("gcd of given two numbers is ::"+hcf); } public static void main(String args[]){ Scanner sc = new Scanner(System.in); System.out.println("Enter first number ::"); int a = sc.nextInt(); System.out.println("Enter second number ::"); int b = sc.nextInt(); lcm(a, b); gcd(a,b); } } Enter first number :: 125 Enter second number :: 25 LCM of given numbers is :: 125 GCD of given two numbers is ::25
[ { "code": null, "e": 1140, "s": 1062, "text": "Following is an example which computes find LCM and GCD of two given numbers." }, { "code": null, "e": 2094, "s": 1140, "text": "import java.util.Scanner;\npublic class LCM_GCD {\n public static void lcm(int a, int b){\n int max, step, lcm = 0;\n if(a > b){\n max = step = a;\n } else{\n max = step = b;\n }\n while(a!= 0) {\n if(max%a == 0 && max%b == 0) {\n lcm = max;\n break;\n }\n max += step;\n }\n System.out.println(\"LCM of given numbers is :: \"+lcm);\n }\n public static void gcd(int a,int b){\n int i, hcf = 0;\n for(i = 1; i <= a || i <= b; i++) {\n if( a%i == 0 && b%i == 0 )\n hcf = i;\n }\n System.out.println(\"gcd of given two numbers is ::\"+hcf);\n }\n public static void main(String args[]){\n Scanner sc = new Scanner(System.in);\n System.out.println(\"Enter first number ::\");\n int a = sc.nextInt();\n System.out.println(\"Enter second number ::\");\n int b = sc.nextInt();\n lcm(a, b);\n gcd(a,b);\n }\n}" }, { "code": null, "e": 2210, "s": 2094, "text": "Enter first number ::\n125\nEnter second number ::\n25\nLCM of given numbers is :: 125\nGCD of given two numbers is ::25" } ]
DocumentDB - Access Control
DocumentDB provides the concepts to control access to DocumentDB resources. Access to DocumentDB resources is governed by a master key token or a resource token. Connections based on resource tokens can only access the resources specified by the tokens and no other resources. Resource tokens are based on user permissions. First you create one or more users, and these are defined at the database level. First you create one or more users, and these are defined at the database level. Then you create one or more permissions for each user, based on the resources that you want to allow each user to access. Then you create one or more permissions for each user, based on the resources that you want to allow each user to access. Each permission generates a resource token that allows either read-only or full access to a given resource and that can be any user resource within the database. Each permission generates a resource token that allows either read-only or full access to a given resource and that can be any user resource within the database. Users are defined at the database level and permissions are defined for each user. Users are defined at the database level and permissions are defined for each user. Users and permissions apply to all collections in the database. Users and permissions apply to all collections in the database. Let’s take a look at a simple example in which we will learn how to define users and permissions to achieve granular security in DocumentDB. We will start with a new DocumentClient and query for the myfirstdb database. private static async Task CreateDocumentClient() { // Create a new instance of the DocumentClient using (var client = new DocumentClient(new Uri(EndpointUrl), AuthorizationKey)) { database = client.CreateDatabaseQuery("SELECT * FROM c WHERE c.id = 'myfirstdb'").AsEnumerable().First(); collection = client.CreateDocumentCollectionQuery(database.CollectionsLink, "SELECT * FROM c WHERE c.id = 'MyCollection'").AsEnumerable().First(); var alice = await CreateUser(client, "Alice"); var tom = await CreateUser(client, "Tom"); } } Following is the implementation for CreateUser. private async static Task<User> CreateUser(DocumentClient client, string userId) { Console.WriteLine(); Console.WriteLine("**** Create User {0} in {1} ****", userId, database.Id); var userDefinition = new User { Id = userId }; var result = await client.CreateUserAsync(database.SelfLink, userDefinition); var user = result.Resource; Console.WriteLine("Created new user"); ViewUser(user); return user; } Step 1 − Create two users, Alice and Tom like any resource we create, we construct a definition object with the desired Id and call the create method and in this case we're calling CreateUserAsync with the database's SelfLink and the userDefinition. We get back the result from whose resource property we obtain the newly created user object. Now to see these two new users in the database. private static void ViewUsers(DocumentClient client) { Console.WriteLine(); Console.WriteLine("**** View Users in {0} ****", database.Id); var users = client.CreateUserQuery(database.UsersLink).ToList(); var i = 0; foreach (var user in users) { i++; Console.WriteLine(); Console.WriteLine("User #{0}", i); ViewUser(user); } Console.WriteLine(); Console.WriteLine("Total users in database {0}: {1}", database.Id, users.Count); } private static void ViewUser(User user) { Console.WriteLine("User ID: {0} ", user.Id); Console.WriteLine("Resource ID: {0} ", user.ResourceId); Console.WriteLine("Self Link: {0} ", user.SelfLink); Console.WriteLine("Permissions Link: {0} ", user.PermissionsLink); Console.WriteLine("Timestamp: {0} ", user.Timestamp); } Step 2 − Call CreateUserQuery, against the database's UsersLink to retrieve a list of all users. Then loop through them and view their properties. Now we have to create them first. So let's say that we wanted to allow Alice read/write permissions to the MyCollection collection, but Tom can only read documents in the collection. await CreatePermission(client, alice, "Alice Collection Access", PermissionMode.All, collection); await CreatePermission(client, tom, "Tom Collection Access", PermissionMode.Read, collection); Step 3− Create a permission on a resource that is MyCollection collection so we need to get that resource a SelfLink. Step 4 − Then create a Permission.All on this collection for Alice and a Permission.Read on this collection for Tom. Following is the implementation for CreatePermission. private async static Task CreatePermission(DocumentClient client, User user, string permId, PermissionMode permissionMode, string resourceLink) { Console.WriteLine(); Console.WriteLine("**** Create Permission {0} for {1} ****", permId, user.Id); var permDefinition = new Permission { Id = permId, PermissionMode = permissionMode, ResourceLink = resourceLink }; var result = await client.CreatePermissionAsync(user.SelfLink, permDefinition); var perm = result.Resource; Console.WriteLine("Created new permission"); ViewPermission(perm); } As you should come to expect by now, we do this by creating a definition object for the new permission, which includes an Id and a permissionMode, which is either Permission.All or Permission.Read, and the SelfLink of the resource that's being secured by the permission. Step 5 − Call CreatePermissionAsync and get the created permission from the resource property in the result. To view the created permission, following is the implementation of ViewPermissions. private static void ViewPermissions(DocumentClient client, User user) { Console.WriteLine(); Console.WriteLine("**** View Permissions for {0} ****", user.Id); var perms = client.CreatePermissionQuery(user.PermissionsLink).ToList(); var i = 0; foreach (var perm in perms) { i++; Console.WriteLine(); Console.WriteLine("Permission #{0}", i); ViewPermission(perm); } Console.WriteLine(); Console.WriteLine("Total permissions for {0}: {1}", user.Id, perms.Count); } private static void ViewPermission(Permission perm) { Console.WriteLine("Permission ID: {0} ", perm.Id); Console.WriteLine("Resource ID: {0} ", perm.ResourceId); Console.WriteLine("Permission Mode: {0} ", perm.PermissionMode); Console.WriteLine("Token: {0} ", perm.Token); Console.WriteLine("Timestamp: {0} ", perm.Timestamp); } This time, it's a permission query against the user's permissions link and we simply list each permission returned for the user. Let's delete the Alice’s and Tom’s permissions. await DeletePermission(client, alice, "Alice Collection Access"); await DeletePermission(client, tom, "Tom Collection Access"); Following is the implementation for DeletePermission. private async static Task DeletePermission(DocumentClient client, User user, string permId) { Console.WriteLine(); Console.WriteLine("**** Delete Permission {0} from {1} ****", permId, user.Id); var query = new SqlQuerySpec { QueryText = "SELECT * FROM c WHERE c.id = @id", Parameters = new SqlParameterCollection { new SqlParameter { Name = "@id", Value = permId } } }; Permission perm = client.CreatePermissionQuery(user.PermissionsLink, query) .AsEnumerable().First(); await client.DeletePermissionAsync(perm.SelfLink); Console.WriteLine("Deleted permission {0} from user {1}", permId, user.Id); } Step 6 − To delete permissions, query by permission Id to get the SelfLink, and then using the SelfLink to delete the permission. Next, let’s delete the users themselves. Let’s delete both the users. await DeleteUser(client, "Alice"); await DeleteUser(client, "Tom"); Following is the implementation for DeleteUser. private async static Task DeleteUser(DocumentClient client, string userId) { Console.WriteLine(); Console.WriteLine("**** Delete User {0} in {1} ****", userId, database.Id); var query = new SqlQuerySpec { QueryText = "SELECT * FROM c WHERE c.id = @id", Parameters = new SqlParameterCollection { new SqlParameter { Name = "@id", Value = userId } } }; User user = client.CreateUserQuery(database.SelfLink, query).AsEnumerable().First(); await client.DeleteUserAsync(user.SelfLink); Console.WriteLine("Deleted user {0} from database {1}", userId, database.Id); } Step 7 − First query to get her SelfLink and then call DeleteUserAsync to delete her user object. Following is the implementation of CreateDocumentClient task in which we call all the above tasks. private static async Task CreateDocumentClient() { // Create a new instance of the DocumentClient using (var client = new DocumentClient(new Uri(EndpointUrl), AuthorizationKey)) { database = client.CreateDatabaseQuery("SELECT * FROM c WHERE c.id = 'myfirstdb'").AsEnumerable().First(); collection = client.CreateDocumentCollectionQuery(database.CollectionsLink, "SELECT * FROM c WHERE c.id = 'MyCollection'").AsEnumerable().First(); ViewUsers(client); var alice = await CreateUser(client, "Alice"); var tom = await CreateUser(client, "Tom"); ViewUsers(client); ViewPermissions(client, alice); ViewPermissions(client, tom); string collectionLink = client.CreateDocumentCollectionQuery(database.SelfLink, "SELECT VALUE c._self FROM c WHERE c.id = 'MyCollection'") .AsEnumerable().First().Value; await CreatePermission(client, alice, "Alice Collection Access", PermissionMode.All, collectionLink); await CreatePermission(client, tom, "Tom Collection Access", PermissionMode.Read, collectionLink); ViewPermissions(client, alice); ViewPermissions(client, tom); await DeletePermission(client, alice, "Alice Collection Access"); await DeletePermission(client, tom, "Tom Collection Access"); await DeleteUser(client, "Alice"); await DeleteUser(client, "Tom"); } } When the above code is compiled and executed you will receive the following output. **** View Users in myfirstdb **** Total users in database myfirstdb: 0 **** Create User Alice in myfirstdb **** Created new user User ID: Alice Resource ID: kV5oAC56NwA= Self Link: dbs/kV5oAA==/users/kV5oAC56NwA=/ Permissions Link: dbs/kV5oAA==/users/kV5oAC56NwA=/permissions/ Timestamp: 12/17/2015 5:44:19 PM **** Create User Tom in myfirstdb **** Created new user User ID: Tom Resource ID: kV5oAALxKgA= Self Link: dbs/kV5oAA==/users/kV5oAALxKgA=/ Permissions Link: dbs/kV5oAA==/users/kV5oAALxKgA=/permissions/ Timestamp: 12/17/2015 5:44:21 PM **** View Users in myfirstdb **** User #1 User ID: Tom Resource ID: kV5oAALxKgA= Self Link: dbs/kV5oAA==/users/kV5oAALxKgA=/ Permissions Link: dbs/kV5oAA==/users/kV5oAALxKgA=/permissions/ Timestamp: 12/17/2015 5:44:21 PM User #2 User ID: Alice Resource ID: kV5oAC56NwA= Self Link: dbs/kV5oAA==/users/kV5oAC56NwA=/ Permissions Link: dbs/kV5oAA==/users/kV5oAC56NwA=/permissions/ Timestamp: 12/17/2015 5:44:19 PM Total users in database myfirstdb: 2 **** View Permissions for Alice **** Total permissions for Alice: 0 **** View Permissions for Tom **** Total permissions for Tom: 0 **** Create Permission Alice Collection Access for Alice **** Created new permission Permission ID: Alice Collection Access Resource ID: kV5oAC56NwDON1RduEoCAA== Permission Mode: All Token: type=resource&ver=1&sig=zB6hfvvleC0oGGbq5cc67w==;Zt3Lx Ol14h8pd6/tyF1h62zbZKk9VwEIATIldw4ZyipQGW951kirueAKdeb3MxzQ7eCvDfvp7Y/ZxFpnip/D G JYcPyim5cf+dgLvos6fUuiKSFSul7uEKqp5JmJqUCyAvD7w+qt1Qr1PmrJDyAIgbZDBFWGe2VT9FaBH o PYwrLjRlnH0AxfbrR+T/UpWMSSHtLB8JvNFZNSH8hRjmQupuTSxCTYEC89bZ/pS6fNmNg8=; Timestamp: 12/17/2015 5:44:28 PM **** Create Permission Tom Collection Access for Tom **** Created new permission Permission ID: Tom Collection Access Resource ID: kV5oAALxKgCMai3JKWdfAA== Permission Mode: Read Token: type=resource&ver=1&sig=ieBHKeyi6EY9ZOovDpe76w==;92gwq V4AxKaCJ2dLS02VnJiig/5AEbPcfo1xvOjR10uK3a3FUMFULgsaK8nzxdz6hLVCIKUj6hvMOTOSN8Lt 7 i30mVqzpzCfe7JO3TYSJEI9D0/5HbMIEgaNJiCu0JPPwsjVecTytiLN56FHPguoQZ7WmUAhVTA0IMP6 p jQpLDgJ43ZaG4Zv3qWJiO689balD+egwiU2b7RICH4j6R66UVye+GPxq/gjzqbHwx79t54=; Timestamp: 12/17/2015 5:44:30 PM **** View Permissions for Alice **** Permission #1 Permission ID: Alice Collection Access Resource ID: kV5oAC56NwDON1RduEoCAA== Permission Mode: All Token: type=resource&ver=1&sig=BSzz/VNe9j4IPJ9M31Mf4Q==;Tcq/B X50njB1vmANZ/4aHj/3xNkghaqh1OfV95JMi6j4v7fkU+gyWe3mJasO3MJcoop9ixmVnB+RKOhFaSxE l P37SaGuIIik7GAWS+dcEBWglMefc95L2YkeNuZsjmmW5b+a8ELCUg7N45MKbpzkp5BrmmGVJ7h4Z4pf D rdmehYLuxSPLkr9ndbOOrD8E3bux6TgXCsgYQscpIlJHSKCKHUHfXWBP2Y1LV2zpJmRjis=; Timestamp: 12/17/2015 5:44:28 PM Total permissions for Alice: 1 **** View Permissions for Tom **** Permission #1 Permission ID: Tom Collection Access Resource ID: kV5oAALxKgCMai3JKWdfAA== Permission Mode: Read Token: type=resource&ver=1&sig=NPkWNJp1mAkCASE8KdR6PA==;ur/G2 V+fDamBmzECux000VnF5i28f8WRbPwEPxD1DMpFPqYcu45wlDyzT5A5gBr3/R3qqYkEVn8bU+een6Gl j L6vXzIwsZfL12u/1hW4mJT2as2PWH3eadry6Q/zRXHAxV8m+YuxSzlZPjBFyJ4Oi30mrTXbBAEafZhA 5 yvbHkpLmQkLCERy40FbIFOzG87ypljREpwWTKC/z8RSrsjITjAlfD/hVDoOyNJwX3HRaz4=; Timestamp: 12/17/2015 5:44:30 PM Total permissions for Tom: 1 **** Delete Permission Alice Collection Access from Alice **** Deleted permission Alice Collection Access from user Alice **** Delete Permission Tom Collection Access from Tom **** Deleted permission Tom Collection Access from user Tom **** Delete User Alice in myfirstdb **** Deleted user Alice from database myfirstdb **** Delete User Tom in myfirstdb **** Deleted user Tom from database myfirstdb Print Add Notes Bookmark this page
[ { "code": null, "e": 2604, "s": 2280, "text": "DocumentDB provides the concepts to control access to DocumentDB resources. Access to DocumentDB resources is governed by a master key token or a resource token. Connections based on resource tokens can only access the resources specified by the tokens and no other resources. Resource tokens are based on user permissions." }, { "code": null, "e": 2685, "s": 2604, "text": "First you create one or more users, and these are defined at the database level." }, { "code": null, "e": 2766, "s": 2685, "text": "First you create one or more users, and these are defined at the database level." }, { "code": null, "e": 2888, "s": 2766, "text": "Then you create one or more permissions for each user, based on the resources that you want to allow each user to access." }, { "code": null, "e": 3010, "s": 2888, "text": "Then you create one or more permissions for each user, based on the resources that you want to allow each user to access." }, { "code": null, "e": 3172, "s": 3010, "text": "Each permission generates a resource token that allows either read-only or full access to a given resource and that can be any user resource within the database." }, { "code": null, "e": 3334, "s": 3172, "text": "Each permission generates a resource token that allows either read-only or full access to a given resource and that can be any user resource within the database." }, { "code": null, "e": 3417, "s": 3334, "text": "Users are defined at the database level and permissions are defined for each user." }, { "code": null, "e": 3500, "s": 3417, "text": "Users are defined at the database level and permissions are defined for each user." }, { "code": null, "e": 3564, "s": 3500, "text": "Users and permissions apply to all collections in the database." }, { "code": null, "e": 3628, "s": 3564, "text": "Users and permissions apply to all collections in the database." }, { "code": null, "e": 3769, "s": 3628, "text": "Let’s take a look at a simple example in which we will learn how to define users and permissions to achieve granular security in DocumentDB." }, { "code": null, "e": 3847, "s": 3769, "text": "We will start with a new DocumentClient and query for the myfirstdb database." }, { "code": null, "e": 4433, "s": 3847, "text": "private static async Task CreateDocumentClient() {\n // Create a new instance of the DocumentClient\n using (var client = new DocumentClient(new Uri(EndpointUrl), AuthorizationKey)) {\n database = client.CreateDatabaseQuery(\"SELECT * FROM c WHERE c.id =\n 'myfirstdb'\").AsEnumerable().First();\n\t\t\t\n collection = client.CreateDocumentCollectionQuery(database.CollectionsLink,\n \"SELECT * FROM c WHERE c.id = 'MyCollection'\").AsEnumerable().First();\n\t\t\t\n var alice = await CreateUser(client, \"Alice\");\n var tom = await CreateUser(client, \"Tom\");\n }\n}" }, { "code": null, "e": 4481, "s": 4433, "text": "Following is the implementation for CreateUser." }, { "code": null, "e": 4914, "s": 4481, "text": "private async static Task<User> CreateUser(DocumentClient client, string userId) {\n Console.WriteLine();\n Console.WriteLine(\"**** Create User {0} in {1} ****\", userId, database.Id);\n\t\n var userDefinition = new User { Id = userId };\n var result = await client.CreateUserAsync(database.SelfLink, userDefinition);\n var user = result.Resource;\n\t\n Console.WriteLine(\"Created new user\");\n ViewUser(user);\n\t\n return user;\n}" }, { "code": null, "e": 5257, "s": 4914, "text": "Step 1 − Create two users, Alice and Tom like any resource we create, we construct a definition object with the desired Id and call the create method and in this case we're calling CreateUserAsync with the database's SelfLink and the userDefinition. We get back the result from whose resource property we obtain the newly created user object." }, { "code": null, "e": 5305, "s": 5257, "text": "Now to see these two new users in the database." }, { "code": null, "e": 6139, "s": 5305, "text": "private static void ViewUsers(DocumentClient client) {\n Console.WriteLine(); \n Console.WriteLine(\"**** View Users in {0} ****\", database.Id); \n\t\n var users = client.CreateUserQuery(database.UsersLink).ToList();\n var i = 0;\n\t\n foreach (var user in users) { \n i++; \n Console.WriteLine(); \n Console.WriteLine(\"User #{0}\", i); \n ViewUser(user); \n }\n\t\n Console.WriteLine();\n Console.WriteLine(\"Total users in database {0}: {1}\", database.Id, users.Count); \n}\n \nprivate static void ViewUser(User user) {\n Console.WriteLine(\"User ID: {0} \", user.Id); \n Console.WriteLine(\"Resource ID: {0} \", user.ResourceId); \n Console.WriteLine(\"Self Link: {0} \", user.SelfLink); \n Console.WriteLine(\"Permissions Link: {0} \", user.PermissionsLink); \n Console.WriteLine(\"Timestamp: {0} \", user.Timestamp); \n}" }, { "code": null, "e": 6286, "s": 6139, "text": "Step 2 − Call CreateUserQuery, against the database's UsersLink to retrieve a list of all users. Then loop through them and view their properties." }, { "code": null, "e": 6469, "s": 6286, "text": "Now we have to create them first. So let's say that we wanted to allow Alice read/write permissions to the MyCollection collection, but Tom can only read documents in the collection." }, { "code": null, "e": 6670, "s": 6469, "text": "await CreatePermission(client, alice, \"Alice Collection Access\", PermissionMode.All,\n collection);\n\t\nawait CreatePermission(client, tom, \"Tom Collection Access\", PermissionMode.Read,\n collection);" }, { "code": null, "e": 6788, "s": 6670, "text": "Step 3− Create a permission on a resource that is MyCollection collection so we need to get that resource a SelfLink." }, { "code": null, "e": 6905, "s": 6788, "text": "Step 4 − Then create a Permission.All on this collection for Alice and a Permission.Read on this collection for Tom." }, { "code": null, "e": 6959, "s": 6905, "text": "Following is the implementation for CreatePermission." }, { "code": null, "e": 7546, "s": 6959, "text": "private async static Task CreatePermission(DocumentClient client, User user,\n string permId, PermissionMode permissionMode, string resourceLink) {\n Console.WriteLine();\n Console.WriteLine(\"**** Create Permission {0} for {1} ****\", permId, user.Id);\n\t\n var permDefinition = new Permission {\n Id = permId,\n PermissionMode = permissionMode,\n ResourceLink = resourceLink\n };\n\t\n var result = await client.CreatePermissionAsync(user.SelfLink, permDefinition);\n var perm = result.Resource;\n Console.WriteLine(\"Created new permission\");\n ViewPermission(perm);\n}" }, { "code": null, "e": 7817, "s": 7546, "text": "As you should come to expect by now, we do this by creating a definition object for the new permission, which includes an Id and a permissionMode, which is either Permission.All or Permission.Read, and the SelfLink of the resource that's being secured by the permission." }, { "code": null, "e": 7926, "s": 7817, "text": "Step 5 − Call CreatePermissionAsync and get the created permission from the resource property in the result." }, { "code": null, "e": 8010, "s": 7926, "text": "To view the created permission, following is the implementation of ViewPermissions." }, { "code": null, "e": 8887, "s": 8010, "text": "private static void ViewPermissions(DocumentClient client, User user) {\n Console.WriteLine(); \n Console.WriteLine(\"**** View Permissions for {0} ****\", user.Id);\n\t\n var perms = client.CreatePermissionQuery(user.PermissionsLink).ToList();\n var i = 0; \n\t\n foreach (var perm in perms) {\n i++; \n Console.WriteLine(); \n Console.WriteLine(\"Permission #{0}\", i); \n ViewPermission(perm); \n } \n\t\n Console.WriteLine(); \n Console.WriteLine(\"Total permissions for {0}: {1}\", user.Id, perms.Count); \n}\n \nprivate static void ViewPermission(Permission perm) {\n Console.WriteLine(\"Permission ID: {0} \", perm.Id); \n Console.WriteLine(\"Resource ID: {0} \", perm.ResourceId); \n Console.WriteLine(\"Permission Mode: {0} \", perm.PermissionMode);\n Console.WriteLine(\"Token: {0} \", perm.Token); \n Console.WriteLine(\"Timestamp: {0} \", perm.Timestamp); \n}" }, { "code": null, "e": 9016, "s": 8887, "text": "This time, it's a permission query against the user's permissions link and we simply list each permission returned for the user." }, { "code": null, "e": 9064, "s": 9016, "text": "Let's delete the Alice’s and Tom’s permissions." }, { "code": null, "e": 9193, "s": 9064, "text": "await DeletePermission(client, alice, \"Alice Collection Access\"); \nawait DeletePermission(client, tom, \"Tom Collection Access\");" }, { "code": null, "e": 9247, "s": 9193, "text": "Following is the implementation for DeletePermission." }, { "code": null, "e": 9917, "s": 9247, "text": "private async static Task DeletePermission(DocumentClient client, User user,\n string permId) {\n Console.WriteLine(); \n Console.WriteLine(\"**** Delete Permission {0} from {1} ****\", permId, user.Id);\n\t\n var query = new SqlQuerySpec {\n QueryText = \"SELECT * FROM c WHERE c.id = @id\", \n Parameters = new SqlParameterCollection {\n new SqlParameter { Name = \"@id\", Value = permId }\n } \n };\n\t\n Permission perm = client.CreatePermissionQuery(user.PermissionsLink, query)\n .AsEnumerable().First(); \n await client.DeletePermissionAsync(perm.SelfLink); \n Console.WriteLine(\"Deleted permission {0} from user {1}\", permId, user.Id); \n}" }, { "code": null, "e": 10047, "s": 9917, "text": "Step 6 − To delete permissions, query by permission Id to get the SelfLink, and then using the SelfLink to delete the permission." }, { "code": null, "e": 10117, "s": 10047, "text": "Next, let’s delete the users themselves. Let’s delete both the users." }, { "code": null, "e": 10186, "s": 10117, "text": "await DeleteUser(client, \"Alice\"); \nawait DeleteUser(client, \"Tom\");" }, { "code": null, "e": 10234, "s": 10186, "text": "Following is the implementation for DeleteUser." }, { "code": null, "e": 10855, "s": 10234, "text": "private async static Task DeleteUser(DocumentClient client, string userId) {\n Console.WriteLine(); \n Console.WriteLine(\"**** Delete User {0} in {1} ****\", userId, database.Id);\n\t\n var query = new SqlQuerySpec { \n QueryText = \"SELECT * FROM c WHERE c.id = @id\", \n Parameters = new SqlParameterCollection {\n new SqlParameter { Name = \"@id\", Value = userId }\n } \n };\n\t\n User user = client.CreateUserQuery(database.SelfLink, query).AsEnumerable().First(); \n await client.DeleteUserAsync(user.SelfLink); \n Console.WriteLine(\"Deleted user {0} from database {1}\", userId, database.Id); \n}" }, { "code": null, "e": 10953, "s": 10855, "text": "Step 7 − First query to get her SelfLink and then call DeleteUserAsync to delete her user object." }, { "code": null, "e": 11052, "s": 10953, "text": "Following is the implementation of CreateDocumentClient task in which we call all the above tasks." }, { "code": null, "e": 12508, "s": 11052, "text": "private static async Task CreateDocumentClient() {\n // Create a new instance of the DocumentClient\n using (var client = new DocumentClient(new Uri(EndpointUrl), AuthorizationKey)) {\n database = client.CreateDatabaseQuery(\"SELECT * FROM c WHERE c.id =\n 'myfirstdb'\").AsEnumerable().First();\n\t\t\t\n collection = client.CreateDocumentCollectionQuery(database.CollectionsLink,\n \"SELECT * FROM c WHERE c.id = 'MyCollection'\").AsEnumerable().First();\n\t\t\t\n ViewUsers(client);\n\t\t\n var alice = await CreateUser(client, \"Alice\");\n var tom = await CreateUser(client, \"Tom\");\n ViewUsers(client);\n\t\t\n ViewPermissions(client, alice);\n ViewPermissions(client, tom);\n\t\t\n string collectionLink = client.CreateDocumentCollectionQuery(database.SelfLink,\n \"SELECT VALUE c._self FROM c WHERE c.id = 'MyCollection'\")\n .AsEnumerable().First().Value;\n\t\t\t\n await CreatePermission(client, alice, \"Alice Collection Access\", PermissionMode.All,\n collectionLink);\n\t\t\t\n await CreatePermission(client, tom, \"Tom Collection Access\", PermissionMode.Read,\n collectionLink);\n\t\t\t\n ViewPermissions(client, alice);\n ViewPermissions(client, tom);\n\t\t\n await DeletePermission(client, alice, \"Alice Collection Access\");\n await DeletePermission(client, tom, \"Tom Collection Access\");\n\t\t\n await DeleteUser(client, \"Alice\");\n await DeleteUser(client, \"Tom\");\n }\n}" }, { "code": null, "e": 12592, "s": 12508, "text": "When the above code is compiled and executed you will receive the following output." }, { "code": null, "e": 16563, "s": 12592, "text": "**** View Users in myfirstdb **** \n \nTotal users in database myfirstdb: 0 \n \n**** Create User Alice in myfirstdb **** \nCreated new user \n User ID: Alice \n Resource ID: kV5oAC56NwA= \n Self Link: dbs/kV5oAA==/users/kV5oAC56NwA=/ \n Permissions Link: dbs/kV5oAA==/users/kV5oAC56NwA=/permissions/ \n Timestamp: 12/17/2015 5:44:19 PM\n\t\t \n**** Create User Tom in myfirstdb **** \nCreated new user \n User ID: Tom \n Resource ID: kV5oAALxKgA= \n Self Link: dbs/kV5oAA==/users/kV5oAALxKgA=/ \n Permissions Link: dbs/kV5oAA==/users/kV5oAALxKgA=/permissions/ \n Timestamp: 12/17/2015 5:44:21 PM\n\t\t \n**** View Users in myfirstdb ****\n \nUser #1 \n User ID: Tom \n Resource ID: kV5oAALxKgA= \n Self Link: dbs/kV5oAA==/users/kV5oAALxKgA=/ \n Permissions Link: dbs/kV5oAA==/users/kV5oAALxKgA=/permissions/ \n Timestamp: 12/17/2015 5:44:21 PM \n\t\t \nUser #2 \n User ID: Alice \n Resource ID: kV5oAC56NwA= \n Self Link: dbs/kV5oAA==/users/kV5oAC56NwA=/ \n Permissions Link: dbs/kV5oAA==/users/kV5oAC56NwA=/permissions/ \n Timestamp: 12/17/2015 5:44:19 PM\n\t\t \nTotal users in database myfirstdb: 2\n \n**** View Permissions for Alice **** \n \nTotal permissions for Alice: 0 \n\n**** View Permissions for Tom **** \n \nTotal permissions for Tom: 0 \n\n**** Create Permission Alice Collection Access for Alice **** \nCreated new permission \n Permission ID: Alice Collection Access \n Resource ID: kV5oAC56NwDON1RduEoCAA== \n Permission Mode: All\n Token: type=resource&ver=1&sig=zB6hfvvleC0oGGbq5cc67w==;Zt3Lx \nOl14h8pd6/tyF1h62zbZKk9VwEIATIldw4ZyipQGW951kirueAKdeb3MxzQ7eCvDfvp7Y/ZxFpnip/D G \nJYcPyim5cf+dgLvos6fUuiKSFSul7uEKqp5JmJqUCyAvD7w+qt1Qr1PmrJDyAIgbZDBFWGe2VT9FaBH o \nPYwrLjRlnH0AxfbrR+T/UpWMSSHtLB8JvNFZNSH8hRjmQupuTSxCTYEC89bZ/pS6fNmNg8=; \n Timestamp: 12/17/2015 5:44:28 PM\n\t\t \n**** Create Permission Tom Collection Access for Tom **** \nCreated new permission \n Permission ID: Tom Collection Access \n Resource ID: kV5oAALxKgCMai3JKWdfAA== \n Permission Mode: Read \n Token: type=resource&ver=1&sig=ieBHKeyi6EY9ZOovDpe76w==;92gwq \nV4AxKaCJ2dLS02VnJiig/5AEbPcfo1xvOjR10uK3a3FUMFULgsaK8nzxdz6hLVCIKUj6hvMOTOSN8Lt 7 \ni30mVqzpzCfe7JO3TYSJEI9D0/5HbMIEgaNJiCu0JPPwsjVecTytiLN56FHPguoQZ7WmUAhVTA0IMP6 p \njQpLDgJ43ZaG4Zv3qWJiO689balD+egwiU2b7RICH4j6R66UVye+GPxq/gjzqbHwx79t54=; \n Timestamp: 12/17/2015 5:44:30 PM\n\t\t \n**** View Permissions for Alice ****\n \nPermission #1 \n Permission ID: Alice Collection Access \n Resource ID: kV5oAC56NwDON1RduEoCAA== \n Permission Mode: All \n Token: type=resource&ver=1&sig=BSzz/VNe9j4IPJ9M31Mf4Q==;Tcq/B \nX50njB1vmANZ/4aHj/3xNkghaqh1OfV95JMi6j4v7fkU+gyWe3mJasO3MJcoop9ixmVnB+RKOhFaSxE l \nP37SaGuIIik7GAWS+dcEBWglMefc95L2YkeNuZsjmmW5b+a8ELCUg7N45MKbpzkp5BrmmGVJ7h4Z4pf D \nrdmehYLuxSPLkr9ndbOOrD8E3bux6TgXCsgYQscpIlJHSKCKHUHfXWBP2Y1LV2zpJmRjis=; \n Timestamp: 12/17/2015 5:44:28 PM\n\t\t \nTotal permissions for Alice: 1\n \n**** View Permissions for Tom ****\nPermission #1 \n Permission ID: Tom Collection Access \n Resource ID: kV5oAALxKgCMai3JKWdfAA== \n Permission Mode: Read \n Token: type=resource&ver=1&sig=NPkWNJp1mAkCASE8KdR6PA==;ur/G2 \nV+fDamBmzECux000VnF5i28f8WRbPwEPxD1DMpFPqYcu45wlDyzT5A5gBr3/R3qqYkEVn8bU+een6Gl j \nL6vXzIwsZfL12u/1hW4mJT2as2PWH3eadry6Q/zRXHAxV8m+YuxSzlZPjBFyJ4Oi30mrTXbBAEafZhA 5 \nyvbHkpLmQkLCERy40FbIFOzG87ypljREpwWTKC/z8RSrsjITjAlfD/hVDoOyNJwX3HRaz4=; \n Timestamp: 12/17/2015 5:44:30 PM\n\t\t \nTotal permissions for Tom: 1\n \n**** Delete Permission Alice Collection Access from Alice **** \nDeleted permission Alice Collection Access from user Alice\n \n**** Delete Permission Tom Collection Access from Tom **** \nDeleted permission Tom Collection Access from user Tom\n \n**** Delete User Alice in myfirstdb **** \nDeleted user Alice from database myfirstdb\n \n**** Delete User Tom in myfirstdb **** \nDeleted user Tom from database myfirstdb\n" }, { "code": null, "e": 16570, "s": 16563, "text": " Print" }, { "code": null, "e": 16581, "s": 16570, "text": " Add Notes" } ]
How to make div height expand with its content using CSS ? - GeeksforGeeks
20 Dec, 2021 The height property is used to set the height of an element. The height property does not contains padding, margin and border of element. The height property contains many values which define the height of an element. The height property values are listed below:Syntax: height: length|percentage|auto|initial|inherit; Property Values: height: auto; It is used to set height property to its default value. If the height property set to auto then the browser calculates the height of element. height: length; It is used to set the height of element in form of px, cm etc. The length can not be negative. height: initial; It is used to set height property to its default value. height: inherit; It is used to set height property from its parent element. Example 1: This example use height: auto; property to display the content. html <!DOCTYPE html><html> <head> <!-- style to set height property to display content --> <style> p { color:white; } .main { background-color:black; height:auto; border-radius: 20px 20px 0px 0px; } .left-column { background-color:indigo; height:120px; width:49%; float:left; border-bottom-left-radius: 20px; } .right-column{ background-color:green; height:7.5em; width:49%; float:right; border-bottom-right-radius: 20px; } h1{ color:Green; } </style></head> <body> <center> <h1>GeeksforGeeks</h1> <div class="main"> <p> Also, any geeks can help other geeks by writing articles on the GeeksforGeeks, publishing articles follow few steps that are Articles that need little modification/improvement from reviewers are published first. To quickly get your articles reviewed, please refer existing articles, their formatting style, coding style, and try to make you are close to them. </p> </div> <div class="left-column"> <p> It is a good platform to learn programming. It is an educational website. Prepare for the Recruitment drive of product based companies like Microsoft, Amazon, Adobe etc with a free online placement preparation course. </p> </div> <div class="right-column"> <p> The course focuses on various MCQ's & Coding question likely to be asked in the interviews & make your upcoming placement season efficient and successful. </p> </div> </center></body> </html> Output Example 2: This example use height: inherit property to display the content. html <!DOCTYPE html><html> <head> <!-- CSS style to set height property of content --> <style> .auto { height:auto; background-color:orange; } .inherit { height:inherit; background-color:cyan; } .percentage { height:25%; } h1 { color:green; } </style></head> <body style = "text-align:center;"> <h1>GeeksforGeeks</h1> <div class="auto"> <p> Also, any geeks can help other geeks by writing articles on the GeeksforGeeks, publishing articles follow few steps that are Articles that need little modification/improvement from reviewers are published first. To quickly get your articles reviewed, please refer existing articles, their formatting style, coding style, and try to make you are close to them. </p> <div class="inherit"> <p> It is a good platform to learn programming. It is an educational website. Prepare for the Recruitment drive of product based companies like Microsoft, Amazon, Adobe etc with a free online placement preparation course. </p> </div> <div class="percentage"> <p> The course focuses on various MCQ's & Coding question likely to be asked in the interviews & make your upcoming placement season efficient and successful. </p> </div> </div></body> </html> Output: shubham_singh anikaseth98 CSS-Misc Picked Web-Programs Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Roadmap to Become a Web Developer in 2022 Installation of Node.js on Linux How to fetch data from an API in ReactJS ? How to insert spaces/tabs in text using HTML/CSS? Top 10 Projects For Beginners To Practice HTML and CSS Skills Convert a string to an integer in JavaScript Difference between var, let and const keywords in JavaScript How to calculate the number of days between two dates in javascript? Differences between Functional Components and Class Components in React How to create footer to stay at the bottom of a Web page?
[ { "code": null, "e": 24870, "s": 24842, "text": "\n20 Dec, 2021" }, { "code": null, "e": 25141, "s": 24870, "text": "The height property is used to set the height of an element. The height property does not contains padding, margin and border of element. The height property contains many values which define the height of an element. The height property values are listed below:Syntax: " }, { "code": null, "e": 25189, "s": 25141, "text": "height: length|percentage|auto|initial|inherit;" }, { "code": null, "e": 25208, "s": 25189, "text": "Property Values: " }, { "code": null, "e": 25364, "s": 25208, "text": "height: auto; It is used to set height property to its default value. If the height property set to auto then the browser calculates the height of element." }, { "code": null, "e": 25475, "s": 25364, "text": "height: length; It is used to set the height of element in form of px, cm etc. The length can not be negative." }, { "code": null, "e": 25548, "s": 25475, "text": "height: initial; It is used to set height property to its default value." }, { "code": null, "e": 25624, "s": 25548, "text": "height: inherit; It is used to set height property from its parent element." }, { "code": null, "e": 25701, "s": 25624, "text": "Example 1: This example use height: auto; property to display the content. " }, { "code": null, "e": 25706, "s": 25701, "text": "html" }, { "code": "<!DOCTYPE html><html> <head> <!-- style to set height property to display content --> <style> p { color:white; } .main { background-color:black; height:auto; border-radius: 20px 20px 0px 0px; } .left-column { background-color:indigo; height:120px; width:49%; float:left; border-bottom-left-radius: 20px; } .right-column{ background-color:green; height:7.5em; width:49%; float:right; border-bottom-right-radius: 20px; } h1{ color:Green; } </style></head> <body> <center> <h1>GeeksforGeeks</h1> <div class=\"main\"> <p> Also, any geeks can help other geeks by writing articles on the GeeksforGeeks, publishing articles follow few steps that are Articles that need little modification/improvement from reviewers are published first. To quickly get your articles reviewed, please refer existing articles, their formatting style, coding style, and try to make you are close to them. </p> </div> <div class=\"left-column\"> <p> It is a good platform to learn programming. It is an educational website. Prepare for the Recruitment drive of product based companies like Microsoft, Amazon, Adobe etc with a free online placement preparation course. </p> </div> <div class=\"right-column\"> <p> The course focuses on various MCQ's & Coding question likely to be asked in the interviews & make your upcoming placement season efficient and successful. </p> </div> </center></body> </html> ", "e": 27628, "s": 25706, "text": null }, { "code": null, "e": 27636, "s": 27628, "text": "Output " }, { "code": null, "e": 27715, "s": 27636, "text": "Example 2: This example use height: inherit property to display the content. " }, { "code": null, "e": 27720, "s": 27715, "text": "html" }, { "code": "<!DOCTYPE html><html> <head> <!-- CSS style to set height property of content --> <style> .auto { height:auto; background-color:orange; } .inherit { height:inherit; background-color:cyan; } .percentage { height:25%; } h1 { color:green; } </style></head> <body style = \"text-align:center;\"> <h1>GeeksforGeeks</h1> <div class=\"auto\"> <p> Also, any geeks can help other geeks by writing articles on the GeeksforGeeks, publishing articles follow few steps that are Articles that need little modification/improvement from reviewers are published first. To quickly get your articles reviewed, please refer existing articles, their formatting style, coding style, and try to make you are close to them. </p> <div class=\"inherit\"> <p> It is a good platform to learn programming. It is an educational website. Prepare for the Recruitment drive of product based companies like Microsoft, Amazon, Adobe etc with a free online placement preparation course. </p> </div> <div class=\"percentage\"> <p> The course focuses on various MCQ's & Coding question likely to be asked in the interviews & make your upcoming placement season efficient and successful. </p> </div> </div></body> </html> ", "e": 29400, "s": 27720, "text": null }, { "code": null, "e": 29409, "s": 29400, "text": "Output: " }, { "code": null, "e": 29423, "s": 29409, "text": "shubham_singh" }, { "code": null, "e": 29435, "s": 29423, "text": "anikaseth98" }, { "code": null, "e": 29444, "s": 29435, "text": "CSS-Misc" }, { "code": null, "e": 29451, "s": 29444, "text": "Picked" }, { "code": null, "e": 29464, "s": 29451, "text": "Web-Programs" }, { "code": null, "e": 29481, "s": 29464, "text": "Web Technologies" }, { "code": null, "e": 29579, "s": 29481, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29621, "s": 29579, "text": "Roadmap to Become a Web Developer in 2022" }, { "code": null, "e": 29654, "s": 29621, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 29697, "s": 29654, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 29747, "s": 29697, "text": "How to insert spaces/tabs in text using HTML/CSS?" }, { "code": null, "e": 29809, "s": 29747, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 29854, "s": 29809, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 29915, "s": 29854, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 29984, "s": 29915, "text": "How to calculate the number of days between two dates in javascript?" }, { "code": null, "e": 30056, "s": 29984, "text": "Differences between Functional Components and Class Components in React" } ]
Ensemble models for Classification | by Gaurika Tyagi | Towards Data Science
You have cleaned your data and removed all correlating features. You have also visualized your dataset and know the class labels are separable. You have also tuned your hyper-parameters. That's great, but why isn’t your model performing well? Did you try stacking your models? Traditionally, we have modeled our data with a single algorithm. That might be a Logistic Regression, Gaussian Naive Bayes, or XGBoost. Here’s what an ensemble stacking model does: An algorithm that is used to combine the base estimators is called the meta learner. We can determine how we want this algorithm to respond to different predictions from other models(classifiers in this case). It can be: Predictions of estimatorsPredictions as well as the original training data Predictions of estimators Predictions as well as the original training data But is it the final class predictions only? No, you can choose what metric drives that decision: It could be 'predict_proba', or 'predict' or bothYou can also use other 'decision_function' in sklearn It could be 'predict_proba', or 'predict' or both You can also use other 'decision_function' in sklearn The final meta learner can then be any of the estimators (by default sklearn has logistic regression) We take a baseline Gaussian Naive Bayes estimator and compare all future results to its prediction accuracy: rf = OneVsRestClassifier(estimator = GaussianNB())cv = RepeatedStratifiedKFold(n_splits=10, n_repeats=3, random_state=20)n_scores = cross_val_score(rf, X, y, scoring='f1_weighted', cv=cv, error_score='raise')print(n_scores)print('Baseline scores \n mean f1 weighted: %.3f with a %.3f standard deviation in scores ' % (np.mean(n_scores), np.std(n_scores))) In the end, we wanted a classifier with an F1 score higher than 81.1% and we ended up getting an F1 score of 96.7% with a stacking model. In the healthcare setup, I will take that 0.1% improvement over SVC models and not trade-off the stacked model’s complexity! You can find the full code here: https://github.com/gaurikatyagi/Machine-Learning/blob/master/Classification/Ensemble%20Model-%20Stacked%20Classification.ipynb Go stack now...
[ { "code": null, "e": 415, "s": 172, "text": "You have cleaned your data and removed all correlating features. You have also visualized your dataset and know the class labels are separable. You have also tuned your hyper-parameters. That's great, but why isn’t your model performing well?" }, { "code": null, "e": 585, "s": 415, "text": "Did you try stacking your models? Traditionally, we have modeled our data with a single algorithm. That might be a Logistic Regression, Gaussian Naive Bayes, or XGBoost." }, { "code": null, "e": 630, "s": 585, "text": "Here’s what an ensemble stacking model does:" }, { "code": null, "e": 851, "s": 630, "text": "An algorithm that is used to combine the base estimators is called the meta learner. We can determine how we want this algorithm to respond to different predictions from other models(classifiers in this case). It can be:" }, { "code": null, "e": 926, "s": 851, "text": "Predictions of estimatorsPredictions as well as the original training data" }, { "code": null, "e": 952, "s": 926, "text": "Predictions of estimators" }, { "code": null, "e": 1002, "s": 952, "text": "Predictions as well as the original training data" }, { "code": null, "e": 1099, "s": 1002, "text": "But is it the final class predictions only? No, you can choose what metric drives that decision:" }, { "code": null, "e": 1202, "s": 1099, "text": "It could be 'predict_proba', or 'predict' or bothYou can also use other 'decision_function' in sklearn" }, { "code": null, "e": 1252, "s": 1202, "text": "It could be 'predict_proba', or 'predict' or both" }, { "code": null, "e": 1306, "s": 1252, "text": "You can also use other 'decision_function' in sklearn" }, { "code": null, "e": 1408, "s": 1306, "text": "The final meta learner can then be any of the estimators (by default sklearn has logistic regression)" }, { "code": null, "e": 1517, "s": 1408, "text": "We take a baseline Gaussian Naive Bayes estimator and compare all future results to its prediction accuracy:" }, { "code": null, "e": 1873, "s": 1517, "text": "rf = OneVsRestClassifier(estimator = GaussianNB())cv = RepeatedStratifiedKFold(n_splits=10, n_repeats=3, random_state=20)n_scores = cross_val_score(rf, X, y, scoring='f1_weighted', cv=cv, error_score='raise')print(n_scores)print('Baseline scores \\n mean f1 weighted: %.3f with a %.3f standard deviation in scores ' % (np.mean(n_scores), np.std(n_scores)))" }, { "code": null, "e": 2011, "s": 1873, "text": "In the end, we wanted a classifier with an F1 score higher than 81.1% and we ended up getting an F1 score of 96.7% with a stacking model." }, { "code": null, "e": 2136, "s": 2011, "text": "In the healthcare setup, I will take that 0.1% improvement over SVC models and not trade-off the stacked model’s complexity!" }, { "code": null, "e": 2296, "s": 2136, "text": "You can find the full code here: https://github.com/gaurikatyagi/Machine-Learning/blob/master/Classification/Ensemble%20Model-%20Stacked%20Classification.ipynb" } ]
IDE | GeeksforGeeks | A computer science portal for geeks
Please enter your email address or userHandle.
[]
Finding the LCM and HCF of decimal numbers - GeeksforGeeks
12 Aug, 2020 Finding the LCM and HCF are most frequently asked questions in any competitive exams. Finding LCM and HCF for natural numbers are taught in our school level but in some exams they also ask to find the LCM and HCF of decimal numbers. There is easy process to find the LCM and HCF of decimal numbers similar to natural numbers with some changes. Example-1:Find the HCF and LCM of 3, 2.7, 0.09 Explanation: Step-1:Write all the numbers with same number of digits after decimal point.3.00, 2.70, 0.09 3.00, 2.70, 0.09 Step-2:Now count the number of digits after decimal point (value is 2 for above problem) and calculate 10 power of the obtained value. Let the number be n = 102 = 100. Step-3:Now remove the decimal point and find the LCM and HCF of the numbers.LCM(300, 270, 9) and HCF(300, 270, 9). 300 = 22 x 31 x 52 270 = 21 x 33 x 51 9 = 20 x 32 x 50 LCM(300, 270, 9) = 22 x 33 x 52 = 2700 HCF(300, 270, 9) = 20 x 31 x 50 = 3 For finding the LCM and HCF, we should write the number in the power of prime numbers as written above. We should ensure that all the numbers should be written as power of prime numbers of same number. Example : 9 can be written as 32 but the other two numbers also contain 2 and 5 as primes. So we can write other two numbers as powers of 0. So 9 can be written as 20 x 32 x 50 and it won’t change the value of the number.Since we have our numbers in form of power of primes, Now the LCM is the number formed as the product of primes with its power is maximum value of the power of the same prime in given numbers.LCM = 2 power of max(2, 1, 0) x 3 power of max(1, 3, 2) x 5 power of max(2, 1, 0) = 22 x 33 x 52 = 2700 HCF calculation is similar but with only one change. Instead of taking max in power we take min in power.HCF = 2 power of min(2, 1, 0) x 3 power of min(1, 3, 2) x 5 power of min(2, 1, 0) = 20 x 31 x 50 = 3 LCM(300, 270, 9) and HCF(300, 270, 9). 300 = 22 x 31 x 52 270 = 21 x 33 x 51 9 = 20 x 32 x 50 LCM(300, 270, 9) = 22 x 33 x 52 = 2700 HCF(300, 270, 9) = 20 x 31 x 50 = 3 For finding the LCM and HCF, we should write the number in the power of prime numbers as written above. We should ensure that all the numbers should be written as power of prime numbers of same number. Example : 9 can be written as 32 but the other two numbers also contain 2 and 5 as primes. So we can write other two numbers as powers of 0. So 9 can be written as 20 x 32 x 50 and it won’t change the value of the number. Since we have our numbers in form of power of primes, Now the LCM is the number formed as the product of primes with its power is maximum value of the power of the same prime in given numbers. LCM = 2 power of max(2, 1, 0) x 3 power of max(1, 3, 2) x 5 power of max(2, 1, 0) = 22 x 33 x 52 = 2700 HCF calculation is similar but with only one change. Instead of taking max in power we take min in power. HCF = 2 power of min(2, 1, 0) x 3 power of min(1, 3, 2) x 5 power of min(2, 1, 0) = 20 x 31 x 50 = 3 Step-4:Now divide the obtained answer with our number n in step 2. The value we obtain is our required answer.LCM(3, 2.7, 9) = 2700/100 = 27 HCF(3, 2.7, 9) = 3/100 = 0.03 LCM(3, 2.7, 9) = 2700/100 = 27 HCF(3, 2.7, 9) = 3/100 = 0.03 Example-2:Find LCM and HCF of 0.216, 6, 2. Explanation:By using the above steps, in similar way we can do this problem. Step-1:0.216, 6, 2 -> 0.216, 6.000, 2.000 0.216, 6, 2 -> 0.216, 6.000, 2.000 Step-2:Since the number of digits after decimal point is 3, the value of n = 103 = 1000. Step-3:Find LCM (216, 6000, 2000) and HCF (216, 600, 200).216 = 23 x 33 = 23 x 33 x 50 6000 = 24 x 31 x 53 = 24 x 31 x 53 2000 = 24 x 53 = 24 x 30 x 53 LCM(216, 600, 200) = 24 x 33 x 53 = 54000 HCF(216, 600, 200) = 23 x 30 x 50 = 8 216 = 23 x 33 = 23 x 33 x 50 6000 = 24 x 31 x 53 = 24 x 31 x 53 2000 = 24 x 53 = 24 x 30 x 53 LCM(216, 600, 200) = 24 x 33 x 53 = 54000 HCF(216, 600, 200) = 23 x 30 x 50 = 8 Step-4:LCM(0.216, 6, 2) = 5400/1000 = 54 HCF(0.216, 6, 2) = 8/1000 = 0.008 LCM(0.216, 6, 2) = 5400/1000 = 54 HCF(0.216, 6, 2) = 8/1000 = 0.008 Example-3:Find the LCM and HCF of 0.63, 1.05. Explanation : Step-1:0.63, 1.05 -> 0.63, 1.05 0.63, 1.05 -> 0.63, 1.05 Step-2:Since the number of digits after decimal point is 2, the value of n = 102 = 100. Step-3:Remove decimal point and find LCM (63, 105) and HCF(63, 105).63 = 32 x 50 x 71 105 = 31 x 51 x 71 LCM (63, 105) = 32 x 51 x 71 = 315 HCF(63, 105) = 31 x 50 x 71 = 21 63 = 32 x 50 x 71 105 = 31 x 51 x 71 LCM (63, 105) = 32 x 51 x 71 = 315 HCF(63, 105) = 31 x 50 x 71 = 21 Step-4:LCM (0.63, 1.05) = 315/100 = 3.15 HCF(0.63, 1.05) = 21/100 = 2.1 LCM (0.63, 1.05) = 315/100 = 3.15 HCF(0.63, 1.05) = 21/100 = 2.1 In this simple way we can find the LCM and HCF of any number of decimals of any number. Aptitude Engineering Mathematics GATE GRE Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Mathematics | Walks, Trails, Paths, Cycles and Circuits in Graph Arrow Symbols in LaTeX Newton's Divided Difference Interpolation Formula Set Notations in LaTeX Mathematics | Graph Isomorphisms and Connectivity GATE | GATE-IT-2004 | Question 66 GATE | GATE-CS-2016 (Set 2) | Question 48 GATE | GATE CS 2008 | Question 66 GATE | GATE-CS-2014-(Set-3) | Question 65 GATE | GATE-CS-2006 | Question 49
[ { "code": null, "e": 24760, "s": 24732, "text": "\n12 Aug, 2020" }, { "code": null, "e": 24993, "s": 24760, "text": "Finding the LCM and HCF are most frequently asked questions in any competitive exams. Finding LCM and HCF for natural numbers are taught in our school level but in some exams they also ask to find the LCM and HCF of decimal numbers." }, { "code": null, "e": 25104, "s": 24993, "text": "There is easy process to find the LCM and HCF of decimal numbers similar to natural numbers with some changes." }, { "code": null, "e": 25151, "s": 25104, "text": "Example-1:Find the HCF and LCM of 3, 2.7, 0.09" }, { "code": null, "e": 25164, "s": 25151, "text": "Explanation:" }, { "code": null, "e": 25258, "s": 25164, "text": "Step-1:Write all the numbers with same number of digits after decimal point.3.00, 2.70, 0.09 " }, { "code": null, "e": 25276, "s": 25258, "text": "3.00, 2.70, 0.09 " }, { "code": null, "e": 25444, "s": 25276, "text": "Step-2:Now count the number of digits after decimal point (value is 2 for above problem) and calculate 10 power of the obtained value. Let the number be n = 102 = 100." }, { "code": null, "e": 26623, "s": 25444, "text": "Step-3:Now remove the decimal point and find the LCM and HCF of the numbers.LCM(300, 270, 9) and HCF(300, 270, 9).\n\n300 = 22 x 31 x 52\n\n270 = 21 x 33 x 51\n\n 9 = 20 x 32 x 50\n\nLCM(300, 270, 9) = 22 x 33 x 52 = 2700\n\nHCF(300, 270, 9) = 20 x 31 x 50 = 3 For finding the LCM and HCF, we should write the number in the power of prime numbers as written above. We should ensure that all the numbers should be written as power of prime numbers of same number. Example : 9 can be written as 32 but the other two numbers also contain 2 and 5 as primes. So we can write other two numbers as powers of 0. So 9 can be written as 20 x 32 x 50 and it won’t change the value of the number.Since we have our numbers in form of power of primes, Now the LCM is the number formed as the product of primes with its power is maximum value of the power of the same prime in given numbers.LCM = 2 power of max(2, 1, 0) x 3 power of max(1, 3, 2) x 5 power of max(2, 1, 0) \n= 22 x 33 x 52 = 2700 HCF calculation is similar but with only one change. Instead of taking max in power we take min in power.HCF = 2 power of min(2, 1, 0) x 3 power of min(1, 3, 2) x 5 power of min(2, 1, 0) \n= 20 x 31 x 50 = 3 " }, { "code": null, "e": 26799, "s": 26623, "text": "LCM(300, 270, 9) and HCF(300, 270, 9).\n\n300 = 22 x 31 x 52\n\n270 = 21 x 33 x 51\n\n 9 = 20 x 32 x 50\n\nLCM(300, 270, 9) = 22 x 33 x 52 = 2700\n\nHCF(300, 270, 9) = 20 x 31 x 50 = 3 " }, { "code": null, "e": 27223, "s": 26799, "text": "For finding the LCM and HCF, we should write the number in the power of prime numbers as written above. We should ensure that all the numbers should be written as power of prime numbers of same number. Example : 9 can be written as 32 but the other two numbers also contain 2 and 5 as primes. So we can write other two numbers as powers of 0. So 9 can be written as 20 x 32 x 50 and it won’t change the value of the number." }, { "code": null, "e": 27416, "s": 27223, "text": "Since we have our numbers in form of power of primes, Now the LCM is the number formed as the product of primes with its power is maximum value of the power of the same prime in given numbers." }, { "code": null, "e": 27522, "s": 27416, "text": "LCM = 2 power of max(2, 1, 0) x 3 power of max(1, 3, 2) x 5 power of max(2, 1, 0) \n= 22 x 33 x 52 = 2700 " }, { "code": null, "e": 27628, "s": 27522, "text": "HCF calculation is similar but with only one change. Instead of taking max in power we take min in power." }, { "code": null, "e": 27731, "s": 27628, "text": "HCF = 2 power of min(2, 1, 0) x 3 power of min(1, 3, 2) x 5 power of min(2, 1, 0) \n= 20 x 31 x 50 = 3 " }, { "code": null, "e": 27904, "s": 27731, "text": "Step-4:Now divide the obtained answer with our number n in step 2. The value we obtain is our required answer.LCM(3, 2.7, 9) = 2700/100 = 27\n\nHCF(3, 2.7, 9) = 3/100 = 0.03\n" }, { "code": null, "e": 27967, "s": 27904, "text": "LCM(3, 2.7, 9) = 2700/100 = 27\n\nHCF(3, 2.7, 9) = 3/100 = 0.03\n" }, { "code": null, "e": 28010, "s": 27967, "text": "Example-2:Find LCM and HCF of 0.216, 6, 2." }, { "code": null, "e": 28087, "s": 28010, "text": "Explanation:By using the above steps, in similar way we can do this problem." }, { "code": null, "e": 28130, "s": 28087, "text": "Step-1:0.216, 6, 2 -> 0.216, 6.000, 2.000 " }, { "code": null, "e": 28166, "s": 28130, "text": "0.216, 6, 2 -> 0.216, 6.000, 2.000 " }, { "code": null, "e": 28255, "s": 28166, "text": "Step-2:Since the number of digits after decimal point is 3, the value of n = 103 = 1000." }, { "code": null, "e": 28492, "s": 28255, "text": "Step-3:Find LCM (216, 6000, 2000) and HCF (216, 600, 200).216 = 23 x 33 = 23 x 33 x 50\n\n6000 = 24 x 31 x 53 = 24 x 31 x 53\n\n2000 = 24 x 53 = 24 x 30 x 53\n\nLCM(216, 600, 200) = 24 x 33 x 53 = 54000\n\nHCF(216, 600, 200) = 23 x 30 x 50 = 8\n" }, { "code": null, "e": 28671, "s": 28492, "text": "216 = 23 x 33 = 23 x 33 x 50\n\n6000 = 24 x 31 x 53 = 24 x 31 x 53\n\n2000 = 24 x 53 = 24 x 30 x 53\n\nLCM(216, 600, 200) = 24 x 33 x 53 = 54000\n\nHCF(216, 600, 200) = 23 x 30 x 50 = 8\n" }, { "code": null, "e": 28748, "s": 28671, "text": "Step-4:LCM(0.216, 6, 2) = 5400/1000 = 54\n\nHCF(0.216, 6, 2) = 8/1000 = 0.008 " }, { "code": null, "e": 28818, "s": 28748, "text": "LCM(0.216, 6, 2) = 5400/1000 = 54\n\nHCF(0.216, 6, 2) = 8/1000 = 0.008 " }, { "code": null, "e": 28864, "s": 28818, "text": "Example-3:Find the LCM and HCF of 0.63, 1.05." }, { "code": null, "e": 28878, "s": 28864, "text": "Explanation :" }, { "code": null, "e": 28911, "s": 28878, "text": "Step-1:0.63, 1.05 -> 0.63, 1.05 " }, { "code": null, "e": 28937, "s": 28911, "text": "0.63, 1.05 -> 0.63, 1.05 " }, { "code": null, "e": 29025, "s": 28937, "text": "Step-2:Since the number of digits after decimal point is 2, the value of n = 102 = 100." }, { "code": null, "e": 29202, "s": 29025, "text": "Step-3:Remove decimal point and find LCM (63, 105) and HCF(63, 105).63 = 32 x 50 x 71\n\n105 = 31 x 51 x 71\n\nLCM (63, 105) = 32 x 51 x 71 = 315\n\nHCF(63, 105) = 31 x 50 x 71 = 21\n" }, { "code": null, "e": 29311, "s": 29202, "text": "63 = 32 x 50 x 71\n\n105 = 31 x 51 x 71\n\nLCM (63, 105) = 32 x 51 x 71 = 315\n\nHCF(63, 105) = 31 x 50 x 71 = 21\n" }, { "code": null, "e": 29385, "s": 29311, "text": "Step-4:LCM (0.63, 1.05) = 315/100 = 3.15\n\nHCF(0.63, 1.05) = 21/100 = 2.1\n" }, { "code": null, "e": 29452, "s": 29385, "text": "LCM (0.63, 1.05) = 315/100 = 3.15\n\nHCF(0.63, 1.05) = 21/100 = 2.1\n" }, { "code": null, "e": 29540, "s": 29452, "text": "In this simple way we can find the LCM and HCF of any number of decimals of any number." }, { "code": null, "e": 29549, "s": 29540, "text": "Aptitude" }, { "code": null, "e": 29573, "s": 29549, "text": "Engineering Mathematics" }, { "code": null, "e": 29578, "s": 29573, "text": "GATE" }, { "code": null, "e": 29582, "s": 29578, "text": "GRE" }, { "code": null, "e": 29680, "s": 29582, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29745, "s": 29680, "text": "Mathematics | Walks, Trails, Paths, Cycles and Circuits in Graph" }, { "code": null, "e": 29768, "s": 29745, "text": "Arrow Symbols in LaTeX" }, { "code": null, "e": 29818, "s": 29768, "text": "Newton's Divided Difference Interpolation Formula" }, { "code": null, "e": 29841, "s": 29818, "text": "Set Notations in LaTeX" }, { "code": null, "e": 29891, "s": 29841, "text": "Mathematics | Graph Isomorphisms and Connectivity" }, { "code": null, "e": 29925, "s": 29891, "text": "GATE | GATE-IT-2004 | Question 66" }, { "code": null, "e": 29967, "s": 29925, "text": "GATE | GATE-CS-2016 (Set 2) | Question 48" }, { "code": null, "e": 30001, "s": 29967, "text": "GATE | GATE CS 2008 | Question 66" }, { "code": null, "e": 30043, "s": 30001, "text": "GATE | GATE-CS-2014-(Set-3) | Question 65" } ]
Python Strings decode() method - GeeksforGeeks
19 Nov, 2020 decode() is a method specified in Strings in Python 2.This method is used to convert from one encoding scheme, in which argument string is encoded to the desired encoding scheme. This works opposite to the encode. It accepts the encoding of the encoding string to decode it and returns the original string. Syntax : decode(encoding, error) Parameters :encoding : Specifies the encoding on the basis of which decoding has to be performed.error : Decides how to handle the errors if they occur, e.g ‘strict’ raises Unicode error in case of exception and ‘ignore’ ignores the errors occurred. Returns : Returns the original string from the encoded string. Code #1 : Code to decode the string # Python code to demonstrate # decode() # initializing string str = "geeksforgeeks" # encoding string str_enc = str.encode(encodeing='utf8') # printing the encoded string print ("The encoded string in base64 format is : ",) print (str_enc ) # printing the original decoded string print ("The decoded string is : ",) print (str_enc.decode('utf8', 'strict')) Output: The encoded string in base64 format is : Z2Vla3Nmb3JnZWVrcw== The decoded string is : geeksforgeeks Application :Encoding and decoding together can be used in the simple applications of storing passwords in the back end and many other applications like cryptography which deals with keeping the information confidential.A small demonstration of the password application is depicted below. Code #2 : Code to demonstrate application of encode-decode # Python code to demonstrate # application of encode-decode # input from user # user = input() # pass = input() user = "geeksforgeeks"passw = "i_lv_coding" # converting password to base64 encoding passw = passw.encode('base64', 'strict') # input from user # user_login = input() # pass_login = input() user_login = "geeksforgeeks" # wrongly entered password pass_wrong = "geeksforgeeks" print ("Password entered : " + pass_wrong ) if(pass_wrong == passw.decode('base64', 'strict')): print ("You are logged in !!")else : print ("Wrong Password !!") print( '\r') # correctly entered password pass_right = "i_lv_coding" print ("Password entered : " + pass_right ) if(pass_right == passw.decode('base64', 'strict')): print ("You are logged in !!")else : print ("Wrong Password !!") Output: Password entered : geeksforgeeks Wrong Password!! Password entered : i_lv_coding You are logged in!! Python-Built-in-functions Python-Functions python-string Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Enumerate() in Python How to Install PIP on Windows ? Different ways to create Pandas Dataframe Python String | replace() Reading and Writing to text files in Python sum() function in Python Create a Pandas DataFrame from Lists How to drop one or multiple columns in Pandas Dataframe *args and **kwargs in Python Graph Plotting in Python | Set 1
[ { "code": null, "e": 23853, "s": 23825, "text": "\n19 Nov, 2020" }, { "code": null, "e": 24160, "s": 23853, "text": "decode() is a method specified in Strings in Python 2.This method is used to convert from one encoding scheme, in which argument string is encoded to the desired encoding scheme. This works opposite to the encode. It accepts the encoding of the encoding string to decode it and returns the original string." }, { "code": null, "e": 24193, "s": 24160, "text": "Syntax : decode(encoding, error)" }, { "code": null, "e": 24443, "s": 24193, "text": "Parameters :encoding : Specifies the encoding on the basis of which decoding has to be performed.error : Decides how to handle the errors if they occur, e.g ‘strict’ raises Unicode error in case of exception and ‘ignore’ ignores the errors occurred." }, { "code": null, "e": 24506, "s": 24443, "text": "Returns : Returns the original string from the encoded string." }, { "code": null, "e": 24543, "s": 24506, "text": " Code #1 : Code to decode the string" }, { "code": "# Python code to demonstrate # decode() # initializing string str = \"geeksforgeeks\" # encoding string str_enc = str.encode(encodeing='utf8') # printing the encoded string print (\"The encoded string in base64 format is : \",) print (str_enc ) # printing the original decoded string print (\"The decoded string is : \",) print (str_enc.decode('utf8', 'strict'))", "e": 24917, "s": 24543, "text": null }, { "code": null, "e": 24925, "s": 24917, "text": "Output:" }, { "code": null, "e": 25029, "s": 24925, "text": "The encoded string in base64 format is : Z2Vla3Nmb3JnZWVrcw==\n\nThe decoded string is : geeksforgeeks\n" }, { "code": null, "e": 25318, "s": 25029, "text": "Application :Encoding and decoding together can be used in the simple applications of storing passwords in the back end and many other applications like cryptography which deals with keeping the information confidential.A small demonstration of the password application is depicted below." }, { "code": null, "e": 25378, "s": 25318, "text": " Code #2 : Code to demonstrate application of encode-decode" }, { "code": "# Python code to demonstrate # application of encode-decode # input from user # user = input() # pass = input() user = \"geeksforgeeks\"passw = \"i_lv_coding\" # converting password to base64 encoding passw = passw.encode('base64', 'strict') # input from user # user_login = input() # pass_login = input() user_login = \"geeksforgeeks\" # wrongly entered password pass_wrong = \"geeksforgeeks\" print (\"Password entered : \" + pass_wrong ) if(pass_wrong == passw.decode('base64', 'strict')): print (\"You are logged in !!\")else : print (\"Wrong Password !!\") print( '\\r') # correctly entered password pass_right = \"i_lv_coding\" print (\"Password entered : \" + pass_right ) if(pass_right == passw.decode('base64', 'strict')): print (\"You are logged in !!\")else : print (\"Wrong Password !!\")", "e": 26184, "s": 25378, "text": null }, { "code": null, "e": 26192, "s": 26184, "text": "Output:" }, { "code": null, "e": 26295, "s": 26192, "text": "Password entered : geeksforgeeks\nWrong Password!!\n\nPassword entered : i_lv_coding\nYou are logged in!!\n" }, { "code": null, "e": 26321, "s": 26295, "text": "Python-Built-in-functions" }, { "code": null, "e": 26338, "s": 26321, "text": "Python-Functions" }, { "code": null, "e": 26352, "s": 26338, "text": "python-string" }, { "code": null, "e": 26359, "s": 26352, "text": "Python" }, { "code": null, "e": 26457, "s": 26359, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26466, "s": 26457, "text": "Comments" }, { "code": null, "e": 26479, "s": 26466, "text": "Old Comments" }, { "code": null, "e": 26501, "s": 26479, "text": "Enumerate() in Python" }, { "code": null, "e": 26533, "s": 26501, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 26575, "s": 26533, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 26601, "s": 26575, "text": "Python String | replace()" }, { "code": null, "e": 26645, "s": 26601, "text": "Reading and Writing to text files in Python" }, { "code": null, "e": 26670, "s": 26645, "text": "sum() function in Python" }, { "code": null, "e": 26707, "s": 26670, "text": "Create a Pandas DataFrame from Lists" }, { "code": null, "e": 26763, "s": 26707, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 26792, "s": 26763, "text": "*args and **kwargs in Python" } ]
JavaScript | padEnd() Method - GeeksforGeeks
18 Nov, 2019 The padEnd() method in JavaScript is used to pad a string with another string until it reaches the given length. The padding is applied from the right end of the string. Syntax: string.padEnd( targetLength, padString ) Parameters: This method accepts two parameters as mentioned above and described below: targetLength: It is the length of the final string once the original string has been padded. If the value is less than the original string length, then the original string is returned. padString: It is the string that is to be padded with the original string. If this value is too long to be within the targetLength, it is truncated. Return Value: It returns the final string that is padded with the given string of the given length. Example 1: This example uses padEnd() method to pad strings into another string. <!DOCTYPE html><html> <head> <title> JavaScript | padEnd() method </title></head> <body> <h1 style="color: green"> GeeksforGeeks </h1> <b> JavaScript | padEnd() method </b> <p> Output for "Hello" with "$": <span class="output"></span> </p> <p> Output for "Geeks" with "Geeks": <span class="output2"></span> </p> <button onclick="padStrings()"> Pad Strings </button> <script type="text/javascript"> function padStrings() { exString = "Hello"; exString2 = "Geeks"; output = exString.padEnd(12, "$"); output2 = exString2.padEnd(12, "Geeks"); document.querySelector('.output').textContent = output; document.querySelector('.output2').textContent = output2; } </script></body> </html> Output: Before clicking the button: After clicking the button: Example 2: This example uses padEnd() method to pad numbers into the another number. <!DOCTYPE html><html> <head> <title> JavaScript | padEnd() method </title></head> <body> <h1 style="color: green"> GeeksforGeeks </h1> <b> JavaScript | padEnd() method </b> <p> Output for "1234" with "0": <span class="output"></span> </p> <p> Output for "99" with "**": <span class="output2"></span> </p> <button onclick="padNumbers()"> Pad Numbers </button> <script type="text/javascript"> function padNumbers() { exNumber = 1234; exNumber2 = 99; output = String(exNumber).padEnd(8, "0"); output2 = String(exNumber2).padEnd(8, "**"); document.querySelector('.output').textContent = output; document.querySelector('.output2').textContent = output2; } </script></body> </html> Output: Before clicking the button: After clicking the button: Supported Browsers: The browser supported by padEnd() method are listed below: Google Chrome 57 Firefox 48 Edge 15 Safari 10 Opera 44 javascript-functions 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 Difference Between PUT and PATCH Request How to get character array from string in JavaScript? Remove elements from a JavaScript Array How to get selected value in dropdown list using JavaScript ? Top 10 Front End Developer Skills That You Need in 2022 Installation of Node.js on Linux Top 10 Projects For Beginners To Practice HTML and CSS Skills How to fetch data from an API in ReactJS ? How to insert spaces/tabs in text using HTML/CSS?
[ { "code": null, "e": 24909, "s": 24881, "text": "\n18 Nov, 2019" }, { "code": null, "e": 25079, "s": 24909, "text": "The padEnd() method in JavaScript is used to pad a string with another string until it reaches the given length. The padding is applied from the right end of the string." }, { "code": null, "e": 25087, "s": 25079, "text": "Syntax:" }, { "code": null, "e": 25128, "s": 25087, "text": "string.padEnd( targetLength, padString )" }, { "code": null, "e": 25215, "s": 25128, "text": "Parameters: This method accepts two parameters as mentioned above and described below:" }, { "code": null, "e": 25400, "s": 25215, "text": "targetLength: It is the length of the final string once the original string has been padded. If the value is less than the original string length, then the original string is returned." }, { "code": null, "e": 25549, "s": 25400, "text": "padString: It is the string that is to be padded with the original string. If this value is too long to be within the targetLength, it is truncated." }, { "code": null, "e": 25649, "s": 25549, "text": "Return Value: It returns the final string that is padded with the given string of the given length." }, { "code": null, "e": 25730, "s": 25649, "text": "Example 1: This example uses padEnd() method to pad strings into another string." }, { "code": "<!DOCTYPE html><html> <head> <title> JavaScript | padEnd() method </title></head> <body> <h1 style=\"color: green\"> GeeksforGeeks </h1> <b> JavaScript | padEnd() method </b> <p> Output for \"Hello\" with \"$\": <span class=\"output\"></span> </p> <p> Output for \"Geeks\" with \"Geeks\": <span class=\"output2\"></span> </p> <button onclick=\"padStrings()\"> Pad Strings </button> <script type=\"text/javascript\"> function padStrings() { exString = \"Hello\"; exString2 = \"Geeks\"; output = exString.padEnd(12, \"$\"); output2 = exString2.padEnd(12, \"Geeks\"); document.querySelector('.output').textContent = output; document.querySelector('.output2').textContent = output2; } </script></body> </html>", "e": 26737, "s": 25730, "text": null }, { "code": null, "e": 26745, "s": 26737, "text": "Output:" }, { "code": null, "e": 26773, "s": 26745, "text": "Before clicking the button:" }, { "code": null, "e": 26800, "s": 26773, "text": "After clicking the button:" }, { "code": null, "e": 26885, "s": 26800, "text": "Example 2: This example uses padEnd() method to pad numbers into the another number." }, { "code": "<!DOCTYPE html><html> <head> <title> JavaScript | padEnd() method </title></head> <body> <h1 style=\"color: green\"> GeeksforGeeks </h1> <b> JavaScript | padEnd() method </b> <p> Output for \"1234\" with \"0\": <span class=\"output\"></span> </p> <p> Output for \"99\" with \"**\": <span class=\"output2\"></span> </p> <button onclick=\"padNumbers()\"> Pad Numbers </button> <script type=\"text/javascript\"> function padNumbers() { exNumber = 1234; exNumber2 = 99; output = String(exNumber).padEnd(8, \"0\"); output2 = String(exNumber2).padEnd(8, \"**\"); document.querySelector('.output').textContent = output; document.querySelector('.output2').textContent = output2; } </script></body> </html>", "e": 27914, "s": 26885, "text": null }, { "code": null, "e": 27922, "s": 27914, "text": "Output:" }, { "code": null, "e": 27950, "s": 27922, "text": "Before clicking the button:" }, { "code": null, "e": 27977, "s": 27950, "text": "After clicking the button:" }, { "code": null, "e": 28056, "s": 27977, "text": "Supported Browsers: The browser supported by padEnd() method are listed below:" }, { "code": null, "e": 28073, "s": 28056, "text": "Google Chrome 57" }, { "code": null, "e": 28084, "s": 28073, "text": "Firefox 48" }, { "code": null, "e": 28092, "s": 28084, "text": "Edge 15" }, { "code": null, "e": 28102, "s": 28092, "text": "Safari 10" }, { "code": null, "e": 28111, "s": 28102, "text": "Opera 44" }, { "code": null, "e": 28132, "s": 28111, "text": "javascript-functions" }, { "code": null, "e": 28143, "s": 28132, "text": "JavaScript" }, { "code": null, "e": 28160, "s": 28143, "text": "Web Technologies" }, { "code": null, "e": 28258, "s": 28160, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28267, "s": 28258, "text": "Comments" }, { "code": null, "e": 28280, "s": 28267, "text": "Old Comments" }, { "code": null, "e": 28341, "s": 28280, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 28382, "s": 28341, "text": "Difference Between PUT and PATCH Request" }, { "code": null, "e": 28436, "s": 28382, "text": "How to get character array from string in JavaScript?" }, { "code": null, "e": 28476, "s": 28436, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 28538, "s": 28476, "text": "How to get selected value in dropdown list using JavaScript ?" }, { "code": null, "e": 28594, "s": 28538, "text": "Top 10 Front End Developer Skills That You Need in 2022" }, { "code": null, "e": 28627, "s": 28594, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 28689, "s": 28627, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 28732, "s": 28689, "text": "How to fetch data from an API in ReactJS ?" } ]
How to create a Popup Menu in Tkinter?
We need menubars in applications where user interaction is required. Menus can be created by initializing the Menu(parent) object along with the menu items. A popup Menu can be created by initializing tk_popup(x_root,y_root, False) which ensures that the menu is visible on the screen. Now, we will add an event which can be triggered through the Mouse Button (Right Click). The grab_release() method sets the mouse button release to unset the popup menu. #Import the required libraries from tkinter import * from tkinter import ttk #Create an instance of Tkinter frame win = Tk() #Set the geometry of the Tkinter library win.geometry("700x350") label = Label(win, text="Right-click anywhere to display a menu", font= ('Helvetica 18')) label.pack(pady= 40) #Add Menu popup = Menu(win, tearoff=0) #Adding Menu Items popup.add_command(label="New") popup.add_command(label="Edit") popup.add_separator() popup.add_command(label="Save") def menu_popup(event): # display the popup menu try: popup.tk_popup(event.x_root, event.y_root, 0) finally: #Release the grab popup.grab_release() win.bind("<Button-3>", menu_popup) button = ttk.Button(win, text="Quit", command=win.destroy) button.pack() mainloop() Running the above code will display a window with a Label and a button. When we right click with the Mouse, a popup menu will appear in the window.
[ { "code": null, "e": 1518, "s": 1062, "text": "We need menubars in applications where user interaction is required. Menus can be created by initializing the Menu(parent) object along with the menu items. A popup Menu can be created by initializing tk_popup(x_root,y_root, False) which ensures that the menu is visible on the screen. Now, we will add an event which can be triggered through the Mouse Button (Right Click). The grab_release() method sets the mouse button release to unset the popup menu." }, { "code": null, "e": 2296, "s": 1518, "text": "#Import the required libraries\nfrom tkinter import *\nfrom tkinter import ttk\n\n#Create an instance of Tkinter frame\nwin = Tk()\n\n#Set the geometry of the Tkinter library\nwin.geometry(\"700x350\")\n\nlabel = Label(win, text=\"Right-click anywhere to display a menu\", font= ('Helvetica 18'))\nlabel.pack(pady= 40)\n\n#Add Menu\npopup = Menu(win, tearoff=0)\n\n#Adding Menu Items\npopup.add_command(label=\"New\")\npopup.add_command(label=\"Edit\")\npopup.add_separator()\npopup.add_command(label=\"Save\")\n\ndef menu_popup(event):\n # display the popup menu\n try:\n popup.tk_popup(event.x_root, event.y_root, 0)\n finally:\n #Release the grab\n popup.grab_release()\n\nwin.bind(\"<Button-3>\", menu_popup)\n\nbutton = ttk.Button(win, text=\"Quit\", command=win.destroy)\nbutton.pack()\n\nmainloop()" }, { "code": null, "e": 2444, "s": 2296, "text": "Running the above code will display a window with a Label and a button. When we right click with the Mouse, a popup menu will appear in the window." } ]
Maximum Index | Practice | GeeksforGeeks
Given an array A[] of N positive integers. The task is to find the maximum of j - i subjected to the constraint of A[i] < A[j] and i < j. Example 1: Input: N = 2 A[] = {1, 10} Output: 1 Explanation: A[0]<A[1] so (j-i) is 1-0 = 1. Example 2: Input: N = 9 A[] = {34, 8, 10, 3, 2, 80, 30, 33, 1} Output: 6 Explanation: In the given array A[1] < A[7] satisfying the required condition(A[i] < A[j]) thus giving the maximum difference of j - i which is 6(7-1). Your Task: The task is to complete the function maxIndexDiff() which finds and returns maximum index difference. Printing the output will be handled by driver code. Return -1 in case no such index is found. Expected Time Complexity: O(N) Expected Auxiliary Space: O(N) Constraints: 1 ≤ N ≤ 107 0 ≤ A[i] ≤ 109 0 visveswar190126110 hours ago int maxIndexDiff(int A[], int n) { // Your code here int max_difference=0; int diff=0; for(int i=0;i<n;i++ ) { for(int j=n-1;j>=i;j--) { if(A[i]<=A[j]) { diff=j-i; max_difference=max(max_difference,diff); break; } } } return max_difference; } 0 aniket6518gadhe6 days ago JAVA SOLUTION Total Time Taken: 0.56/1.98 static int maxIndexDiff(int A[], int N) { int index = 0; int max_diff = 0; for(int i = 0; i < N; i++){ int j = N-1; while(j>i){ if(A[i]<=A[j]){ int diff = j - i; max_diff = Math.max(diff, max_diff); break; } j--; } } return max_diff; } 0 atharvsharma08086 days ago int max=0; for(int i=0;i<N;i++) { int count=0; for(int j=N-1;j>=0;j--) { if(A[i]<=A[j]) { count=j-i; break; } } if(count>max) { max=count; } } return max; +2 lawbindpandey01w1 week ago Time complexity : O(N) and Aux space : O(N) int maxIndexDiff(int A[], int N) { // Your code here vector<int> minA(N); vector<int> maxA(N); int curr_min = A[0]; int curr_max = A[N - 1]; minA[0] = 0; maxA[N - 1] = N - 1; for(int i = 1 ; i < N; i++){ if(A[i] < curr_min){ minA[i] = i; curr_min = A[i]; } else minA[i] = minA[i - 1]; } //for(auto x : minA) cout << x << " "; cout << "\n"; for(int i = N - 2; i >= 0; i--){ if(A[i] > curr_max){ maxA[i] = i; curr_max = A[i]; } else maxA[i] = maxA[i + 1]; } //for(auto x : maxA) cout << x << " "; cout << "\n"; int max_diff = 0; int j = 0; for(int i = 0; i < N && j < N; i++){ while(j < N && A[minA[i]] <= A[maxA[j]] && i <= j){ max_diff = max(max_diff, j - i); j++; } } return max_diff; } 0 amrit_kumar2 weeks ago int maxIndexDiff(int A[], int N) { int maxDiff = INT_MIN; int right[N]; int left[N]; for(int i=N-1;i>=0;i--) { if(i==N-1) right[i] = A[i]; else right[i] = max(right[i+1],A[i]); } int i=0,j=0; while(i<N&&j<N) { while(j<N &&A[i]<=right[j]) j++; maxDiff = max(maxDiff, j-i-1); i++; } return maxDiff; } +1 ravikant021112 weeks ago // simplest java solution int index = 0; int max_diff = -1; for(int i = 0; i < N; i++){ int j = index + 1; while(j<N){ if(arr[i] <= arr[j]){ int diff = j - i; max_diff = Math.max(diff, max_diff); index = j; } j++; } } return max_diff; +1 visveswar19012612 weeks ago int maxIndexDiff(int A[], int n) { // Your code here int max_diff=0; int i=0; while(i<n) { for(int j=0;j<n;j++) { if(A[i]<=A[j]) { max_diff=max(max_diff,j-i); } } i++; } return max_diff; }}; -2 parmarabhishek0622 weeks ago C++ EASY SOLUTION(0.27 SEC) int maxIndexDiff(int A[], int n) { int diff = 0; int max = 0; for(int i = 0;i<n;i++){ for(int j = n-1;j>i;j--){ if(A[i]<=A[j]){ diff = j-i; break; } } if(diff>max){ max = diff; } } return max; if(max==0){ return {-1}; } } +2 arpita biswal3 weeks ago class Solution { // Function to find the maximum index difference. maxIndexDiff(A, N) { //your code here let i=0,j=N-1,maxdiff=0; while(i<=j){ if(A[i]<=A[j]){ maxdiff=Math.max(maxdiff,j-i); j=N-1; i++; } else{ j--; } } return maxdiff; }} 0 charansaisadla3 weeks ago WHAT is WRONG def maxIndexDiff(self,A, N): ##Your code here dic={} for i in range(N): dic[A[i]]=i A.sort() max1=0 for i in range(N-1): diff=dic[A[i+1]]-dic[A[i]] max1=max(max1,diff) return max1 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": 378, "s": 238, "text": "Given an array A[] of N positive integers. The task is to find the maximum of j - i subjected to the constraint of A[i] < A[j] and i < j.\n " }, { "code": null, "e": 389, "s": 378, "text": "Example 1:" }, { "code": null, "e": 470, "s": 389, "text": "Input:\nN = 2\nA[] = {1, 10}\nOutput:\n1\nExplanation:\nA[0]<A[1] so (j-i) is 1-0 = 1." }, { "code": null, "e": 481, "s": 470, "text": "Example 2:" }, { "code": null, "e": 699, "s": 481, "text": "Input:\nN = 9\nA[] = {34, 8, 10, 3, 2, 80, 30, 33, 1}\nOutput:\n6\nExplanation:\nIn the given array A[1] < A[7]\nsatisfying the required \ncondition(A[i] < A[j]) thus giving \nthe maximum difference of j - i \nwhich is 6(7-1).\n" }, { "code": null, "e": 908, "s": 701, "text": "Your Task:\nThe task is to complete the function maxIndexDiff() which finds and returns maximum index difference. Printing the output will be handled by driver code. Return -1 in case no such index is found." }, { "code": null, "e": 970, "s": 908, "text": "Expected Time Complexity: O(N)\nExpected Auxiliary Space: O(N)" }, { "code": null, "e": 1010, "s": 970, "text": "Constraints:\n1 ≤ N ≤ 107\n0 ≤ A[i] ≤ 109" }, { "code": null, "e": 1014, "s": 1012, "text": "0" }, { "code": null, "e": 1043, "s": 1014, "text": "visveswar190126110 hours ago" }, { "code": null, "e": 1447, "s": 1043, "text": "int maxIndexDiff(int A[], int n) { // Your code here int max_difference=0; int diff=0; for(int i=0;i<n;i++ ) { for(int j=n-1;j>=i;j--) { if(A[i]<=A[j]) { diff=j-i; max_difference=max(max_difference,diff); break; } } } return max_difference; }" }, { "code": null, "e": 1449, "s": 1447, "text": "0" }, { "code": null, "e": 1475, "s": 1449, "text": "aniket6518gadhe6 days ago" }, { "code": null, "e": 1489, "s": 1475, "text": "JAVA SOLUTION" }, { "code": null, "e": 1507, "s": 1489, "text": "Total Time Taken:" }, { "code": null, "e": 1517, "s": 1507, "text": "0.56/1.98" }, { "code": null, "e": 1915, "s": 1519, "text": " static int maxIndexDiff(int A[], int N) { int index = 0; int max_diff = 0; for(int i = 0; i < N; i++){ int j = N-1; while(j>i){ if(A[i]<=A[j]){ int diff = j - i; max_diff = Math.max(diff, max_diff); break; } j--; } } return max_diff; }" }, { "code": null, "e": 1917, "s": 1915, "text": "0" }, { "code": null, "e": 1944, "s": 1917, "text": "atharvsharma08086 days ago" }, { "code": null, "e": 2286, "s": 1944, "text": " int max=0; for(int i=0;i<N;i++) { int count=0; for(int j=N-1;j>=0;j--) { if(A[i]<=A[j]) { count=j-i; break; } } if(count>max) { max=count; } } return max;" }, { "code": null, "e": 2289, "s": 2286, "text": "+2" }, { "code": null, "e": 2316, "s": 2289, "text": "lawbindpandey01w1 week ago" }, { "code": null, "e": 2360, "s": 2316, "text": "Time complexity : O(N) and Aux space : O(N)" }, { "code": null, "e": 2842, "s": 2364, "text": "int maxIndexDiff(int A[], int N) { // Your code here vector<int> minA(N); vector<int> maxA(N); int curr_min = A[0]; int curr_max = A[N - 1]; minA[0] = 0; maxA[N - 1] = N - 1; for(int i = 1 ; i < N; i++){ if(A[i] < curr_min){ minA[i] = i; curr_min = A[i]; } else minA[i] = minA[i - 1]; }" }, { "code": null, "e": 3553, "s": 2842, "text": " //for(auto x : minA) cout << x << \" \"; cout << \"\\n\"; for(int i = N - 2; i >= 0; i--){ if(A[i] > curr_max){ maxA[i] = i; curr_max = A[i]; } else maxA[i] = maxA[i + 1]; } //for(auto x : maxA) cout << x << \" \"; cout << \"\\n\"; int max_diff = 0; int j = 0; for(int i = 0; i < N && j < N; i++){ while(j < N && A[minA[i]] <= A[maxA[j]] && i <= j){ max_diff = max(max_diff, j - i); j++; } } return max_diff; }" }, { "code": null, "e": 3561, "s": 3559, "text": "0" }, { "code": null, "e": 3584, "s": 3561, "text": "amrit_kumar2 weeks ago" }, { "code": null, "e": 4086, "s": 3584, "text": "int maxIndexDiff(int A[], int N) \n { \n int maxDiff = INT_MIN;\n int right[N];\n int left[N];\n for(int i=N-1;i>=0;i--)\n {\n if(i==N-1) right[i] = A[i];\n else right[i] = max(right[i+1],A[i]);\n \n }\n int i=0,j=0;\n while(i<N&&j<N)\n {\n while(j<N &&A[i]<=right[j]) j++;\n maxDiff = max(maxDiff, j-i-1);\n i++; \n \n }\n return maxDiff;\n \n \n }" }, { "code": null, "e": 4089, "s": 4086, "text": "+1" }, { "code": null, "e": 4114, "s": 4089, "text": "ravikant021112 weeks ago" }, { "code": null, "e": 4514, "s": 4114, "text": " // simplest java solution int index = 0; int max_diff = -1; for(int i = 0; i < N; i++){ int j = index + 1; while(j<N){ if(arr[i] <= arr[j]){ int diff = j - i; max_diff = Math.max(diff, max_diff); index = j; } j++; } } return max_diff;" }, { "code": null, "e": 4517, "s": 4514, "text": "+1" }, { "code": null, "e": 4545, "s": 4517, "text": "visveswar19012612 weeks ago" }, { "code": null, "e": 4876, "s": 4545, "text": " int maxIndexDiff(int A[], int n) { // Your code here int max_diff=0; int i=0; while(i<n) { for(int j=0;j<n;j++) { if(A[i]<=A[j]) { max_diff=max(max_diff,j-i); } } i++; } return max_diff; }};" }, { "code": null, "e": 4879, "s": 4876, "text": "-2" }, { "code": null, "e": 4908, "s": 4879, "text": "parmarabhishek0622 weeks ago" }, { "code": null, "e": 4936, "s": 4908, "text": "C++ EASY SOLUTION(0.27 SEC)" }, { "code": null, "e": 5342, "s": 4936, "text": "int maxIndexDiff(int A[], int n) { int diff = 0; int max = 0; for(int i = 0;i<n;i++){ for(int j = n-1;j>i;j--){ if(A[i]<=A[j]){ diff = j-i; break; } } if(diff>max){ max = diff; } } return max; if(max==0){ return {-1}; } }" }, { "code": null, "e": 5347, "s": 5344, "text": "+2" }, { "code": null, "e": 5372, "s": 5347, "text": "arpita biswal3 weeks ago" }, { "code": null, "e": 5744, "s": 5372, "text": "class Solution { // Function to find the maximum index difference. maxIndexDiff(A, N) { //your code here let i=0,j=N-1,maxdiff=0; while(i<=j){ if(A[i]<=A[j]){ maxdiff=Math.max(maxdiff,j-i); j=N-1; i++; } else{ j--; } } return maxdiff; }}" }, { "code": null, "e": 5746, "s": 5744, "text": "0" }, { "code": null, "e": 5772, "s": 5746, "text": "charansaisadla3 weeks ago" }, { "code": null, "e": 5786, "s": 5772, "text": "WHAT is WRONG" }, { "code": null, "e": 5954, "s": 5786, "text": "def maxIndexDiff(self,A, N): ##Your code here dic={} for i in range(N): dic[A[i]]=i A.sort() max1=0 for i in range(N-1):" }, { "code": null, "e": 6048, "s": 5954, "text": " diff=dic[A[i+1]]-dic[A[i]] max1=max(max1,diff) return max1" }, { "code": null, "e": 6194, "s": 6048, "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": 6230, "s": 6194, "text": " Login to access your submissions. " }, { "code": null, "e": 6240, "s": 6230, "text": "\nProblem\n" }, { "code": null, "e": 6250, "s": 6240, "text": "\nContest\n" }, { "code": null, "e": 6313, "s": 6250, "text": "Reset the IDE using the second button on the top right corner." }, { "code": null, "e": 6461, "s": 6313, "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": 6669, "s": 6461, "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": 6775, "s": 6669, "text": "You can access the hints to get an idea about what is expected of you as well as the final solution code." } ]
What is arguments object in JavaScript?
Arguments object in JavaScript is an object, which represents the arguments to the function executing. Its syntax has two arguments: [function.]arguments[p] You can try to run the following code to learn what are arguments object in JavaScript Live Demo <html> <body> <script> function functionArgument(val1, val2, val3) { var res = ""; res += "Expected Arguments: " + functionArgument.length; res += "<br />"; res += "Current Arguments : " + arguments.length; res += "<br />"; res += "Each argument = " for (p = 0; p < arguments.length; p++) { res += "<br />"; res += functionArgument.arguments[p]; res += " "; } document.write(res); } functionArgument(20, 50, 80, "Demo Text!","Hello World", new Date()) </script> </body> </html>
[ { "code": null, "e": 1195, "s": 1062, "text": "Arguments object in JavaScript is an object, which represents the arguments to the function executing. Its syntax has two arguments:" }, { "code": null, "e": 1219, "s": 1195, "text": "[function.]arguments[p]" }, { "code": null, "e": 1306, "s": 1219, "text": "You can try to run the following code to learn what are arguments object in JavaScript" }, { "code": null, "e": 1316, "s": 1306, "text": "Live Demo" }, { "code": null, "e": 1994, "s": 1316, "text": "<html>\n <body>\n <script>\n function functionArgument(val1, val2, val3) {\n var res = \"\";\n res += \"Expected Arguments: \" + functionArgument.length;\n res += \"<br />\";\n res += \"Current Arguments : \" + arguments.length;\n\n res += \"<br />\";\n res += \"Each argument = \"\n\n for (p = 0; p < arguments.length; p++) {\n res += \"<br />\";\n res += functionArgument.arguments[p];\n res += \" \";\n }\n document.write(res);\n }\n functionArgument(20, 50, 80, \"Demo Text!\",\"Hello World\", new Date())\n </script>\n </body>\n</html>" } ]
Python’s «predict_proba» Doesn’t Actually Predict Probabilities (and How to Fix It) | by Samuele Mazzanti | Towards Data Science
Data scientists typically evaluate their predictive models in terms of accuracy or precision, but hardly ever ask themselves: “Is my model capable of predicting real probabilities?” However, an accurate estimate of probability is extremely valuable from a business point of view (sometimes even more valuable than a good precision). Want an example? Imagine your company is selling 2 mugs, one is a plain white mug, and the other one has a kitten picture on it. You must decide which mug to show to a given customer. In order to do that, you need to predict the probability that a given user will buy each of them. So you train a couple of different models and you get these results: Now, which mug would you suggest to this user? Both models agree that the user is more likely to buy the plain mug (so, model A and model B have the same area under ROC, since this metric only evaluates the sorting). But, according to model A, you will maximize the expected profit by recommending the plain mug. Whereas, according to model B the expected profit is maximized by the kitten mug. In applications like this one, it’s vital to figure out which model is able to estimate better probabilities. In this article, we will see how to measure probability calibration (both visually and numerically) and how to “correct” an existing model in order to get better probabilities. All the most popular machine learning libraries in Python have a method called «predict_proba»: Scikit-learn (e.g. LogisticRegression, SVC, RandomForest, ...), XGBoost, LightGBM, CatBoost, Keras... But, despite its name, «predict_proba» does not quite predict probabilities. In fact, different studies (especially this one and this one) have shown that the most popular predictive models are not calibrated. The fact that a number is between zero and one is not enough for calling it a probability! But then, when can we say that a number actually represents a probability? Imagine that you have trained a predictive model to predict whether a patient will develop a cancer. Now say that, for a given patient, the model predicts 5% probability. In principle, we should observe the very same patient in multiple parallel universes and see if actually it develops a cancer 5% of the times. Since we cannot walk that road, the best proxy is to take all the patients that are in the vicinity of 5% probability and count how many of them have developed cancer. If the observed percentage is actually close to 5%, we say that the probabilities provided by the model are “calibrated”. When predicted probabilities reflect the real underlying probabilities, they are said “calibrated”. But how to check if your model is calibrated? The easiest way to assess the calibration of your model is through a plot called “calibration curve” (a.k.a. “reliability diagram”). The idea is to divide the observations into bins of probability. Thus, observations that belong to the same bin share a similar probability. At this point, for each bin, the calibration curve compares the predicted mean (i.e. mean of the predicted probability) with the theoretical mean (i.e. mean of the observed target variable). Scikit-learn does all this work for you, through the function “calibration_curve”: from sklearn.calibration import calibration_curvey_means, proba_means = calibration_curve(y, proba, n_bins, strategy) You only need to choose the number of bins and (optionally) a binning strategy between: “uniform”, interval 0–1 is divided in n_bins of equal width; “quantile”, bin edges are defined such that each bin has the same number of observations. For plotting purposes, I personally prefer the “quantile” approach. In fact, “uniform” binning may be misleading because some bins could contain very few observations. The Numpy function returns two arrays containing, for each bin, the mean probability and the mean of the target variable. Therefore, all we need to do is to plot them: import matplotlib.pyplot as pltplt.plot([0, 1], [0, 1], linestyle = '--', label = 'Perfect calibration')plt.plot(proba_means, y_means) Supposing that your model has a good precision, the calibration curve will be monotonically increasing. But this doesn’t mean that the model is well calibrated. Indeed, your model is well calibrated only if the calibration curve is very close to the bisector (i.e. the dashed grey line), since this would mean that the predicted probability is on average close to the theoretical probability. Let’s see some examples of common types of calibration curves that indicate a miscalibration of your model: The most common types of miscalibration are: Systematic overestimation. Compared to the true distribution, the distribution of predicted probabilities is pushed towards the right. This is common when you train a model on an unbalanced dataset with very few positives. Systematic underestimation. Compared to the true distribution, the distribution of predicted probabilities is pushed leftward. Center of the distribution is too heavy. This happens when “algorithms such as support vector machines and boosted trees tend to push predicted probabilities away from 0 and 1” (quote from «Predicting good probabilities with supervised learning»). Tails of the distribution are too heavy. For instance, “Other methods such as naive bayes have the opposite bias and tend to push predictions closer to 0 and 1” (quote from «Predicting good probabilities with supervised learning»). Suppose you have trained a classifier that yields accurate but uncalibrated probabilities. The idea of probability calibration is to build a second model (called calibrator) that is able to “correct” them into real probabilities. Note that calibration should not be carried out on the same data that has been used for training the first classifier. Therefore, calibration consists in a function that transforms a 1-dimensional vector (of uncalibrated probabilities) into another 1-dimensional vector (of calibrated probabilities). Two methods are mostly used as calibrators: Isotonic regression. A non-parametric algorithm that fits a non-decreasing free form line to the data. The fact that the line is non-decreasing is fundamental because it respects the original sorting. Logistic regression. Let’s see how to use calibrators in practice in Python, with the help of a toy dataset: from sklearn.datasets import make_classificationX, y = make_classification( n_samples = 15000, n_features = 50, n_informative = 30, n_redundant = 20, weights = [.9, .1], random_state = 0)X_train, X_valid, X_test = X[:5000], X[5000:10000], X[10000:]y_train, y_valid, y_test = y[:5000], y[5000:10000], y[10000:] First of all, we will need to fit a classifier. Let’s use random forest (but any model that has a «predict_proba» method would be ok). from sklearn.ensemble import RandomForestClassifierforest = RandomForestClassifier().fit(X_train, y_train)proba_valid = forest.predict_proba(X_valid)[:, 1] Then, we will use the output of the classifier (on validation data) to fit the calibrator and finally predicting probabilities on test data. Isotonic regression: from sklearn.isotonic import IsotonicRegressioniso_reg = IsotonicRegression(y_min = 0, y_max = 1, out_of_bounds = 'clip').fit(proba_valid, y_valid)proba_test_forest_isoreg = iso_reg.predict(forest.predict_proba(X_test)[:, 1]) Logistic regression: from sklearn.linear_model import LogisticRegressionlog_reg = LogisticRegression().fit(proba_valid.reshape(-1, 1), y_valid)proba_test_forest_logreg = log_reg.predict_proba(forest.predict_proba(X_test)[:, 1].reshape(-1, 1))[:, 1] At this point we have three options for predicting probabilities: plain random forest,random forest + isotonic regression,random forest + logistic regression. plain random forest, random forest + isotonic regression, random forest + logistic regression. But how do we assess which one is the most calibrated? Everybody likes plots. But besides the calibration plot, we need a quantitative way to measure (mis)calibration. The most commonly used metric is called Expected Calibration Error. It answers the question: How far away is our predicted probability from the true probability, on average? Let’s take one classifier for instance: It’s easy to define the calibration error of a single bin: it’s the absolute difference between the mean of predicted probabilities and the fraction of positives within the same bin. If you think about it, it’s pretty intuitive. Take one bin, and suppose the mean of its predicted probabilities is 25%. Thus, we expect that the fraction of positives in that bin is approximately equal to 25%. The farther this value is from 25%, the worse the calibration of that bin. Thus, Expected Calibration Error (ECE) is a weighted mean of the calibration errors of the single bins, where each bin weighs proportionally to the number of observations that it contains: where b identifies a bin and B is the number of bins. Note that the denominator is simply the total number of samples. But this formula leaves us the problem of defining the number of bins. In order to find a metric that is as neutral as possible, I propose to set the number of bins according to the Freedman-Diaconis rule (which is a statistical rule designed for finding the number of bins that makes the histogram as close as possible to the theoretical probability distribution). Using Freedman-Diaconis rule in Python is extremely simple because it’s already implemented in numpy’s histogram function (it’s enough to pass the string “fd” to the parameter “bins”). Here is a Python implementation of the expected calibration error, which employs the Freedman-Diaconis rule as default: def expected_calibration_error(y, proba, bins = 'fd'): import numpy as np bin_count, bin_edges = np.histogram(proba, bins = bins) n_bins = len(bin_count) bin_edges[0] -= 1e-8 # because left edge is not included bin_id = np.digitize(proba, bin_edges, right = True) - 1 bin_ysum = np.bincount(bin_id, weights = y, minlength = n_bins) bin_probasum = np.bincount(bin_id, weights = proba, minlength = n_bins) bin_ymean = np.divide(bin_ysum, bin_count, out = np.zeros(n_bins), where = bin_count > 0) bin_probamean = np.divide(bin_probasum, bin_count, out = np.zeros(n_bins), where = bin_count > 0) ece = np.abs((bin_probamean - bin_ymean) * bin_count).sum() / len(proba) return ece Now that we have a metric for calibration, let’s compare the calibration of the three models that we have obtained above (on test set): In this case, isotonic regression provided the best outcome in terms of calibration, being far only 1.2% from the true probability, on average. It’s a huge improvement, if you consider that the ECE of the plain random forest was 7%. Here are some interesting papers (on which this article is based) that I recommend if you want to deepen the topic of probability calibration: «Predicting good probabilities with supervised learning» (2005) by Caruana and Niculescu-Mizil. «On Calibration of Modern Neural Networks» (2017) by Guo et al. «Obtaining Well Calibrated Probabilities Using Bayesian Binning» (2015) by Naeini et al. Thank you for reading! I hope you found this post useful. I appreciate feedback and constructive criticism. If you want to talk about this article or other related topics, you can text me at my Linkedin contact.
[ { "code": null, "e": 297, "s": 171, "text": "Data scientists typically evaluate their predictive models in terms of accuracy or precision, but hardly ever ask themselves:" }, { "code": null, "e": 353, "s": 297, "text": "“Is my model capable of predicting real probabilities?”" }, { "code": null, "e": 521, "s": 353, "text": "However, an accurate estimate of probability is extremely valuable from a business point of view (sometimes even more valuable than a good precision). Want an example?" }, { "code": null, "e": 855, "s": 521, "text": "Imagine your company is selling 2 mugs, one is a plain white mug, and the other one has a kitten picture on it. You must decide which mug to show to a given customer. In order to do that, you need to predict the probability that a given user will buy each of them. So you train a couple of different models and you get these results:" }, { "code": null, "e": 902, "s": 855, "text": "Now, which mug would you suggest to this user?" }, { "code": null, "e": 1072, "s": 902, "text": "Both models agree that the user is more likely to buy the plain mug (so, model A and model B have the same area under ROC, since this metric only evaluates the sorting)." }, { "code": null, "e": 1250, "s": 1072, "text": "But, according to model A, you will maximize the expected profit by recommending the plain mug. Whereas, according to model B the expected profit is maximized by the kitten mug." }, { "code": null, "e": 1360, "s": 1250, "text": "In applications like this one, it’s vital to figure out which model is able to estimate better probabilities." }, { "code": null, "e": 1537, "s": 1360, "text": "In this article, we will see how to measure probability calibration (both visually and numerically) and how to “correct” an existing model in order to get better probabilities." }, { "code": null, "e": 1735, "s": 1537, "text": "All the most popular machine learning libraries in Python have a method called «predict_proba»: Scikit-learn (e.g. LogisticRegression, SVC, RandomForest, ...), XGBoost, LightGBM, CatBoost, Keras..." }, { "code": null, "e": 1945, "s": 1735, "text": "But, despite its name, «predict_proba» does not quite predict probabilities. In fact, different studies (especially this one and this one) have shown that the most popular predictive models are not calibrated." }, { "code": null, "e": 2036, "s": 1945, "text": "The fact that a number is between zero and one is not enough for calling it a probability!" }, { "code": null, "e": 2111, "s": 2036, "text": "But then, when can we say that a number actually represents a probability?" }, { "code": null, "e": 2425, "s": 2111, "text": "Imagine that you have trained a predictive model to predict whether a patient will develop a cancer. Now say that, for a given patient, the model predicts 5% probability. In principle, we should observe the very same patient in multiple parallel universes and see if actually it develops a cancer 5% of the times." }, { "code": null, "e": 2715, "s": 2425, "text": "Since we cannot walk that road, the best proxy is to take all the patients that are in the vicinity of 5% probability and count how many of them have developed cancer. If the observed percentage is actually close to 5%, we say that the probabilities provided by the model are “calibrated”." }, { "code": null, "e": 2815, "s": 2715, "text": "When predicted probabilities reflect the real underlying probabilities, they are said “calibrated”." }, { "code": null, "e": 2861, "s": 2815, "text": "But how to check if your model is calibrated?" }, { "code": null, "e": 2994, "s": 2861, "text": "The easiest way to assess the calibration of your model is through a plot called “calibration curve” (a.k.a. “reliability diagram”)." }, { "code": null, "e": 3326, "s": 2994, "text": "The idea is to divide the observations into bins of probability. Thus, observations that belong to the same bin share a similar probability. At this point, for each bin, the calibration curve compares the predicted mean (i.e. mean of the predicted probability) with the theoretical mean (i.e. mean of the observed target variable)." }, { "code": null, "e": 3409, "s": 3326, "text": "Scikit-learn does all this work for you, through the function “calibration_curve”:" }, { "code": null, "e": 3527, "s": 3409, "text": "from sklearn.calibration import calibration_curvey_means, proba_means = calibration_curve(y, proba, n_bins, strategy)" }, { "code": null, "e": 3615, "s": 3527, "text": "You only need to choose the number of bins and (optionally) a binning strategy between:" }, { "code": null, "e": 3676, "s": 3615, "text": "“uniform”, interval 0–1 is divided in n_bins of equal width;" }, { "code": null, "e": 3766, "s": 3676, "text": "“quantile”, bin edges are defined such that each bin has the same number of observations." }, { "code": null, "e": 3934, "s": 3766, "text": "For plotting purposes, I personally prefer the “quantile” approach. In fact, “uniform” binning may be misleading because some bins could contain very few observations." }, { "code": null, "e": 4102, "s": 3934, "text": "The Numpy function returns two arrays containing, for each bin, the mean probability and the mean of the target variable. Therefore, all we need to do is to plot them:" }, { "code": null, "e": 4237, "s": 4102, "text": "import matplotlib.pyplot as pltplt.plot([0, 1], [0, 1], linestyle = '--', label = 'Perfect calibration')plt.plot(proba_means, y_means)" }, { "code": null, "e": 4630, "s": 4237, "text": "Supposing that your model has a good precision, the calibration curve will be monotonically increasing. But this doesn’t mean that the model is well calibrated. Indeed, your model is well calibrated only if the calibration curve is very close to the bisector (i.e. the dashed grey line), since this would mean that the predicted probability is on average close to the theoretical probability." }, { "code": null, "e": 4738, "s": 4630, "text": "Let’s see some examples of common types of calibration curves that indicate a miscalibration of your model:" }, { "code": null, "e": 4783, "s": 4738, "text": "The most common types of miscalibration are:" }, { "code": null, "e": 5006, "s": 4783, "text": "Systematic overestimation. Compared to the true distribution, the distribution of predicted probabilities is pushed towards the right. This is common when you train a model on an unbalanced dataset with very few positives." }, { "code": null, "e": 5133, "s": 5006, "text": "Systematic underestimation. Compared to the true distribution, the distribution of predicted probabilities is pushed leftward." }, { "code": null, "e": 5381, "s": 5133, "text": "Center of the distribution is too heavy. This happens when “algorithms such as support vector machines and boosted trees tend to push predicted probabilities away from 0 and 1” (quote from «Predicting good probabilities with supervised learning»)." }, { "code": null, "e": 5613, "s": 5381, "text": "Tails of the distribution are too heavy. For instance, “Other methods such as naive bayes have the opposite bias and tend to push predictions closer to 0 and 1” (quote from «Predicting good probabilities with supervised learning»)." }, { "code": null, "e": 5843, "s": 5613, "text": "Suppose you have trained a classifier that yields accurate but uncalibrated probabilities. The idea of probability calibration is to build a second model (called calibrator) that is able to “correct” them into real probabilities." }, { "code": null, "e": 5962, "s": 5843, "text": "Note that calibration should not be carried out on the same data that has been used for training the first classifier." }, { "code": null, "e": 6144, "s": 5962, "text": "Therefore, calibration consists in a function that transforms a 1-dimensional vector (of uncalibrated probabilities) into another 1-dimensional vector (of calibrated probabilities)." }, { "code": null, "e": 6188, "s": 6144, "text": "Two methods are mostly used as calibrators:" }, { "code": null, "e": 6389, "s": 6188, "text": "Isotonic regression. A non-parametric algorithm that fits a non-decreasing free form line to the data. The fact that the line is non-decreasing is fundamental because it respects the original sorting." }, { "code": null, "e": 6410, "s": 6389, "text": "Logistic regression." }, { "code": null, "e": 6498, "s": 6410, "text": "Let’s see how to use calibrators in practice in Python, with the help of a toy dataset:" }, { "code": null, "e": 6829, "s": 6498, "text": "from sklearn.datasets import make_classificationX, y = make_classification( n_samples = 15000, n_features = 50, n_informative = 30, n_redundant = 20, weights = [.9, .1], random_state = 0)X_train, X_valid, X_test = X[:5000], X[5000:10000], X[10000:]y_train, y_valid, y_test = y[:5000], y[5000:10000], y[10000:]" }, { "code": null, "e": 6964, "s": 6829, "text": "First of all, we will need to fit a classifier. Let’s use random forest (but any model that has a «predict_proba» method would be ok)." }, { "code": null, "e": 7120, "s": 6964, "text": "from sklearn.ensemble import RandomForestClassifierforest = RandomForestClassifier().fit(X_train, y_train)proba_valid = forest.predict_proba(X_valid)[:, 1]" }, { "code": null, "e": 7261, "s": 7120, "text": "Then, we will use the output of the classifier (on validation data) to fit the calibrator and finally predicting probabilities on test data." }, { "code": null, "e": 7282, "s": 7261, "text": "Isotonic regression:" }, { "code": null, "e": 7508, "s": 7282, "text": "from sklearn.isotonic import IsotonicRegressioniso_reg = IsotonicRegression(y_min = 0, y_max = 1, out_of_bounds = 'clip').fit(proba_valid, y_valid)proba_test_forest_isoreg = iso_reg.predict(forest.predict_proba(X_test)[:, 1])" }, { "code": null, "e": 7529, "s": 7508, "text": "Logistic regression:" }, { "code": null, "e": 7757, "s": 7529, "text": "from sklearn.linear_model import LogisticRegressionlog_reg = LogisticRegression().fit(proba_valid.reshape(-1, 1), y_valid)proba_test_forest_logreg = log_reg.predict_proba(forest.predict_proba(X_test)[:, 1].reshape(-1, 1))[:, 1]" }, { "code": null, "e": 7823, "s": 7757, "text": "At this point we have three options for predicting probabilities:" }, { "code": null, "e": 7916, "s": 7823, "text": "plain random forest,random forest + isotonic regression,random forest + logistic regression." }, { "code": null, "e": 7937, "s": 7916, "text": "plain random forest," }, { "code": null, "e": 7974, "s": 7937, "text": "random forest + isotonic regression," }, { "code": null, "e": 8011, "s": 7974, "text": "random forest + logistic regression." }, { "code": null, "e": 8066, "s": 8011, "text": "But how do we assess which one is the most calibrated?" }, { "code": null, "e": 8272, "s": 8066, "text": "Everybody likes plots. But besides the calibration plot, we need a quantitative way to measure (mis)calibration. The most commonly used metric is called Expected Calibration Error. It answers the question:" }, { "code": null, "e": 8353, "s": 8272, "text": "How far away is our predicted probability from the true probability, on average?" }, { "code": null, "e": 8393, "s": 8353, "text": "Let’s take one classifier for instance:" }, { "code": null, "e": 8576, "s": 8393, "text": "It’s easy to define the calibration error of a single bin: it’s the absolute difference between the mean of predicted probabilities and the fraction of positives within the same bin." }, { "code": null, "e": 8861, "s": 8576, "text": "If you think about it, it’s pretty intuitive. Take one bin, and suppose the mean of its predicted probabilities is 25%. Thus, we expect that the fraction of positives in that bin is approximately equal to 25%. The farther this value is from 25%, the worse the calibration of that bin." }, { "code": null, "e": 9050, "s": 8861, "text": "Thus, Expected Calibration Error (ECE) is a weighted mean of the calibration errors of the single bins, where each bin weighs proportionally to the number of observations that it contains:" }, { "code": null, "e": 9169, "s": 9050, "text": "where b identifies a bin and B is the number of bins. Note that the denominator is simply the total number of samples." }, { "code": null, "e": 9535, "s": 9169, "text": "But this formula leaves us the problem of defining the number of bins. In order to find a metric that is as neutral as possible, I propose to set the number of bins according to the Freedman-Diaconis rule (which is a statistical rule designed for finding the number of bins that makes the histogram as close as possible to the theoretical probability distribution)." }, { "code": null, "e": 9720, "s": 9535, "text": "Using Freedman-Diaconis rule in Python is extremely simple because it’s already implemented in numpy’s histogram function (it’s enough to pass the string “fd” to the parameter “bins”)." }, { "code": null, "e": 9840, "s": 9720, "text": "Here is a Python implementation of the expected calibration error, which employs the Freedman-Diaconis rule as default:" }, { "code": null, "e": 10527, "s": 9840, "text": "def expected_calibration_error(y, proba, bins = 'fd'): import numpy as np bin_count, bin_edges = np.histogram(proba, bins = bins) n_bins = len(bin_count) bin_edges[0] -= 1e-8 # because left edge is not included bin_id = np.digitize(proba, bin_edges, right = True) - 1 bin_ysum = np.bincount(bin_id, weights = y, minlength = n_bins) bin_probasum = np.bincount(bin_id, weights = proba, minlength = n_bins) bin_ymean = np.divide(bin_ysum, bin_count, out = np.zeros(n_bins), where = bin_count > 0) bin_probamean = np.divide(bin_probasum, bin_count, out = np.zeros(n_bins), where = bin_count > 0) ece = np.abs((bin_probamean - bin_ymean) * bin_count).sum() / len(proba) return ece" }, { "code": null, "e": 10663, "s": 10527, "text": "Now that we have a metric for calibration, let’s compare the calibration of the three models that we have obtained above (on test set):" }, { "code": null, "e": 10896, "s": 10663, "text": "In this case, isotonic regression provided the best outcome in terms of calibration, being far only 1.2% from the true probability, on average. It’s a huge improvement, if you consider that the ECE of the plain random forest was 7%." }, { "code": null, "e": 11039, "s": 10896, "text": "Here are some interesting papers (on which this article is based) that I recommend if you want to deepen the topic of probability calibration:" }, { "code": null, "e": 11135, "s": 11039, "text": "«Predicting good probabilities with supervised learning» (2005) by Caruana and Niculescu-Mizil." }, { "code": null, "e": 11199, "s": 11135, "text": "«On Calibration of Modern Neural Networks» (2017) by Guo et al." }, { "code": null, "e": 11288, "s": 11199, "text": "«Obtaining Well Calibrated Probabilities Using Bayesian Binning» (2015) by Naeini et al." }, { "code": null, "e": 11346, "s": 11288, "text": "Thank you for reading! I hope you found this post useful." } ]
Difference between BIGINT and BIGINT(20) in MySQL?
The only difference between BIGINT and BIGINT(20) is for displaying width. The 20 can be used for displaying width. Let us see an example and create a table. Here, we have set BIGINT(20) − mysql> create table DemoTable ( Number bigint(20) zerofill ); Query OK, 0 rows affected (0.58 sec) Insert some records in the table using insert command − mysql> insert into DemoTable values(1); Query OK, 1 row affected (0.08 sec) mysql> insert into DemoTable values(12); Query OK, 1 row affected (0.15 sec) mysql> insert into DemoTable values(123); Query OK, 1 row affected (0.13 sec) mysql> insert into DemoTable values(1234); Query OK, 1 row affected (0.11 sec) Display all records from the table using select statement − mysql> select *from DemoTable; This will produce the following output. The width is now 20, therefore the number expands and visible like below − +----------------------+ | Number | +----------------------+ | 00000000000000000001 | | 00000000000000000012 | | 00000000000000000123 | | 00000000000000001234 | +----------------------+ 4 rows in set (0.00 sec)
[ { "code": null, "e": 1178, "s": 1062, "text": "The only difference between BIGINT and BIGINT(20) is for displaying width. The 20 can be used for displaying width." }, { "code": null, "e": 1251, "s": 1178, "text": "Let us see an example and create a table. Here, we have set BIGINT(20) −" }, { "code": null, "e": 1353, "s": 1251, "text": "mysql> create table DemoTable\n(\n Number bigint(20) zerofill\n);\nQuery OK, 0 rows affected (0.58 sec)" }, { "code": null, "e": 1409, "s": 1353, "text": "Insert some records in the table using insert command −" }, { "code": null, "e": 1719, "s": 1409, "text": "mysql> insert into DemoTable values(1);\nQuery OK, 1 row affected (0.08 sec)\nmysql> insert into DemoTable values(12);\nQuery OK, 1 row affected (0.15 sec)\nmysql> insert into DemoTable values(123);\nQuery OK, 1 row affected (0.13 sec)\nmysql> insert into DemoTable values(1234);\nQuery OK, 1 row affected (0.11 sec)" }, { "code": null, "e": 1779, "s": 1719, "text": "Display all records from the table using select statement −" }, { "code": null, "e": 1810, "s": 1779, "text": "mysql> select *from DemoTable;" }, { "code": null, "e": 1925, "s": 1810, "text": "This will produce the following output. The width is now 20, therefore the number expands and visible like below −" }, { "code": null, "e": 2150, "s": 1925, "text": "+----------------------+\n| Number |\n+----------------------+\n| 00000000000000000001 |\n| 00000000000000000012 |\n| 00000000000000000123 |\n| 00000000000000001234 |\n+----------------------+\n4 rows in set (0.00 sec)" } ]
Activity Recognition using Smartphones — Machine Learning application | by Karan Bhanot | Towards Data Science
When I first began to explore machine learning, I read numerous articles and research papers. One of the papers I discovered initially, involved using Machine Learning to classify activities. And even though implementation seemed a far-fetched goal at that time, I was intrigued by the application. Having gained some experience since that day, I believe today I can apply my machine learning knowledge to recognise activities now. For the dataset, I selected the training.csv and test.csv files from the Kaggle competition. I worked on this project as a Jupyter notebook which is available in my Activity Recognition using Machine Learning repo. As a side note, now it’s much easier to find datasets online through Google Dataset Search. This is from where I found the dataset for this project. So, in this article I’ll explain the steps I took in this project and how I used machine learning to classify activities with over 96% accuracy. Fork the repository, open the notebook and let’s start. There are a number of repositories that we will need in this project. numpy and pandas: numpy enables us to work with arrays with great efficiency. Pandas is used to read the dataset file and import it as a dataframe, which is similar to a table with rows and columns.matplotlib: matplotlib is a highly customisable package which has the subpackage pyplot that enables us to draw plots, bar charts, pie charts and more. We get options to add legends, axis titles, change thickness of lines etc. The cm package (colormap) allows us to get colors for our charts.sklearn: This machine learning library includes numerous machine learning algorithms already builtin with certain parameters set as default parameters, so they work right out of the box. numpy and pandas: numpy enables us to work with arrays with great efficiency. Pandas is used to read the dataset file and import it as a dataframe, which is similar to a table with rows and columns. matplotlib: matplotlib is a highly customisable package which has the subpackage pyplot that enables us to draw plots, bar charts, pie charts and more. We get options to add legends, axis titles, change thickness of lines etc. The cm package (colormap) allows us to get colors for our charts. sklearn: This machine learning library includes numerous machine learning algorithms already builtin with certain parameters set as default parameters, so they work right out of the box. If you notice, I’ve added a line %matplotlib inline. This changes the backend for matplotlib to the Jupyter notebook as a result of which, all plots will now show up inline in the Jupyter notebook itself. In this project, I have used four algorithms namely Support Vector Classifier as SVC, Logistic Regression as LogisticRegression, K Nearest Neighbors Classifier as KNeighborsClassifier, and Random Forest Classifier as RandomForestClassifier. To calculate accuracy, I imported accuracy_score. First we will use read_csv() method to import the train and test files into the notebook and save it in the variables training_data and testing_data. We use shape method to find the size of the dataset. It results in the output as (rows, columns). There are 7352 rows and 563 columns in the training dataset and 2947 rows and 563 columns in the testing dataset. We must ensure that the dataset does not have any null values. We use isnull().values.any() to check if any cell is empty. We print the output and see that the output is False meaning there are no null values. So, we can proceed further. We can use the head(5) method to get a glimpse of the first 5 rows of the training data. We see there are 563 columns with the last column as Activity which will act as our label. In the remaining columns, subject is of no specific use for our machine learning application as we want to explore the activity and not who performed it. We can drop this column and the remaining 561 columns will be our features. Same will be done for the testing data. By convention, small letter y acts as the set of labels and capital letter X acts as the set of features. Thus, the names are y_train, X_train, y_test and X_test. We will use these variables during machine learning analysis. One of the key things when working with data is to ensure that all classes are of approximately equal size. This is essential so that the machine learning algorithm is not biased towards any one class. Let’s understand this with the help of an example. Say, the dataset is of 30 activities with varied share percentage. The dataset has 99% data for Activity 1 and 1% data for the remaining activities. In such a case, machine learning will never learn any pattern about the data. It’ll consider that for 99 out of 100 cases, the activity will be Activity 1. So, it’ll always output Activity 1 without any consideration for the data and will still achieve 99% accuracy. Such a model is incorrect and thus approximately equal share of different data classes must be ensured. We first get the count of records for each type of activity in the count_of_each_activity variable. value_counts() gives the counts and np.array converts it into an array. The counts are presented in alphabetical order of the name of the activity. unique() gives us unique values in y_train. We must sort it so that they align with the count values gathered above. The rcParams helps us define certain styles for out chart. We define the figure size using figure.figsize and the font size using font.size. We now have our data ready for the pie chart. pie() method creates a pie chart. The first argument is the count for each activity, the second argument is the respective activity name denoted by labels and the third argument autopct computes percentages for each activity. On observing the pie chart above, you can see that the share of each activity is almost equal. The dataset is very well formed and can be used directly. Next, I observe the type of readings in the datatset. If you look at the column headings, you can see that the columns have either the text Acc to refer to accelerometer reading, Gyro to refer to gyroscope values or none of the two to refer to all others. I first iterate through column names, to check if they contain ‘Acc’ or ‘Gyro’ or not. Based on the variable values, I plot a bar plot using bar() method of pyplot subpackage. The first argument are the X axis labels, the second argument takes the array of Y axis values and the color argument defines the colors red, blue and green respectively for the three bars. I again defined the figure size and font size for this bar plot. To get a better perspective on the data, I understood that I had to take a look at the activities. Thus, I decided that I’ll try to explore more about the ‘Standing’ activity. This is all the information I knew before I began: The dataset has activity records for 30 individuals and some individual performed the Standing activity.The data collected is recorded at a stretch for each individual, especially for each activity. This means the records of any given activity will actually be in time series.There are many features in each record, but I must not include all in one attempt as it might make the understanding of the data more difficult. The dataset has activity records for 30 individuals and some individual performed the Standing activity. The data collected is recorded at a stretch for each individual, especially for each activity. This means the records of any given activity will actually be in time series. There are many features in each record, but I must not include all in one attempt as it might make the understanding of the data more difficult. Based on the information I had, I decided that I’d plot a line graph for all individuals who performed the Standing activity over a time period with respect to a feature. I took the feature as the angle between X and mean Gravity, which should stay almost constant except for minor changes due to human error. I first began by selecting all rows from the dataset that have the ‘Activity’ label as ‘STANDING’ and store it in standing_activity. Here, we must ensure that we reset the index. This is necessary because when we selected the above rows, the removed rows did get removed but the remaining rows’ index did not change and they were no longer in a continuous order. The data collected is in continuous time series for each individual and was recorded at the same rate. So, I can simply assign time values to each activity starting from 0 each time the subject changes. For each subject, the Standing activity records will start with a time value of 0 and increment by 1 till the previous row’s subject matches the present row’s subject. I store all the time series in a variable time_series and convert it into a dataframe using pandas method DataFrame() and store it in a variable time_series_df. Lastly, I combine the records and the time series variable together in standing_activity_df using pandas concatenate() method. axis = 1 tells the method to combine the two dataframes and append them as columns. np.zeros() creates a numpy array of zeros with size equal to the number within parentheses. For a dataframe, appending a square bracket at the end of shape helps us get rows or columns if we use 0 or 1 inside the bracket respectively. Now, as the data is ready to be plot, I use the matplotlib’s cm subpackage to get a list of colors using the rainbow method. I then iterate over the list of subjects inside the standing_activity_df. I specify size of the graph using rcParams. In the plot method, the first argument is X-axis values which is Time column in our case. The second column is for Y-axis values so I input the angle(X, gravityMean) values. Color is defined in c, subject numbers are set as label and width of the line is set to 4 in linewidth. I then specify the X-axis label, Y-axis label and title for the plot. legend() method displays the legend on the graph. If we take a closer look at the graph, we can see that each line on an average, transitions between a maximum range of 0.2–0.3 values. This is indeed the expected behaviour as slight variations can be attributed to minor human errors. Now comes the final step in our process to actually use machine learning algorithms and make classifications. We create an array of zeros of size 4 to store accuracy for each algorithm. We will use this while creating the bar plot. accuracy_scores = np.zeros(4) The process for each one is the same as I will be using the default values of various parameters. Let’s understand it with the help of Support Vector Classifier. First, I write the name of the algorithm as imported SVC(). This is followed by the fit() method which models the algorithm on the data provided. I input the arguments as training data, hence, X_train and y_train. Next, I use the predict() method to predict the outputs of the test data, X_test and store it in prediction variable. I then use the accuracy_score function to calculate the accuracy, which takes the first argument as true values and second argument as prediction. I multiplied it by 100 to convert into percentage. We do the same steps for each algorithm. As you can see from the output values above, the Logistic Regression algorithm performed the best with the accuracy of over 96%. We can also visualise the outputs as a bar graph. In this article, I discussed Activity Recognition, drew visualisations from the dataset and used machine learning algorithms for classifying activities. As per the results, Logistic Regression achieved the highest accuracy. I hope you like my work. As a future perspective, you can try other algorithms, or choose different values of parameters to improve the accuracy even further. Please feel free to share your thoughts and ideas.
[ { "code": null, "e": 604, "s": 172, "text": "When I first began to explore machine learning, I read numerous articles and research papers. One of the papers I discovered initially, involved using Machine Learning to classify activities. And even though implementation seemed a far-fetched goal at that time, I was intrigued by the application. Having gained some experience since that day, I believe today I can apply my machine learning knowledge to recognise activities now." }, { "code": null, "e": 819, "s": 604, "text": "For the dataset, I selected the training.csv and test.csv files from the Kaggle competition. I worked on this project as a Jupyter notebook which is available in my Activity Recognition using Machine Learning repo." }, { "code": null, "e": 968, "s": 819, "text": "As a side note, now it’s much easier to find datasets online through Google Dataset Search. This is from where I found the dataset for this project." }, { "code": null, "e": 1169, "s": 968, "text": "So, in this article I’ll explain the steps I took in this project and how I used machine learning to classify activities with over 96% accuracy. Fork the repository, open the notebook and let’s start." }, { "code": null, "e": 1239, "s": 1169, "text": "There are a number of repositories that we will need in this project." }, { "code": null, "e": 1916, "s": 1239, "text": "numpy and pandas: numpy enables us to work with arrays with great efficiency. Pandas is used to read the dataset file and import it as a dataframe, which is similar to a table with rows and columns.matplotlib: matplotlib is a highly customisable package which has the subpackage pyplot that enables us to draw plots, bar charts, pie charts and more. We get options to add legends, axis titles, change thickness of lines etc. The cm package (colormap) allows us to get colors for our charts.sklearn: This machine learning library includes numerous machine learning algorithms already builtin with certain parameters set as default parameters, so they work right out of the box." }, { "code": null, "e": 2115, "s": 1916, "text": "numpy and pandas: numpy enables us to work with arrays with great efficiency. Pandas is used to read the dataset file and import it as a dataframe, which is similar to a table with rows and columns." }, { "code": null, "e": 2408, "s": 2115, "text": "matplotlib: matplotlib is a highly customisable package which has the subpackage pyplot that enables us to draw plots, bar charts, pie charts and more. We get options to add legends, axis titles, change thickness of lines etc. The cm package (colormap) allows us to get colors for our charts." }, { "code": null, "e": 2595, "s": 2408, "text": "sklearn: This machine learning library includes numerous machine learning algorithms already builtin with certain parameters set as default parameters, so they work right out of the box." }, { "code": null, "e": 2800, "s": 2595, "text": "If you notice, I’ve added a line %matplotlib inline. This changes the backend for matplotlib to the Jupyter notebook as a result of which, all plots will now show up inline in the Jupyter notebook itself." }, { "code": null, "e": 3091, "s": 2800, "text": "In this project, I have used four algorithms namely Support Vector Classifier as SVC, Logistic Regression as LogisticRegression, K Nearest Neighbors Classifier as KNeighborsClassifier, and Random Forest Classifier as RandomForestClassifier. To calculate accuracy, I imported accuracy_score." }, { "code": null, "e": 3241, "s": 3091, "text": "First we will use read_csv() method to import the train and test files into the notebook and save it in the variables training_data and testing_data." }, { "code": null, "e": 3691, "s": 3241, "text": "We use shape method to find the size of the dataset. It results in the output as (rows, columns). There are 7352 rows and 563 columns in the training dataset and 2947 rows and 563 columns in the testing dataset. We must ensure that the dataset does not have any null values. We use isnull().values.any() to check if any cell is empty. We print the output and see that the output is False meaning there are no null values. So, we can proceed further." }, { "code": null, "e": 4141, "s": 3691, "text": "We can use the head(5) method to get a glimpse of the first 5 rows of the training data. We see there are 563 columns with the last column as Activity which will act as our label. In the remaining columns, subject is of no specific use for our machine learning application as we want to explore the activity and not who performed it. We can drop this column and the remaining 561 columns will be our features. Same will be done for the testing data." }, { "code": null, "e": 4366, "s": 4141, "text": "By convention, small letter y acts as the set of labels and capital letter X acts as the set of features. Thus, the names are y_train, X_train, y_test and X_test. We will use these variables during machine learning analysis." }, { "code": null, "e": 4568, "s": 4366, "text": "One of the key things when working with data is to ensure that all classes are of approximately equal size. This is essential so that the machine learning algorithm is not biased towards any one class." }, { "code": null, "e": 5139, "s": 4568, "text": "Let’s understand this with the help of an example. Say, the dataset is of 30 activities with varied share percentage. The dataset has 99% data for Activity 1 and 1% data for the remaining activities. In such a case, machine learning will never learn any pattern about the data. It’ll consider that for 99 out of 100 cases, the activity will be Activity 1. So, it’ll always output Activity 1 without any consideration for the data and will still achieve 99% accuracy. Such a model is incorrect and thus approximately equal share of different data classes must be ensured." }, { "code": null, "e": 5387, "s": 5139, "text": "We first get the count of records for each type of activity in the count_of_each_activity variable. value_counts() gives the counts and np.array converts it into an array. The counts are presented in alphabetical order of the name of the activity." }, { "code": null, "e": 5645, "s": 5387, "text": "unique() gives us unique values in y_train. We must sort it so that they align with the count values gathered above. The rcParams helps us define certain styles for out chart. We define the figure size using figure.figsize and the font size using font.size." }, { "code": null, "e": 5917, "s": 5645, "text": "We now have our data ready for the pie chart. pie() method creates a pie chart. The first argument is the count for each activity, the second argument is the respective activity name denoted by labels and the third argument autopct computes percentages for each activity." }, { "code": null, "e": 6070, "s": 5917, "text": "On observing the pie chart above, you can see that the share of each activity is almost equal. The dataset is very well formed and can be used directly." }, { "code": null, "e": 6326, "s": 6070, "text": "Next, I observe the type of readings in the datatset. If you look at the column headings, you can see that the columns have either the text Acc to refer to accelerometer reading, Gyro to refer to gyroscope values or none of the two to refer to all others." }, { "code": null, "e": 6757, "s": 6326, "text": "I first iterate through column names, to check if they contain ‘Acc’ or ‘Gyro’ or not. Based on the variable values, I plot a bar plot using bar() method of pyplot subpackage. The first argument are the X axis labels, the second argument takes the array of Y axis values and the color argument defines the colors red, blue and green respectively for the three bars. I again defined the figure size and font size for this bar plot." }, { "code": null, "e": 6933, "s": 6757, "text": "To get a better perspective on the data, I understood that I had to take a look at the activities. Thus, I decided that I’ll try to explore more about the ‘Standing’ activity." }, { "code": null, "e": 6984, "s": 6933, "text": "This is all the information I knew before I began:" }, { "code": null, "e": 7405, "s": 6984, "text": "The dataset has activity records for 30 individuals and some individual performed the Standing activity.The data collected is recorded at a stretch for each individual, especially for each activity. This means the records of any given activity will actually be in time series.There are many features in each record, but I must not include all in one attempt as it might make the understanding of the data more difficult." }, { "code": null, "e": 7510, "s": 7405, "text": "The dataset has activity records for 30 individuals and some individual performed the Standing activity." }, { "code": null, "e": 7683, "s": 7510, "text": "The data collected is recorded at a stretch for each individual, especially for each activity. This means the records of any given activity will actually be in time series." }, { "code": null, "e": 7828, "s": 7683, "text": "There are many features in each record, but I must not include all in one attempt as it might make the understanding of the data more difficult." }, { "code": null, "e": 8138, "s": 7828, "text": "Based on the information I had, I decided that I’d plot a line graph for all individuals who performed the Standing activity over a time period with respect to a feature. I took the feature as the angle between X and mean Gravity, which should stay almost constant except for minor changes due to human error." }, { "code": null, "e": 8501, "s": 8138, "text": "I first began by selecting all rows from the dataset that have the ‘Activity’ label as ‘STANDING’ and store it in standing_activity. Here, we must ensure that we reset the index. This is necessary because when we selected the above rows, the removed rows did get removed but the remaining rows’ index did not change and they were no longer in a continuous order." }, { "code": null, "e": 9244, "s": 8501, "text": "The data collected is in continuous time series for each individual and was recorded at the same rate. So, I can simply assign time values to each activity starting from 0 each time the subject changes. For each subject, the Standing activity records will start with a time value of 0 and increment by 1 till the previous row’s subject matches the present row’s subject. I store all the time series in a variable time_series and convert it into a dataframe using pandas method DataFrame() and store it in a variable time_series_df. Lastly, I combine the records and the time series variable together in standing_activity_df using pandas concatenate() method. axis = 1 tells the method to combine the two dataframes and append them as columns." }, { "code": null, "e": 9479, "s": 9244, "text": "np.zeros() creates a numpy array of zeros with size equal to the number within parentheses. For a dataframe, appending a square bracket at the end of shape helps us get rows or columns if we use 0 or 1 inside the bracket respectively." }, { "code": null, "e": 9604, "s": 9479, "text": "Now, as the data is ready to be plot, I use the matplotlib’s cm subpackage to get a list of colors using the rainbow method." }, { "code": null, "e": 10120, "s": 9604, "text": "I then iterate over the list of subjects inside the standing_activity_df. I specify size of the graph using rcParams. In the plot method, the first argument is X-axis values which is Time column in our case. The second column is for Y-axis values so I input the angle(X, gravityMean) values. Color is defined in c, subject numbers are set as label and width of the line is set to 4 in linewidth. I then specify the X-axis label, Y-axis label and title for the plot. legend() method displays the legend on the graph." }, { "code": null, "e": 10355, "s": 10120, "text": "If we take a closer look at the graph, we can see that each line on an average, transitions between a maximum range of 0.2–0.3 values. This is indeed the expected behaviour as slight variations can be attributed to minor human errors." }, { "code": null, "e": 10465, "s": 10355, "text": "Now comes the final step in our process to actually use machine learning algorithms and make classifications." }, { "code": null, "e": 10587, "s": 10465, "text": "We create an array of zeros of size 4 to store accuracy for each algorithm. We will use this while creating the bar plot." }, { "code": null, "e": 10617, "s": 10587, "text": "accuracy_scores = np.zeros(4)" }, { "code": null, "e": 10993, "s": 10617, "text": "The process for each one is the same as I will be using the default values of various parameters. Let’s understand it with the help of Support Vector Classifier. First, I write the name of the algorithm as imported SVC(). This is followed by the fit() method which models the algorithm on the data provided. I input the arguments as training data, hence, X_train and y_train." }, { "code": null, "e": 11350, "s": 10993, "text": "Next, I use the predict() method to predict the outputs of the test data, X_test and store it in prediction variable. I then use the accuracy_score function to calculate the accuracy, which takes the first argument as true values and second argument as prediction. I multiplied it by 100 to convert into percentage. We do the same steps for each algorithm." }, { "code": null, "e": 11529, "s": 11350, "text": "As you can see from the output values above, the Logistic Regression algorithm performed the best with the accuracy of over 96%. We can also visualise the outputs as a bar graph." }, { "code": null, "e": 11753, "s": 11529, "text": "In this article, I discussed Activity Recognition, drew visualisations from the dataset and used machine learning algorithms for classifying activities. As per the results, Logistic Regression achieved the highest accuracy." } ]
Longest Distinct characters in string | Practice | GeeksforGeeks
Given a string S, find length of the longest substring with all distinct characters. Example 1: Input: S = "geeksforgeeks" Output: 7 Explanation: "eksforg" is the longest substring with all distinct characters. ​Example 2: Input: S = "aaa" Output: 1 Explanation: "a" is the longest substring with all distinct characters. Your Task: You don't need to read input or print anything. Your task is to complete the function longestSubstrDitinctChars() which takes the string S as input and returns the length of the longest substring with all distinct characters. Expected Time Complexity: O(|S|). Expected Auxiliary Space: O(K), where K is Constant. Constraints: 1<=|S|<=105 0 nikhilpmsnick5 days ago unordered_set<char> un; int length=0; int count=0; for(int i=0; i<S.size();i++) { if(un.find(S[i])==un.end()) { //s.push_back(S[i]); un.insert(S[i]); length++; } else { if(length>count) { count=length; } un.clear(); //s.push_back(S[i]); i=i-length; length=0; } } if(length>=count) return length; else return count; 0 ayushmishra252 weeks ago longestSubstrDistinctChars(s) { let items = s.split(""), iteratorA=0, iteratorB=0, newStr="", maxStrLength=""; while(iteratorA !== items.length && iteratorB !== items.length){ if(!newStr.includes(items[iteratorB])){ newStr+=items[iteratorB]; if(maxStrLength < newStr.length){ maxStrLength = newStr.length; } }else{ if(maxStrLength < newStr.length){ maxStrLength = newStr.length; } iteratorB =iteratorA; iteratorA++; if(items.length > iteratorB) newStr = items[iteratorB]; } iteratorB++; } return maxStrLength; } 0 harsh39rathod2 weeks ago SIMPLE SOLN C++ int longestSubstrDistinctChars (string S){ int ans=INT_MIN; map<char,int> m; int st=0; int run=0; while(run<S.length()){ if(m[S[run]]!=0){ ans=max(ans,run-st); while(S[st]!=S[run]){ m[S[st]]--; st++; } m[S[st]]--; st++; } m[S[run]]++; run++; } ans=max(ans,run-st); return ans; } 0 ravi1010prakash1 month ago int longestSubstrDistinctChars (string s){ vector<int>prev(256,-1); int n=s.length(); int i=0; int res=0; for(int j=0;j<n;j++) { i=max(i,prev[s[j]]+1); int maxend=j-i+1; res=max(res,maxend); prev[s[j]]=j; } return res; } 0 ravi1010prakash1 month ago int i=0,j=0,mx=0; unordered_map<int,int>mp; while(j<s.size()) { mp[s[j]]++; if(mp.size()>j-i+1) j++; else if( mp.size()==j-i+1) { mx=max(mx,j-i+1); j++; } else if(mp.size()<j-i+1) { while(mp.size()<j-i+1) { mp[s[i]]--; if(mp[s[i]]==0) mp.erase(s[i]); i++; }j++; } }return mx; 0 geeky_kuldeep1 month ago JS Solution class Solution { longestSubstrDistinctChars(s) { let max = Number.MIN_VALUE; let sub = {}; let count = 0; let start = 0; let i = 0; while (i < s.length) { if (sub[s[i]] >= 1) { sub = {}; i = start + 1; sub[s[i]] = 1; start = i; count = 1; } else { sub[s[i]] = 1; count++; } if (count > max) { max = count; } i++; } return max; } } +1 ayushsunariya4581 month ago int longestSubstrDistinctChars (string s) { // your code here vector<int>res(26,0); int j=0,len=0; for(int i=0;i<s.size();i++){ res[s[i]-'a']++; while(res[s[i]-'a']>1){ res[s[j++]-'a']--; } len=max(len,i-j+1); } return len; } 0 tirtha19025681 month ago class Solution{ static int longestSubstrDistinctChars(String S){ HashMap<Character,Integer>map = new HashMap<>(); int i = 0; int j = 0; int max = Integer.MIN_VALUE; while(j<S.length()) { char ch = S.charAt(j); map.put(ch,map.getOrDefault(ch,0)+1 ); if(map.size() == j-i+1){ max = Math.max(max,j-i+1); } // remove elements if repeating elements found if(map.size() < j-i+1) { while(map.size() < j-i+1){ char ci = S.charAt(i); map.put(ci,map.get(ci)-1); if(map.get(ci) == 0){ map.remove(ci); } i++; } } j++; } if(max == Integer.MIN_VALUE){ return -1; } return max; } } +1 amanasati11 month ago Python using Sliding window technique class Solution: def longestSubstrDistinctChars(self, S): # code here l=0 i,j=0,0 dic={} while j<len(S): if S[j] not in dic: dic[S[j]]=1 l=max(l,len(dic)) else: while S[i]!=S[j]: del dic[S[i]] i+=1 i+=1 dic[S[j]]=1 j+=1 return l 0 deepeshacharya22 months ago Java Solution using HashMap static int longestSubstrDistinctChars(String S){ HashMap<Character, Integer> hm = new HashMap<>(); int maxCount = 0,i,n=S.length(),countTillNow = 0; for (i=0;i<n;i++) { if (hm.containsKey(S.charAt(i))) { i = hm.get(S.charAt(i)); i++; hm.clear(); hm.put(S.charAt(i),i); countTillNow = 1; } else { countTillNow++; hm.put(S.charAt(i),i); if (countTillNow > maxCount) maxCount = countTillNow; } } return maxCount; } 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": 324, "s": 238, "text": "Given a string S, find length of the longest substring with all distinct characters. " }, { "code": null, "e": 335, "s": 324, "text": "Example 1:" }, { "code": null, "e": 452, "s": 335, "text": "Input:\nS = \"geeksforgeeks\"\nOutput: 7\nExplanation: \"eksforg\" is the longest \nsubstring with all distinct characters.\n" }, { "code": null, "e": 467, "s": 452, "text": "​Example 2:" }, { "code": null, "e": 569, "s": 467, "text": "Input: \nS = \"aaa\"\nOutput: 1\nExplanation: \"a\" is the longest substring \nwith all distinct characters.\n" }, { "code": null, "e": 807, "s": 569, "text": "\nYour Task:\nYou don't need to read input or print anything. Your task is to complete the function longestSubstrDitinctChars() which takes the string S as input and returns the length of the longest substring with all distinct characters." }, { "code": null, "e": 895, "s": 807, "text": "\nExpected Time Complexity: O(|S|).\nExpected Auxiliary Space: O(K), where K is Constant." }, { "code": null, "e": 921, "s": 895, "text": "\nConstraints:\n1<=|S|<=105" }, { "code": null, "e": 925, "s": 923, "text": "0" }, { "code": null, "e": 949, "s": 925, "text": "nikhilpmsnick5 days ago" }, { "code": null, "e": 1447, "s": 949, "text": "unordered_set<char> un; int length=0; int count=0; for(int i=0; i<S.size();i++) { if(un.find(S[i])==un.end()) { //s.push_back(S[i]); un.insert(S[i]); length++; } else { if(length>count) { count=length; } un.clear(); //s.push_back(S[i]); i=i-length; length=0; } } if(length>=count) return length; else return count;" }, { "code": null, "e": 1449, "s": 1447, "text": "0" }, { "code": null, "e": 1474, "s": 1449, "text": "ayushmishra252 weeks ago" }, { "code": null, "e": 2200, "s": 1474, "text": "longestSubstrDistinctChars(s) { let items = s.split(\"\"), iteratorA=0, iteratorB=0, newStr=\"\", maxStrLength=\"\"; while(iteratorA !== items.length && iteratorB !== items.length){ if(!newStr.includes(items[iteratorB])){ newStr+=items[iteratorB]; if(maxStrLength < newStr.length){ maxStrLength = newStr.length; } }else{ if(maxStrLength < newStr.length){ maxStrLength = newStr.length; } iteratorB =iteratorA; iteratorA++; if(items.length > iteratorB) newStr = items[iteratorB]; } iteratorB++; } return maxStrLength; }" }, { "code": null, "e": 2202, "s": 2200, "text": "0" }, { "code": null, "e": 2227, "s": 2202, "text": "harsh39rathod2 weeks ago" }, { "code": null, "e": 2243, "s": 2227, "text": "SIMPLE SOLN C++" }, { "code": null, "e": 2647, "s": 2245, "text": "int longestSubstrDistinctChars (string S){ int ans=INT_MIN; map<char,int> m; int st=0; int run=0; while(run<S.length()){ if(m[S[run]]!=0){ ans=max(ans,run-st); while(S[st]!=S[run]){ m[S[st]]--; st++; } m[S[st]]--; st++; } m[S[run]]++; run++; } ans=max(ans,run-st); return ans; }" }, { "code": null, "e": 2649, "s": 2647, "text": "0" }, { "code": null, "e": 2676, "s": 2649, "text": "ravi1010prakash1 month ago" }, { "code": null, "e": 2913, "s": 2676, "text": "int longestSubstrDistinctChars (string s){ vector<int>prev(256,-1); int n=s.length(); int i=0; int res=0; for(int j=0;j<n;j++) { i=max(i,prev[s[j]]+1); int maxend=j-i+1; res=max(res,maxend); prev[s[j]]=j; } return res; }" }, { "code": null, "e": 2915, "s": 2913, "text": "0" }, { "code": null, "e": 2942, "s": 2915, "text": "ravi1010prakash1 month ago" }, { "code": null, "e": 3417, "s": 2942, "text": " int i=0,j=0,mx=0; unordered_map<int,int>mp; while(j<s.size()) { mp[s[j]]++; if(mp.size()>j-i+1) j++; else if( mp.size()==j-i+1) { mx=max(mx,j-i+1); j++; } else if(mp.size()<j-i+1) { while(mp.size()<j-i+1) { mp[s[i]]--; if(mp[s[i]]==0) mp.erase(s[i]); i++; }j++; } }return mx;" }, { "code": null, "e": 3419, "s": 3417, "text": "0" }, { "code": null, "e": 3444, "s": 3419, "text": "geeky_kuldeep1 month ago" }, { "code": null, "e": 3944, "s": 3444, "text": "JS Solution\n\nclass Solution {\n longestSubstrDistinctChars(s) {\n let max = Number.MIN_VALUE;\n let sub = {};\n let count = 0;\n let start = 0;\n let i = 0;\n while (i < s.length) {\n if (sub[s[i]] >= 1) {\n sub = {};\n i = start + 1;\n sub[s[i]] = 1;\n start = i;\n count = 1;\n } else {\n sub[s[i]] = 1;\n count++;\n }\n if (count > max) {\n max = count;\n }\n i++;\n }\n return max;\n }\n}" }, { "code": null, "e": 3947, "s": 3944, "text": "+1" }, { "code": null, "e": 3975, "s": 3947, "text": "ayushsunariya4581 month ago" }, { "code": null, "e": 4269, "s": 3975, "text": "int longestSubstrDistinctChars (string s)\n{\n // your code here\n vector<int>res(26,0);\n int j=0,len=0;\n for(int i=0;i<s.size();i++){\n res[s[i]-'a']++;\n while(res[s[i]-'a']>1){\n res[s[j++]-'a']--;\n }\n len=max(len,i-j+1);\n }\n return len;\n}" }, { "code": null, "e": 4271, "s": 4269, "text": "0" }, { "code": null, "e": 4296, "s": 4271, "text": "tirtha19025681 month ago" }, { "code": null, "e": 5257, "s": 4296, "text": "class Solution{\n static int longestSubstrDistinctChars(String S){\n HashMap<Character,Integer>map = new HashMap<>();\n int i = 0;\n int j = 0;\n int max = Integer.MIN_VALUE;\n \n while(j<S.length())\n {\n char ch = S.charAt(j);\n map.put(ch,map.getOrDefault(ch,0)+1 );\n \n if(map.size() == j-i+1){\n max = Math.max(max,j-i+1);\n }\n \n // remove elements if repeating elements found\n if(map.size() < j-i+1)\n {\n while(map.size() < j-i+1){\n char ci = S.charAt(i);\n map.put(ci,map.get(ci)-1);\n if(map.get(ci) == 0){\n map.remove(ci);\n }\n i++;\n } \n }\n \n j++;\n }\n if(max == Integer.MIN_VALUE){\n return -1;\n }\n return max;\n }\n}" }, { "code": null, "e": 5260, "s": 5257, "text": "+1" }, { "code": null, "e": 5282, "s": 5260, "text": "amanasati11 month ago" }, { "code": null, "e": 5320, "s": 5282, "text": "Python using Sliding window technique" }, { "code": null, "e": 5757, "s": 5320, "text": "class Solution:\n\n def longestSubstrDistinctChars(self, S):\n # code here\n l=0\n i,j=0,0\n dic={}\n while j<len(S):\n if S[j] not in dic:\n dic[S[j]]=1\n l=max(l,len(dic))\n else:\n while S[i]!=S[j]:\n del dic[S[i]]\n i+=1\n i+=1\n dic[S[j]]=1\n j+=1\n return l" }, { "code": null, "e": 5759, "s": 5757, "text": "0" }, { "code": null, "e": 5787, "s": 5759, "text": "deepeshacharya22 months ago" }, { "code": null, "e": 5815, "s": 5787, "text": "Java Solution using HashMap" }, { "code": null, "e": 6436, "s": 5815, "text": "static int longestSubstrDistinctChars(String S){ HashMap<Character, Integer> hm = new HashMap<>(); int maxCount = 0,i,n=S.length(),countTillNow = 0; for (i=0;i<n;i++) { if (hm.containsKey(S.charAt(i))) { i = hm.get(S.charAt(i)); i++; hm.clear(); hm.put(S.charAt(i),i); countTillNow = 1; } else { countTillNow++; hm.put(S.charAt(i),i); if (countTillNow > maxCount) maxCount = countTillNow; } } return maxCount; }" }, { "code": null, "e": 6582, "s": 6436, "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": 6618, "s": 6582, "text": " Login to access your submissions. " }, { "code": null, "e": 6628, "s": 6618, "text": "\nProblem\n" }, { "code": null, "e": 6638, "s": 6628, "text": "\nContest\n" }, { "code": null, "e": 6701, "s": 6638, "text": "Reset the IDE using the second button on the top right corner." }, { "code": null, "e": 6849, "s": 6701, "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": 7057, "s": 6849, "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": 7163, "s": 7057, "text": "You can access the hints to get an idea about what is expected of you as well as the final solution code." } ]
What is Bitwise OR Assignment Operator (|=) in JavaScript?
It performs OR operation on the right operand with the left operand and assigns the result to the left operand. You can try to run the following code to learn how to work with Bitwise OR Assignment Operator − <html> <body> <script> var a = 2; // Bit presentation 10 var b = 3; // Bit presentation 11 document.write("(a |= b) => "); document.write(a |= b); </script> </body> </html>
[ { "code": null, "e": 1174, "s": 1062, "text": "It performs OR operation on the right operand with the left operand and assigns the result to the left operand." }, { "code": null, "e": 1271, "s": 1174, "text": "You can try to run the following code to learn how to work with Bitwise OR Assignment Operator −" }, { "code": null, "e": 1499, "s": 1271, "text": "<html>\n <body>\n <script>\n var a = 2; // Bit presentation 10\n var b = 3; // Bit presentation 11\n\n document.write(\"(a |= b) => \");\n document.write(a |= b);\n </script>\n </body>\n</html>" } ]
How to center a Tkinter widget in a sticky frame?
Tkinter has lots of inbuilt functions and methods that can be used configure the properties of Tkinter widgets. These properties vary with different geometry managers. The grid geometry manager is one of them which deals with many complex layout problems in any application. Grid geometry manager adds all the widgets in the given space (if applicable) without overlapping each other. Let us suppose that we have created a sticky frame using Grid geometry manager and we want to center the Label text widget inside the frame. In this case, we have to first make the main window sticky by configuring the row and column property. Once the main window gets sticky with the frame, it can make any widget rationally resizable. The label widget must be sticky in this case. Now, to center the widget, specify the value of the row, column and weight. # Import the required library from tkinter import * # Create an instance of tkinter frame win= Tk() # Set the size of the Tkinter window win.geometry("700x350") # Add a frame to set the size of the window frame= Frame(win, relief= 'sunken') frame.grid(sticky= "we") # Make the frame sticky for every case frame.grid_rowconfigure(0, weight=1) frame.grid_columnconfigure(0, weight=1) # Make the window sticky for every case win.grid_rowconfigure(0, weight=1) win.grid_columnconfigure(0, weight=1) # Add a label widget label= Label(frame, text= "Hey Folks! Welcome to Tutorialspoint", font=('Helvetica 15 bold'), bg= "white") label.grid(row=3,column=0) label.grid_rowconfigure(1, weight=1) label.grid_columnconfigure(1, weight=1) win.mainloop() Executing the above code will display a centered Label Text lying inside the sticky frame.
[ { "code": null, "e": 1447, "s": 1062, "text": "Tkinter has lots of inbuilt functions and methods that can be used configure the properties of Tkinter widgets. These properties vary with different geometry managers. The grid geometry manager is one of them which deals with many complex layout problems in any application. Grid geometry manager adds all the widgets in the given space (if applicable) without overlapping each other." }, { "code": null, "e": 1907, "s": 1447, "text": "Let us suppose that we have created a sticky frame using Grid geometry manager and we want to center the Label text widget inside the frame. In this case, we have to first make the main window sticky by configuring the row and column property. Once the main window gets sticky with the frame, it can make any widget rationally resizable. The label widget must be sticky in this case. Now, to center the widget, specify the value of the row, column and weight." }, { "code": null, "e": 2656, "s": 1907, "text": "# Import the required library\nfrom tkinter import *\n\n# Create an instance of tkinter frame\nwin= Tk()\n\n# Set the size of the Tkinter window\nwin.geometry(\"700x350\")\n\n# Add a frame to set the size of the window\nframe= Frame(win, relief= 'sunken')\nframe.grid(sticky= \"we\")\n\n# Make the frame sticky for every case\nframe.grid_rowconfigure(0, weight=1)\nframe.grid_columnconfigure(0, weight=1)\n\n# Make the window sticky for every case\nwin.grid_rowconfigure(0, weight=1)\nwin.grid_columnconfigure(0, weight=1)\n\n# Add a label widget\nlabel= Label(frame, text= \"Hey Folks! Welcome to Tutorialspoint\",\nfont=('Helvetica 15 bold'), bg= \"white\")\nlabel.grid(row=3,column=0)\nlabel.grid_rowconfigure(1, weight=1)\nlabel.grid_columnconfigure(1, weight=1)\n\nwin.mainloop()" }, { "code": null, "e": 2747, "s": 2656, "text": "Executing the above code will display a centered Label Text lying inside the sticky frame." } ]
How to execute zombie and orphan process in a single C program?
In this section we will see how to execute zombie process and orphan process in a single program in C/C++. Before going to the main discussion, let us see what are the zombie process and orphan process. A zombie process is a process whose execution is completed but it still has an entry in the process table. Zombie processes usually occur for child processes, as the parent process still needs to read its child’s exit status. Once this is done using the wait system call, the zombie process is eliminated from the process table. This is known as reaping the zombie process. Orphan processes are those processes that are still running even though their parent process has terminated or finished. A process can be orphaned intentionally or unintentionally. An intentionally orphaned process runs in the background without any manual support. This is usually done to start an indefinitely running service or to complete a long-running job without user attention. An unintentionally orphaned process is created when its parent process crashes or terminates. Unintentional orphan processes can be avoided using the process group mechanism. Now in the following code we will execute zombie and orphan process simultaneously. Here we have a parent process, it has a child, and this child has another child. If our control inserts into child process, then we will stop the execution for 5 seconds so it can finish up the parent process. Thus the child process become orphan process. After that the grandchild process will be converted into Zombie process. The grandchild finishes execution when its parent (the child of the main process) sleeps for 1 second. Hence the grandchild process does not call terminate, and its entry will be there in the process table. #include <stdio.h> #include <unistd.h> int main() { int x = fork(); //create child process if (x > 0) //if x is non zero, then it is parent process printf("Inside Parent---- PID is : %d\n", getpid()); else if (x == 0) { //for chile process x will be 0 sleep(5); //wait for some times x = fork(); if (x > 0) { printf("Inside Child---- PID :%d and PID of parent : %d\n", getpid(), getppid()); while(1) sleep(1); printf("Inside Child---- PID of parent : %d\n", getppid()); }else if (x == 0) printf("Inside grandchild process---- PID of parent : %d\n", getppid()); } return 0; } soumyadeep@soumyadeep-VirtualBox:~$ ./a.out Inside Parent---- PID is : 3821 soumyadeep@soumyadeep-VirtualBox:~$ Inside Child---- PID :3822 and PID of parent : 686 Inside grandchild process---- PID of parent : 3822 soumyadeep@soumyadeep-VirtualBox:~$
[ { "code": null, "e": 1265, "s": 1062, "text": "In this section we will see how to execute zombie process and orphan process in a single program in C/C++. Before going to the main discussion, let us see what are the zombie process and orphan process." }, { "code": null, "e": 1639, "s": 1265, "text": "A zombie process is a process whose execution is completed but it still has an entry in the process table. Zombie processes usually occur for child processes, as the parent process still needs to read its child’s exit status. Once this is done using the wait system call, the zombie process is eliminated from the process table. This is known as reaping the zombie process." }, { "code": null, "e": 1820, "s": 1639, "text": "Orphan processes are those processes that are still running even though their parent process has terminated or finished. A process can be orphaned intentionally or unintentionally." }, { "code": null, "e": 2025, "s": 1820, "text": "An intentionally orphaned process runs in the background without any manual support. This is usually done to start an indefinitely running service or to complete a long-running job without user attention." }, { "code": null, "e": 2200, "s": 2025, "text": "An unintentionally orphaned process is created when its parent process crashes or terminates. Unintentional orphan processes can be avoided using the process group mechanism." }, { "code": null, "e": 2820, "s": 2200, "text": "Now in the following code we will execute zombie and orphan process simultaneously. Here we have a parent process, it has a child, and this child has another child. If our control inserts into child process, then we will stop the execution for 5 seconds so it can finish up the parent process. Thus the child process become orphan process. After that the grandchild process will be converted into Zombie process. The grandchild finishes execution when its parent (the child of the main process) sleeps for 1 second. Hence the grandchild process does not call terminate, and its entry will be there in the process table." }, { "code": null, "e": 3485, "s": 2820, "text": "#include <stdio.h>\n#include <unistd.h>\nint main() {\n int x = fork(); //create child process\n if (x > 0) //if x is non zero, then it is parent process\n printf(\"Inside Parent---- PID is : %d\\n\", getpid());\n else if (x == 0) { //for chile process x will be 0\n sleep(5); //wait for some times\n x = fork();\n if (x > 0) {\n printf(\"Inside Child---- PID :%d and PID of parent : %d\\n\", getpid(), getppid());\n while(1)\n sleep(1);\n printf(\"Inside Child---- PID of parent : %d\\n\", getppid());\n }else if (x == 0)\n printf(\"Inside grandchild process---- PID of parent : %d\\n\", getppid());\n }\n return 0;\n}" }, { "code": null, "e": 3735, "s": 3485, "text": "soumyadeep@soumyadeep-VirtualBox:~$ ./a.out\nInside Parent---- PID is : 3821\nsoumyadeep@soumyadeep-VirtualBox:~$ Inside Child---- PID :3822 and PID of parent : 686\nInside grandchild process---- PID of parent : 3822\nsoumyadeep@soumyadeep-VirtualBox:~$" } ]
How to Create Browsers Window using HTML and CSS ? - GeeksforGeeks
08 Aug, 2021 The browser window is a tool to view the pages from the internet. It is used to search the content on the internet and get the relevant information from internet.Creating Structure: In this section, we will create a basic site structure and also attach the CDN link of the Font-Awesome for the icons which will be used as a menu icon.CDN links for the Icons from the Font Awesome: <link rel=”stylesheet” href=”https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css”> HTML code: html <!DOCTYPE html><html> <head> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css"></head> <body> <div class="container"> <div class="geeks"> <div class="gfg left"> <i class="fa fa-google" aria-hidden="true">oogle</i> </div> <!-- Google icon from font awesome--> <div class="gfg middle"> <input type="text" value="https://www.geeksforgeeks.org/"> <i class="fa fa-search" aria-hidden="true"></i> </div> <div class="gfg right"> <div style="float:right"> <span class="bar"></span> <span class="bar"></span> <span class="bar"></span> </div> </div> </div> <div class="body"> <h3>GeeksforGeeks</h3> <p>A Computer Science Portal for Geeks</p> </div> </div> </body> </html> Designing Structure: In the previous section, we have created the structure of the basic website where we are going to use as browsers window. In this section, we will design the structure for the browsers window. CSS Code: html <style> * { box-sizing: border-box; } /* Container Design */ .container { border: 2px solid #bdc3c7; border-top-left-radius: 6px; border-top-right-radius: 6px; } .geeks { padding: 10px; background: #f1f1f1; border-top-left-radius: 4px; border-top-right-radius: 4px; } /* Input field design */ input[type=text] { width: 100%; border-radius: 3px; border: none; background-color: white; margin-top: -8px; height: 25px; color: gray; padding: 5px; } .gfg { float: left; } .middle { width: 75%; position: relative; } .left { width: 15%; } .right { width: 10%; } .middle i { position: absolute; left: 430px; top: 2px; color: gray; } .geeks:after { content: ""; display: table; clear: both; } /* Address bar design */ .bar { width: 15px; height: 3px; margin: 3px 0; display: block; background-color: #aaa; } .body { padding: 15px; }</style> Final Solution: This is the final code after combining the above sections. It will the browsers window. html <!DOCTYPE html><html> <head> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css"> <style> * { box-sizing: border-box; } /* Container Design */ .container { border: 2px solid #bdc3c7; border-top-left-radius: 6px; border-top-right-radius: 6px; } .geeks { padding: 10px; background: #f1f1f1; border-top-left-radius: 4px; border-top-right-radius: 4px; } /* Input field design */ input[type=text] { width: 100%; border-radius: 3px; border: none; background-color: white; margin-top: -8px; height: 25px; color: gray; padding: 5px; } .gfg { float: left; } .middle { width: 75%; position: relative; } .left { width: 15%; } .right { width: 10%; } .middle i { position: absolute; left: 430px; top: 2px; color: gray; } .geeks:after { content: ""; display: table; clear: both; } /* Address bar design */ .bar { width: 15px; height: 3px; margin: 3px 0; display: block; background-color: #aaa; } .body { padding: 15px; }</style></head> <body> <div class="container"> <div class="geeks"> <div class="gfg left"> <i class="fa fa-google" aria-hidden="true">oogle</i> </div> <!-- Google icon from font awesome--> <div class="gfg middle"> <input type="text" value="https://www.geeksforgeeks.org/"> <i class="fa fa-search" aria-hidden="true"></i> </div> <div class="gfg right"> <div style="float:right"> <span class="bar"></span> <span class="bar"></span> <span class="bar"></span> </div> </div> </div> <div class="body"> <h3>GeeksforGeeks</h3> <p>A Computer Science Portal for Geeks</p> </div> </div> </body> </html> Output: Supported Browser: Google Chrome Microsoft Edge Firefox Opera Safari Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course. ysachin2314 CSS-Misc HTML-Misc CSS HTML Web Technologies HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Top 10 Projects For Beginners To Practice HTML and CSS Skills How to insert spaces/tabs in text using HTML/CSS? How to update Node.js and NPM to next version ? How to create footer to stay at the bottom of a Web page? Types of CSS (Cascading Style Sheet) Top 10 Projects For Beginners To Practice HTML and CSS Skills How to insert spaces/tabs in text using HTML/CSS? How to Insert Form Data into Database using PHP ? How to update Node.js and NPM to next version ? How to set the default value for an HTML <select> element ?
[ { "code": null, "e": 30274, "s": 30246, "text": "\n08 Aug, 2021" }, { "code": null, "e": 30656, "s": 30274, "text": "The browser window is a tool to view the pages from the internet. It is used to search the content on the internet and get the relevant information from internet.Creating Structure: In this section, we will create a basic site structure and also attach the CDN link of the Font-Awesome for the icons which will be used as a menu icon.CDN links for the Icons from the Font Awesome: " }, { "code": null, "e": 30770, "s": 30656, "text": "<link rel=”stylesheet” href=”https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css”>" }, { "code": null, "e": 30783, "s": 30770, "text": "HTML code: " }, { "code": null, "e": 30788, "s": 30783, "text": "html" }, { "code": "<!DOCTYPE html><html> <head> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\"> <link rel=\"stylesheet\" href=\"https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css\"></head> <body> <div class=\"container\"> <div class=\"geeks\"> <div class=\"gfg left\"> <i class=\"fa fa-google\" aria-hidden=\"true\">oogle</i> </div> <!-- Google icon from font awesome--> <div class=\"gfg middle\"> <input type=\"text\" value=\"https://www.geeksforgeeks.org/\"> <i class=\"fa fa-search\" aria-hidden=\"true\"></i> </div> <div class=\"gfg right\"> <div style=\"float:right\"> <span class=\"bar\"></span> <span class=\"bar\"></span> <span class=\"bar\"></span> </div> </div> </div> <div class=\"body\"> <h3>GeeksforGeeks</h3> <p>A Computer Science Portal for Geeks</p> </div> </div> </body> </html> ", "e": 31946, "s": 30788, "text": null }, { "code": null, "e": 32162, "s": 31946, "text": "Designing Structure: In the previous section, we have created the structure of the basic website where we are going to use as browsers window. In this section, we will design the structure for the browsers window. " }, { "code": null, "e": 32174, "s": 32162, "text": "CSS Code: " }, { "code": null, "e": 32179, "s": 32174, "text": "html" }, { "code": "<style> * { box-sizing: border-box; } /* Container Design */ .container { border: 2px solid #bdc3c7; border-top-left-radius: 6px; border-top-right-radius: 6px; } .geeks { padding: 10px; background: #f1f1f1; border-top-left-radius: 4px; border-top-right-radius: 4px; } /* Input field design */ input[type=text] { width: 100%; border-radius: 3px; border: none; background-color: white; margin-top: -8px; height: 25px; color: gray; padding: 5px; } .gfg { float: left; } .middle { width: 75%; position: relative; } .left { width: 15%; } .right { width: 10%; } .middle i { position: absolute; left: 430px; top: 2px; color: gray; } .geeks:after { content: \"\"; display: table; clear: both; } /* Address bar design */ .bar { width: 15px; height: 3px; margin: 3px 0; display: block; background-color: #aaa; } .body { padding: 15px; }</style>", "e": 33378, "s": 32179, "text": null }, { "code": null, "e": 33484, "s": 33378, "text": "Final Solution: This is the final code after combining the above sections. It will the browsers window. " }, { "code": null, "e": 33489, "s": 33484, "text": "html" }, { "code": "<!DOCTYPE html><html> <head> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\"> <link rel=\"stylesheet\" href=\"https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css\"> <style> * { box-sizing: border-box; } /* Container Design */ .container { border: 2px solid #bdc3c7; border-top-left-radius: 6px; border-top-right-radius: 6px; } .geeks { padding: 10px; background: #f1f1f1; border-top-left-radius: 4px; border-top-right-radius: 4px; } /* Input field design */ input[type=text] { width: 100%; border-radius: 3px; border: none; background-color: white; margin-top: -8px; height: 25px; color: gray; padding: 5px; } .gfg { float: left; } .middle { width: 75%; position: relative; } .left { width: 15%; } .right { width: 10%; } .middle i { position: absolute; left: 430px; top: 2px; color: gray; } .geeks:after { content: \"\"; display: table; clear: both; } /* Address bar design */ .bar { width: 15px; height: 3px; margin: 3px 0; display: block; background-color: #aaa; } .body { padding: 15px; }</style></head> <body> <div class=\"container\"> <div class=\"geeks\"> <div class=\"gfg left\"> <i class=\"fa fa-google\" aria-hidden=\"true\">oogle</i> </div> <!-- Google icon from font awesome--> <div class=\"gfg middle\"> <input type=\"text\" value=\"https://www.geeksforgeeks.org/\"> <i class=\"fa fa-search\" aria-hidden=\"true\"></i> </div> <div class=\"gfg right\"> <div style=\"float:right\"> <span class=\"bar\"></span> <span class=\"bar\"></span> <span class=\"bar\"></span> </div> </div> </div> <div class=\"body\"> <h3>GeeksforGeeks</h3> <p>A Computer Science Portal for Geeks</p> </div> </div> </body> </html>", "e": 35852, "s": 33489, "text": null }, { "code": null, "e": 35862, "s": 35852, "text": "Output: " }, { "code": null, "e": 35881, "s": 35862, "text": "Supported Browser:" }, { "code": null, "e": 35895, "s": 35881, "text": "Google Chrome" }, { "code": null, "e": 35910, "s": 35895, "text": "Microsoft Edge" }, { "code": null, "e": 35918, "s": 35910, "text": "Firefox" }, { "code": null, "e": 35924, "s": 35918, "text": "Opera" }, { "code": null, "e": 35931, "s": 35924, "text": "Safari" }, { "code": null, "e": 36068, "s": 35931, "text": "Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course." }, { "code": null, "e": 36080, "s": 36068, "text": "ysachin2314" }, { "code": null, "e": 36089, "s": 36080, "text": "CSS-Misc" }, { "code": null, "e": 36099, "s": 36089, "text": "HTML-Misc" }, { "code": null, "e": 36103, "s": 36099, "text": "CSS" }, { "code": null, "e": 36108, "s": 36103, "text": "HTML" }, { "code": null, "e": 36125, "s": 36108, "text": "Web Technologies" }, { "code": null, "e": 36130, "s": 36125, "text": "HTML" }, { "code": null, "e": 36228, "s": 36130, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 36237, "s": 36228, "text": "Comments" }, { "code": null, "e": 36250, "s": 36237, "text": "Old Comments" }, { "code": null, "e": 36312, "s": 36250, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 36362, "s": 36312, "text": "How to insert spaces/tabs in text using HTML/CSS?" }, { "code": null, "e": 36410, "s": 36362, "text": "How to update Node.js and NPM to next version ?" }, { "code": null, "e": 36468, "s": 36410, "text": "How to create footer to stay at the bottom of a Web page?" }, { "code": null, "e": 36505, "s": 36468, "text": "Types of CSS (Cascading Style Sheet)" }, { "code": null, "e": 36567, "s": 36505, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 36617, "s": 36567, "text": "How to insert spaces/tabs in text using HTML/CSS?" }, { "code": null, "e": 36667, "s": 36617, "text": "How to Insert Form Data into Database using PHP ?" }, { "code": null, "e": 36715, "s": 36667, "text": "How to update Node.js and NPM to next version ?" } ]
FarmEasy: Crop Recommendation for Farmers made easy | by Darshan Gandhi | Towards Data Science
Please leave a clap if you found this article useful, it helps me a lot! :D In order to mitigate the agrarian crisis in the current status quo, there is a need for better recommendation systems to alleviate the crisis by helping the farmers to make an informed decision before starting the cultivation of crops. The major parameters considered here are: 1. Crop name 2. Sowing Time (Month) 3. Region 4. Temperature - Minimum & Maximum 5. Rainfall - Minimum & Maximum 6. pH value of the Soil 7. Soil Type Step 1: Data Collection This was by far the most important and crucial step during the project building. Since there was no specific dataset available I had to work on building that dataset from scratch and had to choose the parameters accordingly. Additionally, I had several other parameters in mind such as Nitrogen level of Soil, Irrigation Facilities, Crop Rotation Cycle but due to data paucity was not able to take them into account. The data obtained was distributed across different files such as: Soil TypeCash-cropsFlowerFruitGrainHerbsShrubsSpicesTreesVegetablesAverage RainfallAverage Temperature Soil Type Cash-crops Flower Fruit Grain Herbs Shrubs Spices Trees Vegetables Average Rainfall Average Temperature Step 2: Data Transformation The data also had several inconsistencies since it was obtained from several different sources such as : Missing Values Missing Values The missing values had to be removed from the dataset since they would lead to data inconsistencies and eventually to the wrong prediction. 2. Spelling Aberrations The spellings were not consistent throughout the files and had to be normalised to a single value to improve the model accuracy. 3. Redundant Data The redundant data had to be discarded since they would not add any additional significance to the process. The data was eventually coalesced into one dataset to ease the process of model building and computation. Once, the data was collected the data types were checked and changes were made such as changing from String -> Integer where required. Also since a machine learning model works only with numbers, the string values need to be converted into numerical values. For this, I made use of Label Encoder Technique. “Label Encoder is a tool provided by Scikit Learn which helps one to encode the categorical features/variables into their numeric features. The encoder targets variables between 0 to n_classes-1 where n is the number of distinct labels.” More can be learnt about Label Encoding by referring to the official Scikit Learn documentation here. Step 3: Model Building The model used here is: Ensemble Learning Model. Okay first let us understand what ensemble learning is all about! According to Wikipedia ensemble learning is stated follows : “Ensemble Learning approach uses multiple learning algorithms in statistics and machine learning to achieve greater predictive efficiency than either of the constituent learning algorithms alone might obtain.” Here, I have made use of the functionality of Voting Classifier provided by Scikit Learn. from sklearn.ensemble import VotingClassifiermodel=VotingClassifier(estimators=[('rf', random_forest),('gnb',gaussian_naive_bayes),('knn',k_nearest_neighbours), ('dt',decision_tree) ], voting=''hard) As seen in the above code snippet the model was built using algorithms listed below : Random Forest Algorithm Gaussian Naive Bayes Algorithm K-Nearest Neighbours Algorithm Decision Tree Algorithm Voting parameter is set to “hard” here since the model uses predicted class labels for majority rule voting. Step 4: Deployment of the model In order to deploy the trained model for the farmers to use off, we would need an application with a simple user interface which the farmers can utilise. Thus, here I made a simple web interface using HTML, CSS & Bootstrap. The next step was to have a database to store the data for which I made use of : MongoDb Lastly, I wanted to predict the results for the obtained values from the user for which I made use of Flask framework to integrate the backend and the front end. Also,I generated the pickle file for our model to generate the predictions for the input data. Okay, so you would be wondering what is a pickle file? Let’s have a look at it as well. According to the official Python documentation available at docs.python.org : “The pickle module implements binary protocols for serialising and de-serialising a Python object structure. “Pickling” is the process whereby a Python object hierarchy is converted into a byte stream, and “unpickling” is the inverse operation, whereby a byte stream (from a binary file or bytes-like object) is converted back into an object hierarchy.” In simple words, the pickled file converts the trained model into a byte stream and is sent to the website where it is unpickled again where it is used to train the incoming data from the farmers. Login Page for the Farmer The farmer needs to enter their details such as : Name Email Id Password Services offered Prediction Recommendation Information Predict now & Searching a Crop If the farmer would like to search for more information about a specific crop the “Search Crop Section” would be there to the rescue. It helps the farmer with detailed information about the crop for better understanding. “Predict Now Section” The predict now takes in the following parameters for the farmer: Month pH Scale Region Soil Type Additionally, 2 parameters are taken into account from the database itself accordingly to the region mentioned by the farmer Temperature Rainfall After inputting the values, the farmer can click on the “Predict Now” button. The optimum Crop Name is displayed to the farmer for cultivation. RSS News Feed Added the RSS functionality for farmers to get informative news for them to read and be updated! Voice Based Modelling System Additionally, I have tried to implement a question-answer system model where I give a voice input as a question and I get an answer back in voice. The system has been incorporated in the website to ease the process of the farmer for feeding in the application. The farmer just needs to click on the 🎙️ below the input field for talking! Concepts and Libraries used here : iNLTK (Natural Language Tool Kit)- Taking input in the regional language (Hindi in this case) SpeechRecognition- For receiving speech input from the farmer gTTS (Google Text to Speech)- Providing farmer the output via voice Scikit Learn- For making use of NLP libraries I have built a portal for the Farmers in collaboration with my colleague Nipun Iyer which would help them to get assistance regarding crop cultivation strategies, primarily for the services of: prediction, recommendation, information of crops. Thank you for taking the time out and reading this article! 🙂 If you have got any doubts or would love to discuss more and understand about the project, please reach out to me here, would be happy to chat!
[ { "code": null, "e": 248, "s": 172, "text": "Please leave a clap if you found this article useful, it helps me a lot! :D" }, { "code": null, "e": 484, "s": 248, "text": "In order to mitigate the agrarian crisis in the current status quo, there is a need for better recommendation systems to alleviate the crisis by helping the farmers to make an informed decision before starting the cultivation of crops." }, { "code": null, "e": 526, "s": 484, "text": "The major parameters considered here are:" }, { "code": null, "e": 539, "s": 526, "text": "1. Crop name" }, { "code": null, "e": 562, "s": 539, "text": "2. Sowing Time (Month)" }, { "code": null, "e": 572, "s": 562, "text": "3. Region" }, { "code": null, "e": 607, "s": 572, "text": "4. Temperature - Minimum & Maximum" }, { "code": null, "e": 639, "s": 607, "text": "5. Rainfall - Minimum & Maximum" }, { "code": null, "e": 663, "s": 639, "text": "6. pH value of the Soil" }, { "code": null, "e": 676, "s": 663, "text": "7. Soil Type" }, { "code": null, "e": 700, "s": 676, "text": "Step 1: Data Collection" }, { "code": null, "e": 781, "s": 700, "text": "This was by far the most important and crucial step during the project building." }, { "code": null, "e": 1117, "s": 781, "text": "Since there was no specific dataset available I had to work on building that dataset from scratch and had to choose the parameters accordingly. Additionally, I had several other parameters in mind such as Nitrogen level of Soil, Irrigation Facilities, Crop Rotation Cycle but due to data paucity was not able to take them into account." }, { "code": null, "e": 1183, "s": 1117, "text": "The data obtained was distributed across different files such as:" }, { "code": null, "e": 1286, "s": 1183, "text": "Soil TypeCash-cropsFlowerFruitGrainHerbsShrubsSpicesTreesVegetablesAverage RainfallAverage Temperature" }, { "code": null, "e": 1296, "s": 1286, "text": "Soil Type" }, { "code": null, "e": 1307, "s": 1296, "text": "Cash-crops" }, { "code": null, "e": 1314, "s": 1307, "text": "Flower" }, { "code": null, "e": 1320, "s": 1314, "text": "Fruit" }, { "code": null, "e": 1326, "s": 1320, "text": "Grain" }, { "code": null, "e": 1332, "s": 1326, "text": "Herbs" }, { "code": null, "e": 1339, "s": 1332, "text": "Shrubs" }, { "code": null, "e": 1346, "s": 1339, "text": "Spices" }, { "code": null, "e": 1352, "s": 1346, "text": "Trees" }, { "code": null, "e": 1363, "s": 1352, "text": "Vegetables" }, { "code": null, "e": 1380, "s": 1363, "text": "Average Rainfall" }, { "code": null, "e": 1400, "s": 1380, "text": "Average Temperature" }, { "code": null, "e": 1428, "s": 1400, "text": "Step 2: Data Transformation" }, { "code": null, "e": 1533, "s": 1428, "text": "The data also had several inconsistencies since it was obtained from several different sources such as :" }, { "code": null, "e": 1548, "s": 1533, "text": "Missing Values" }, { "code": null, "e": 1563, "s": 1548, "text": "Missing Values" }, { "code": null, "e": 1703, "s": 1563, "text": "The missing values had to be removed from the dataset since they would lead to data inconsistencies and eventually to the wrong prediction." }, { "code": null, "e": 1727, "s": 1703, "text": "2. Spelling Aberrations" }, { "code": null, "e": 1856, "s": 1727, "text": "The spellings were not consistent throughout the files and had to be normalised to a single value to improve the model accuracy." }, { "code": null, "e": 1874, "s": 1856, "text": "3. Redundant Data" }, { "code": null, "e": 1982, "s": 1874, "text": "The redundant data had to be discarded since they would not add any additional significance to the process." }, { "code": null, "e": 2088, "s": 1982, "text": "The data was eventually coalesced into one dataset to ease the process of model building and computation." }, { "code": null, "e": 2223, "s": 2088, "text": "Once, the data was collected the data types were checked and changes were made such as changing from String -> Integer where required." }, { "code": null, "e": 2395, "s": 2223, "text": "Also since a machine learning model works only with numbers, the string values need to be converted into numerical values. For this, I made use of Label Encoder Technique." }, { "code": null, "e": 2633, "s": 2395, "text": "“Label Encoder is a tool provided by Scikit Learn which helps one to encode the categorical features/variables into their numeric features. The encoder targets variables between 0 to n_classes-1 where n is the number of distinct labels.”" }, { "code": null, "e": 2735, "s": 2633, "text": "More can be learnt about Label Encoding by referring to the official Scikit Learn documentation here." }, { "code": null, "e": 2758, "s": 2735, "text": "Step 3: Model Building" }, { "code": null, "e": 2807, "s": 2758, "text": "The model used here is: Ensemble Learning Model." }, { "code": null, "e": 2873, "s": 2807, "text": "Okay first let us understand what ensemble learning is all about!" }, { "code": null, "e": 2934, "s": 2873, "text": "According to Wikipedia ensemble learning is stated follows :" }, { "code": null, "e": 3144, "s": 2934, "text": "“Ensemble Learning approach uses multiple learning algorithms in statistics and machine learning to achieve greater predictive efficiency than either of the constituent learning algorithms alone might obtain.”" }, { "code": null, "e": 3234, "s": 3144, "text": "Here, I have made use of the functionality of Voting Classifier provided by Scikit Learn." }, { "code": null, "e": 3435, "s": 3234, "text": "from sklearn.ensemble import VotingClassifiermodel=VotingClassifier(estimators=[('rf', random_forest),('gnb',gaussian_naive_bayes),('knn',k_nearest_neighbours), ('dt',decision_tree) ], voting=''hard)" }, { "code": null, "e": 3521, "s": 3435, "text": "As seen in the above code snippet the model was built using algorithms listed below :" }, { "code": null, "e": 3545, "s": 3521, "text": "Random Forest Algorithm" }, { "code": null, "e": 3576, "s": 3545, "text": "Gaussian Naive Bayes Algorithm" }, { "code": null, "e": 3607, "s": 3576, "text": "K-Nearest Neighbours Algorithm" }, { "code": null, "e": 3631, "s": 3607, "text": "Decision Tree Algorithm" }, { "code": null, "e": 3740, "s": 3631, "text": "Voting parameter is set to “hard” here since the model uses predicted class labels for majority rule voting." }, { "code": null, "e": 3772, "s": 3740, "text": "Step 4: Deployment of the model" }, { "code": null, "e": 3926, "s": 3772, "text": "In order to deploy the trained model for the farmers to use off, we would need an application with a simple user interface which the farmers can utilise." }, { "code": null, "e": 3996, "s": 3926, "text": "Thus, here I made a simple web interface using HTML, CSS & Bootstrap." }, { "code": null, "e": 4085, "s": 3996, "text": "The next step was to have a database to store the data for which I made use of : MongoDb" }, { "code": null, "e": 4430, "s": 4085, "text": "Lastly, I wanted to predict the results for the obtained values from the user for which I made use of Flask framework to integrate the backend and the front end. Also,I generated the pickle file for our model to generate the predictions for the input data. Okay, so you would be wondering what is a pickle file? Let’s have a look at it as well." }, { "code": null, "e": 4508, "s": 4430, "text": "According to the official Python documentation available at docs.python.org :" }, { "code": null, "e": 4862, "s": 4508, "text": "“The pickle module implements binary protocols for serialising and de-serialising a Python object structure. “Pickling” is the process whereby a Python object hierarchy is converted into a byte stream, and “unpickling” is the inverse operation, whereby a byte stream (from a binary file or bytes-like object) is converted back into an object hierarchy.”" }, { "code": null, "e": 5059, "s": 4862, "text": "In simple words, the pickled file converts the trained model into a byte stream and is sent to the website where it is unpickled again where it is used to train the incoming data from the farmers." }, { "code": null, "e": 5085, "s": 5059, "text": "Login Page for the Farmer" }, { "code": null, "e": 5135, "s": 5085, "text": "The farmer needs to enter their details such as :" }, { "code": null, "e": 5140, "s": 5135, "text": "Name" }, { "code": null, "e": 5149, "s": 5140, "text": "Email Id" }, { "code": null, "e": 5158, "s": 5149, "text": "Password" }, { "code": null, "e": 5175, "s": 5158, "text": "Services offered" }, { "code": null, "e": 5186, "s": 5175, "text": "Prediction" }, { "code": null, "e": 5201, "s": 5186, "text": "Recommendation" }, { "code": null, "e": 5213, "s": 5201, "text": "Information" }, { "code": null, "e": 5244, "s": 5213, "text": "Predict now & Searching a Crop" }, { "code": null, "e": 5378, "s": 5244, "text": "If the farmer would like to search for more information about a specific crop the “Search Crop Section” would be there to the rescue." }, { "code": null, "e": 5465, "s": 5378, "text": "It helps the farmer with detailed information about the crop for better understanding." }, { "code": null, "e": 5487, "s": 5465, "text": "“Predict Now Section”" }, { "code": null, "e": 5553, "s": 5487, "text": "The predict now takes in the following parameters for the farmer:" }, { "code": null, "e": 5559, "s": 5553, "text": "Month" }, { "code": null, "e": 5568, "s": 5559, "text": "pH Scale" }, { "code": null, "e": 5575, "s": 5568, "text": "Region" }, { "code": null, "e": 5585, "s": 5575, "text": "Soil Type" }, { "code": null, "e": 5710, "s": 5585, "text": "Additionally, 2 parameters are taken into account from the database itself accordingly to the region mentioned by the farmer" }, { "code": null, "e": 5722, "s": 5710, "text": "Temperature" }, { "code": null, "e": 5731, "s": 5722, "text": "Rainfall" }, { "code": null, "e": 5809, "s": 5731, "text": "After inputting the values, the farmer can click on the “Predict Now” button." }, { "code": null, "e": 5875, "s": 5809, "text": "The optimum Crop Name is displayed to the farmer for cultivation." }, { "code": null, "e": 5889, "s": 5875, "text": "RSS News Feed" }, { "code": null, "e": 5986, "s": 5889, "text": "Added the RSS functionality for farmers to get informative news for them to read and be updated!" }, { "code": null, "e": 6015, "s": 5986, "text": "Voice Based Modelling System" }, { "code": null, "e": 6162, "s": 6015, "text": "Additionally, I have tried to implement a question-answer system model where I give a voice input as a question and I get an answer back in voice." }, { "code": null, "e": 6352, "s": 6162, "text": "The system has been incorporated in the website to ease the process of the farmer for feeding in the application. The farmer just needs to click on the 🎙️ below the input field for talking!" }, { "code": null, "e": 6387, "s": 6352, "text": "Concepts and Libraries used here :" }, { "code": null, "e": 6481, "s": 6387, "text": "iNLTK (Natural Language Tool Kit)- Taking input in the regional language (Hindi in this case)" }, { "code": null, "e": 6543, "s": 6481, "text": "SpeechRecognition- For receiving speech input from the farmer" }, { "code": null, "e": 6611, "s": 6543, "text": "gTTS (Google Text to Speech)- Providing farmer the output via voice" }, { "code": null, "e": 6657, "s": 6611, "text": "Scikit Learn- For making use of NLP libraries" }, { "code": null, "e": 6901, "s": 6657, "text": "I have built a portal for the Farmers in collaboration with my colleague Nipun Iyer which would help them to get assistance regarding crop cultivation strategies, primarily for the services of: prediction, recommendation, information of crops." }, { "code": null, "e": 6963, "s": 6901, "text": "Thank you for taking the time out and reading this article! 🙂" } ]
Get faster pandas with Modin, even on your laptops. | by Parul Pandey | Towards Data Science
Scale your pandas workflows by changing one line of code Pandas is a library which needs no introduction in the field of data science. It provides high-performance, easy-to-use data structures and data analysis tools. However, when working with excessively large amounts of data, Pandas on a single core becomes insufficient and people have to resort to different distributed systems to increase their performance. The tradeoff for improved performance, however, comes with a steep learning curve. Essentially users probably just want Pandas to run faster and aren’t looking to optimize their workflows for their particular hardware setup. This means people want to use the same Pandas script for their 10KB dataset as their 10TB dataset. Modin offers to provide a solution by optimizing pandas so that Data Scientists spend their time extracting value from their data than on tools that extract data. Modin is an early-stage project at UC Berkeley’s RISELab designed to facilitate the use of distributed computing for Data Science. It is a multiprocess Dataframe library with an identical API to pandas that allows users to speed up their Pandas workflows. Modin accelerates Pandas queries by 4x on an 8-core machine, only requiring users to change a single line of code in their notebooks. The system has been designed for existing Pandas users who would like their programs to run faster and scale better without significant code changes. The ultimate goal of this work is to be able to use Pandas in a cloud setting. Modin is completely open-source and can be found on GitHub: https://github.com/modin-project/modin Modin can be installed from PyPI: pip install modin For Windows, one of the dependencies is Ray. Ray is not yet supported natively on Windows, so in order to install it, one needs to use the WSL(Windows Subsystem for Linux). Consider a 4 core modern laptop with a dataframe that fits comfortably in it. While pandas use only one of the CPUs core, modin, on the other hand, uses all of them. Essentially what modin does is that it simply increases the utilisation of all cores of the CPU thereby giving a better performance. On large machine usefulness of modin becomes much more pronounced. Let’s pretend there is some server or some pretty powerful machine. So pandas will still utilise a single core and again modin will use all of them. Here is a performance comparison of read_csv with pandas and modin on a 144 core computer. There is a nice linear scaling in pandas but that’s because it’s still only using one core. It may be hard to see the green bars because they’re so low in modin. Typically 2 gigabytes takes about 2 seconds and 18 gigabytes take approximately less than 18 seconds. Let’s have a look into the architecture of Modin. The partitioning schema partitions along both columns and rows because it gives Modin flexibility and scalability in both the number of columns and the number of rows supported. Modin is separated into different layers.: Pandas API is exposed at the topmost layer Next layer houses the Query Compiler which receives queries from the pandas API layer and performs certain optimizations. At the last layer is the Partition Manager and is responsible for the data layout and shuffling, partitioning, and serializing the tasks that get sent to each partition. The pandas API is massive and that is a reason probably why it has such a wide range of use cases. With such a lot of operations at hand, modin followed a data-driven approach. This means the creators of modin took a look at what people mostly use in pandas. They went to Kaggle and did a massive scrape of all the notebooks and scripts present there and ultimately figured out the most popular pandas’ methods which are as follows: pd.read_CSV is by far the most used method in pandas followed by, pd.Dataframe.Therefore, at modin, they started implementing things and optimizing them in the order of their popularity: Currently, modin supports about 71% of the pandas API. This represents about 93% of usage based on the study. Modin uses Ray to provide an effortless way to speed up the pandas’ notebooks, scripts, and libraries. Ray is a high-performance distributed execution framework targeted at large-scale machine learning and reinforcement learning applications. The same code can be run on a single machine to achieve efficient multiprocessing, and it can be used on a cluster for large computations. You can find Ray on GitHub: github.com/ray-project/ray. Modin wraps pandas and transparently distributes the data and computation, accelerating the pandas’ workflows with one line of code change. Users continue to use previous pandas notebooks while experiencing a considerable speedup from Modin, even on a single machine. Only a modification of the import statement is needed, wherein one needs to import modin.pandas rather than simple pandas. import numpy as npimport modin.pandas as pd Let’s build a toy dataset using Numpy consisting of random integers. Notice, we don’t have to specify partitioning here. ata = np.random.randint(0,100,size = (2**16, 2**4))df = pd.DataFrame(data)df = df.add_prefix("Col:") When we print out the type, it is a Modin dataframe. type(df)modin.pandas.dataframe.DataFrame if we were to print out the first 5 lines with the head command, it renders an HTML table just like pandas would. df.head() Modin manages the data partitioning and shuffling so that users can focus on extracting value from the data. The following code was run on a 2013 4-core iMac with 32GB RAM. read_csv is by far the most used pandas’ operation. Let’s do a quick comparison when we use read_csv in pandas vs modin. pandas %%timeimport pandas pandas_csv_data = pandas.read_csv("../800MB.csv")-----------------------------------------------------------------CPU times: user 26.3 s, sys: 3.14 s, total: 29.4sWall time: 29.5 s Modin %%timemodin_csv_data = pd.read_csv("../800MB.csv")-----------------------------------------------------------------CPU times: user 76.7 ms, sys: 5.08 ms, total: 81.8 msWall time: 7.6 s With Modin, read_csv performs up to 4x faster on a 4-core machine just by changing the import statement pandas groupby is extremely well written and is extremely fast. But even with that, modin outperforms pandas. pandas %%timeimport pandas_ = pandas_csv_data.groupby(by=pandas_csv_data.col_1).sum()-----------------------------------------------------------------CPU times: user 5.98 s, sys: 1.77 s, total: 7.75 sWall time: 7.74 s modin %%timeresults = modin_csv_data.groupby(by=modin_csv_data.col_1).sum()-----------------------------------------------------------------CPU times: user 3.18 s, sys: 42.2 ms, total: 3.23 sWall time: 7.3 s In case one wants to use a pandas API that hasn’t been yet implemented or optimized, one can actually default to pandas. This makes the system usable for notebooks that use operations not yet implemented in Modin even though there will be a drop in performance as it will use the pandas API now. When defaulting to pandas, you will see a warning: dot_df = df.dot(df.T) It returns a distributed Modin DataFrame once the computation is complete. type(dot_df)-----------------modin.pandas.dataframe.DataFrame Modin is still in its early stages and appears to be a very promising add on to the pandas. Modin handles all the partitioning and shuffling for the user so that we can essentially focus on our workflows. Modin’s basic goal is to enable the users to use the same tools on small data as well as big data without having to worry about changing the API to suit different data sizes. Edit: Since the publishing of this article a lot of people have been asking me how is Modin different from Dask in terms of its offers. Here is a detailed comparison by the author:
[ { "code": null, "e": 229, "s": 172, "text": "Scale your pandas workflows by changing one line of code" }, { "code": null, "e": 1074, "s": 229, "text": "Pandas is a library which needs no introduction in the field of data science. It provides high-performance, easy-to-use data structures and data analysis tools. However, when working with excessively large amounts of data, Pandas on a single core becomes insufficient and people have to resort to different distributed systems to increase their performance. The tradeoff for improved performance, however, comes with a steep learning curve. Essentially users probably just want Pandas to run faster and aren’t looking to optimize their workflows for their particular hardware setup. This means people want to use the same Pandas script for their 10KB dataset as their 10TB dataset. Modin offers to provide a solution by optimizing pandas so that Data Scientists spend their time extracting value from their data than on tools that extract data." }, { "code": null, "e": 1330, "s": 1074, "text": "Modin is an early-stage project at UC Berkeley’s RISELab designed to facilitate the use of distributed computing for Data Science. It is a multiprocess Dataframe library with an identical API to pandas that allows users to speed up their Pandas workflows." }, { "code": null, "e": 1693, "s": 1330, "text": "Modin accelerates Pandas queries by 4x on an 8-core machine, only requiring users to change a single line of code in their notebooks. The system has been designed for existing Pandas users who would like their programs to run faster and scale better without significant code changes. The ultimate goal of this work is to be able to use Pandas in a cloud setting." }, { "code": null, "e": 1792, "s": 1693, "text": "Modin is completely open-source and can be found on GitHub: https://github.com/modin-project/modin" }, { "code": null, "e": 1826, "s": 1792, "text": "Modin can be installed from PyPI:" }, { "code": null, "e": 1844, "s": 1826, "text": "pip install modin" }, { "code": null, "e": 2017, "s": 1844, "text": "For Windows, one of the dependencies is Ray. Ray is not yet supported natively on Windows, so in order to install it, one needs to use the WSL(Windows Subsystem for Linux)." }, { "code": null, "e": 2183, "s": 2017, "text": "Consider a 4 core modern laptop with a dataframe that fits comfortably in it. While pandas use only one of the CPUs core, modin, on the other hand, uses all of them." }, { "code": null, "e": 2316, "s": 2183, "text": "Essentially what modin does is that it simply increases the utilisation of all cores of the CPU thereby giving a better performance." }, { "code": null, "e": 2623, "s": 2316, "text": "On large machine usefulness of modin becomes much more pronounced. Let’s pretend there is some server or some pretty powerful machine. So pandas will still utilise a single core and again modin will use all of them. Here is a performance comparison of read_csv with pandas and modin on a 144 core computer." }, { "code": null, "e": 2785, "s": 2623, "text": "There is a nice linear scaling in pandas but that’s because it’s still only using one core. It may be hard to see the green bars because they’re so low in modin." }, { "code": null, "e": 2887, "s": 2785, "text": "Typically 2 gigabytes takes about 2 seconds and 18 gigabytes take approximately less than 18 seconds." }, { "code": null, "e": 2937, "s": 2887, "text": "Let’s have a look into the architecture of Modin." }, { "code": null, "e": 3115, "s": 2937, "text": "The partitioning schema partitions along both columns and rows because it gives Modin flexibility and scalability in both the number of columns and the number of rows supported." }, { "code": null, "e": 3158, "s": 3115, "text": "Modin is separated into different layers.:" }, { "code": null, "e": 3201, "s": 3158, "text": "Pandas API is exposed at the topmost layer" }, { "code": null, "e": 3323, "s": 3201, "text": "Next layer houses the Query Compiler which receives queries from the pandas API layer and performs certain optimizations." }, { "code": null, "e": 3493, "s": 3323, "text": "At the last layer is the Partition Manager and is responsible for the data layout and shuffling, partitioning, and serializing the tasks that get sent to each partition." }, { "code": null, "e": 3592, "s": 3493, "text": "The pandas API is massive and that is a reason probably why it has such a wide range of use cases." }, { "code": null, "e": 3926, "s": 3592, "text": "With such a lot of operations at hand, modin followed a data-driven approach. This means the creators of modin took a look at what people mostly use in pandas. They went to Kaggle and did a massive scrape of all the notebooks and scripts present there and ultimately figured out the most popular pandas’ methods which are as follows:" }, { "code": null, "e": 4113, "s": 3926, "text": "pd.read_CSV is by far the most used method in pandas followed by, pd.Dataframe.Therefore, at modin, they started implementing things and optimizing them in the order of their popularity:" }, { "code": null, "e": 4168, "s": 4113, "text": "Currently, modin supports about 71% of the pandas API." }, { "code": null, "e": 4223, "s": 4168, "text": "This represents about 93% of usage based on the study." }, { "code": null, "e": 4661, "s": 4223, "text": "Modin uses Ray to provide an effortless way to speed up the pandas’ notebooks, scripts, and libraries. Ray is a high-performance distributed execution framework targeted at large-scale machine learning and reinforcement learning applications. The same code can be run on a single machine to achieve efficient multiprocessing, and it can be used on a cluster for large computations. You can find Ray on GitHub: github.com/ray-project/ray." }, { "code": null, "e": 5052, "s": 4661, "text": "Modin wraps pandas and transparently distributes the data and computation, accelerating the pandas’ workflows with one line of code change. Users continue to use previous pandas notebooks while experiencing a considerable speedup from Modin, even on a single machine. Only a modification of the import statement is needed, wherein one needs to import modin.pandas rather than simple pandas." }, { "code": null, "e": 5096, "s": 5052, "text": "import numpy as npimport modin.pandas as pd" }, { "code": null, "e": 5217, "s": 5096, "text": "Let’s build a toy dataset using Numpy consisting of random integers. Notice, we don’t have to specify partitioning here." }, { "code": null, "e": 5318, "s": 5217, "text": "ata = np.random.randint(0,100,size = (2**16, 2**4))df = pd.DataFrame(data)df = df.add_prefix(\"Col:\")" }, { "code": null, "e": 5371, "s": 5318, "text": "When we print out the type, it is a Modin dataframe." }, { "code": null, "e": 5412, "s": 5371, "text": "type(df)modin.pandas.dataframe.DataFrame" }, { "code": null, "e": 5526, "s": 5412, "text": "if we were to print out the first 5 lines with the head command, it renders an HTML table just like pandas would." }, { "code": null, "e": 5536, "s": 5526, "text": "df.head()" }, { "code": null, "e": 5709, "s": 5536, "text": "Modin manages the data partitioning and shuffling so that users can focus on extracting value from the data. The following code was run on a 2013 4-core iMac with 32GB RAM." }, { "code": null, "e": 5830, "s": 5709, "text": "read_csv is by far the most used pandas’ operation. Let’s do a quick comparison when we use read_csv in pandas vs modin." }, { "code": null, "e": 5837, "s": 5830, "text": "pandas" }, { "code": null, "e": 6038, "s": 5837, "text": "%%timeimport pandas pandas_csv_data = pandas.read_csv(\"../800MB.csv\")-----------------------------------------------------------------CPU times: user 26.3 s, sys: 3.14 s, total: 29.4sWall time: 29.5 s" }, { "code": null, "e": 6044, "s": 6038, "text": "Modin" }, { "code": null, "e": 6229, "s": 6044, "text": "%%timemodin_csv_data = pd.read_csv(\"../800MB.csv\")-----------------------------------------------------------------CPU times: user 76.7 ms, sys: 5.08 ms, total: 81.8 msWall time: 7.6 s" }, { "code": null, "e": 6333, "s": 6229, "text": "With Modin, read_csv performs up to 4x faster on a 4-core machine just by changing the import statement" }, { "code": null, "e": 6443, "s": 6333, "text": "pandas groupby is extremely well written and is extremely fast. But even with that, modin outperforms pandas." }, { "code": null, "e": 6450, "s": 6443, "text": "pandas" }, { "code": null, "e": 6661, "s": 6450, "text": "%%timeimport pandas_ = pandas_csv_data.groupby(by=pandas_csv_data.col_1).sum()-----------------------------------------------------------------CPU times: user 5.98 s, sys: 1.77 s, total: 7.75 sWall time: 7.74 s" }, { "code": null, "e": 6667, "s": 6661, "text": "modin" }, { "code": null, "e": 6869, "s": 6667, "text": "%%timeresults = modin_csv_data.groupby(by=modin_csv_data.col_1).sum()-----------------------------------------------------------------CPU times: user 3.18 s, sys: 42.2 ms, total: 3.23 sWall time: 7.3 s" }, { "code": null, "e": 7216, "s": 6869, "text": "In case one wants to use a pandas API that hasn’t been yet implemented or optimized, one can actually default to pandas. This makes the system usable for notebooks that use operations not yet implemented in Modin even though there will be a drop in performance as it will use the pandas API now. When defaulting to pandas, you will see a warning:" }, { "code": null, "e": 7238, "s": 7216, "text": "dot_df = df.dot(df.T)" }, { "code": null, "e": 7313, "s": 7238, "text": "It returns a distributed Modin DataFrame once the computation is complete." }, { "code": null, "e": 7375, "s": 7313, "text": "type(dot_df)-----------------modin.pandas.dataframe.DataFrame" }, { "code": null, "e": 7755, "s": 7375, "text": "Modin is still in its early stages and appears to be a very promising add on to the pandas. Modin handles all the partitioning and shuffling for the user so that we can essentially focus on our workflows. Modin’s basic goal is to enable the users to use the same tools on small data as well as big data without having to worry about changing the API to suit different data sizes." } ]
Difference between window.location.href, window.location.replace and window.location.assign in JavaScript - GeeksforGeeks
30 Jun, 2021 Window.location is a property that returns a Location object with information about the document’s current location. This Location object represents the location (URL) of the object it is linked to i.e. holds all the information about the current document location (host, href, port, protocol, etc.) All three commands are used to redirect the page to another page/website but differ in terms of their impact on the browser history. window.location.href Property: The href property on the location object stores the URL of the current webpage. On changing the href property, a user can navigate to a new URL, i.e. go to a new webpage. It adds an item to the history list (so that when the user clicks the “Back” button, he/she can return to the current page). Updating the href property is considered to be faster than using the assign() function (as calling a function is slower than accessing the property). Syntax: window.location.href = 'https://www.geeksforgeeks.org'; Example: HTML <!DOCTYPE html><html> <body> <button onclick="getCurrentLocation()"> Get URL </button> <button onclick="setCurrentLocation()"> Change URL </button> <script> function getCurrentLocation() { // Get current location var loc = window.location.href; alert(loc); } function setCurrentLocation() { // Change current location var newloc = "https://www.geeksforgeeks.org/"; window.location.href = newloc; } </script></body> </html> Output: Note: The following 2 lines of code perform the same purpose. Javascript // Less favouredwindow.location = 'https://www.geeksforgeeks.org' // More favouredwindow.location.href = 'https://www.geeksforgeeks.org' window.location.replace Property: The replace function is used to navigate to a new URL without adding a new record to the history. As the name suggests, this function “replaces” the topmost entry from the history stack, i.e., removes the topmost entry from the history list, by overwriting it with a new entry. So, when the user clicks the “Back” button, he/she will not be able to return to the current page. Hence, the major difference between the assign() and replace() methods is that the replace() function will delete the current page from the session history. The replace function does not wipe out the entire page history, nor does it make the “Back” button non-functional. Syntax: window.location.replace("https://geeksforgeeks.org/web-development/") Example: HTML <!DOCTYPE html><html> <body> <button onclick="replaceLocation()"> Replace current webpage </button> <script> function replaceLocation() { // Replace the current location // with new location var newloc = "https://www.geeksforgeeks.org/"; window.location.replace(newloc); } </script></body> </html> Output: window.location.assign Property: The assign function is similar to the href property as it is also used to navigate to a new URL. The assign method, however, does not show the current location, it is only used to go to a new location. Unlike the replace method, the assign method adds a new record to history (so that when the user clicks the “Back” button, he/she can return to the current page). However, rather than updating the href property, calling a function is considered safer and more readable. The assign() method is also preferred over href as it allows the user to mock the function and check the URL input parameters while testing. Syntax: window.location.assign("https://geeksforgeeks.org/") Example: HTML <!DOCTYPE html><html> <body> <button onclick="assignLocation()"> Go to new webpage </button> <script> function assignLocation() { // Go to another webpage (geeksforgeeks) var newloc = "https://www.geeksforgeeks.org/"; window.location.assign(newloc); } </script></body> </html> Output: Difference between window.location.replace, window.location.assign and window.location.href properties: JavaScript-Properties JavaScript-Questions Picked Difference Between JavaScript Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Difference Between Method Overloading and Method Overriding in Java Comparison between Adjacency List and Adjacency Matrix representation of Graph Difference between Synchronous and Asynchronous Transmission Difference between LAN, MAN and WAN Difference between Prim's and Kruskal's algorithm for MST Convert a string to an integer in JavaScript Hide or show elements in HTML using display property How to calculate the number of days between two dates in javascript? Differences between Functional Components and Class Components in React How to Open URL in New Tab using JavaScript ?
[ { "code": null, "e": 24469, "s": 24441, "text": "\n30 Jun, 2021" }, { "code": null, "e": 24769, "s": 24469, "text": "Window.location is a property that returns a Location object with information about the document’s current location. This Location object represents the location (URL) of the object it is linked to i.e. holds all the information about the current document location (host, href, port, protocol, etc.)" }, { "code": null, "e": 24902, "s": 24769, "text": "All three commands are used to redirect the page to another page/website but differ in terms of their impact on the browser history." }, { "code": null, "e": 24933, "s": 24902, "text": "window.location.href Property:" }, { "code": null, "e": 25013, "s": 24933, "text": "The href property on the location object stores the URL of the current webpage." }, { "code": null, "e": 25104, "s": 25013, "text": "On changing the href property, a user can navigate to a new URL, i.e. go to a new webpage." }, { "code": null, "e": 25229, "s": 25104, "text": "It adds an item to the history list (so that when the user clicks the “Back” button, he/she can return to the current page)." }, { "code": null, "e": 25379, "s": 25229, "text": "Updating the href property is considered to be faster than using the assign() function (as calling a function is slower than accessing the property)." }, { "code": null, "e": 25387, "s": 25379, "text": "Syntax:" }, { "code": null, "e": 25443, "s": 25387, "text": "window.location.href = 'https://www.geeksforgeeks.org';" }, { "code": null, "e": 25454, "s": 25445, "text": "Example:" }, { "code": null, "e": 25459, "s": 25454, "text": "HTML" }, { "code": "<!DOCTYPE html><html> <body> <button onclick=\"getCurrentLocation()\"> Get URL </button> <button onclick=\"setCurrentLocation()\"> Change URL </button> <script> function getCurrentLocation() { // Get current location var loc = window.location.href; alert(loc); } function setCurrentLocation() { // Change current location var newloc = \"https://www.geeksforgeeks.org/\"; window.location.href = newloc; } </script></body> </html>", "e": 26016, "s": 25459, "text": null }, { "code": null, "e": 26024, "s": 26016, "text": "Output:" }, { "code": null, "e": 26086, "s": 26024, "text": "Note: The following 2 lines of code perform the same purpose." }, { "code": null, "e": 26097, "s": 26086, "text": "Javascript" }, { "code": "// Less favouredwindow.location = 'https://www.geeksforgeeks.org' // More favouredwindow.location.href = 'https://www.geeksforgeeks.org' ", "e": 26237, "s": 26097, "text": null }, { "code": null, "e": 26271, "s": 26237, "text": "window.location.replace Property:" }, { "code": null, "e": 26369, "s": 26271, "text": "The replace function is used to navigate to a new URL without adding a new record to the history." }, { "code": null, "e": 26550, "s": 26369, "text": "As the name suggests, this function “replaces” the topmost entry from the history stack, i.e., removes the topmost entry from the history list, by overwriting it with a new entry." }, { "code": null, "e": 26649, "s": 26550, "text": "So, when the user clicks the “Back” button, he/she will not be able to return to the current page." }, { "code": null, "e": 26806, "s": 26649, "text": "Hence, the major difference between the assign() and replace() methods is that the replace() function will delete the current page from the session history." }, { "code": null, "e": 26921, "s": 26806, "text": "The replace function does not wipe out the entire page history, nor does it make the “Back” button non-functional." }, { "code": null, "e": 26929, "s": 26921, "text": "Syntax:" }, { "code": null, "e": 26999, "s": 26929, "text": "window.location.replace(\"https://geeksforgeeks.org/web-development/\")" }, { "code": null, "e": 27010, "s": 27001, "text": "Example:" }, { "code": null, "e": 27015, "s": 27010, "text": "HTML" }, { "code": "<!DOCTYPE html><html> <body> <button onclick=\"replaceLocation()\"> Replace current webpage </button> <script> function replaceLocation() { // Replace the current location // with new location var newloc = \"https://www.geeksforgeeks.org/\"; window.location.replace(newloc); } </script></body> </html>", "e": 27394, "s": 27015, "text": null }, { "code": null, "e": 27402, "s": 27394, "text": "Output:" }, { "code": null, "e": 27435, "s": 27402, "text": "window.location.assign Property:" }, { "code": null, "e": 27532, "s": 27435, "text": "The assign function is similar to the href property as it is also used to navigate to a new URL." }, { "code": null, "e": 27637, "s": 27532, "text": "The assign method, however, does not show the current location, it is only used to go to a new location." }, { "code": null, "e": 27800, "s": 27637, "text": "Unlike the replace method, the assign method adds a new record to history (so that when the user clicks the “Back” button, he/she can return to the current page)." }, { "code": null, "e": 27907, "s": 27800, "text": "However, rather than updating the href property, calling a function is considered safer and more readable." }, { "code": null, "e": 28048, "s": 27907, "text": "The assign() method is also preferred over href as it allows the user to mock the function and check the URL input parameters while testing." }, { "code": null, "e": 28056, "s": 28048, "text": "Syntax:" }, { "code": null, "e": 28109, "s": 28056, "text": "window.location.assign(\"https://geeksforgeeks.org/\")" }, { "code": null, "e": 28118, "s": 28109, "text": "Example:" }, { "code": null, "e": 28123, "s": 28118, "text": "HTML" }, { "code": "<!DOCTYPE html><html> <body> <button onclick=\"assignLocation()\"> Go to new webpage </button> <script> function assignLocation() { // Go to another webpage (geeksforgeeks) var newloc = \"https://www.geeksforgeeks.org/\"; window.location.assign(newloc); } </script></body> </html>", "e": 28476, "s": 28123, "text": null }, { "code": null, "e": 28484, "s": 28476, "text": "Output:" }, { "code": null, "e": 28588, "s": 28484, "text": "Difference between window.location.replace, window.location.assign and window.location.href properties:" }, { "code": null, "e": 28610, "s": 28588, "text": "JavaScript-Properties" }, { "code": null, "e": 28631, "s": 28610, "text": "JavaScript-Questions" }, { "code": null, "e": 28638, "s": 28631, "text": "Picked" }, { "code": null, "e": 28657, "s": 28638, "text": "Difference Between" }, { "code": null, "e": 28668, "s": 28657, "text": "JavaScript" }, { "code": null, "e": 28685, "s": 28668, "text": "Web Technologies" }, { "code": null, "e": 28783, "s": 28685, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28792, "s": 28783, "text": "Comments" }, { "code": null, "e": 28805, "s": 28792, "text": "Old Comments" }, { "code": null, "e": 28873, "s": 28805, "text": "Difference Between Method Overloading and Method Overriding in Java" }, { "code": null, "e": 28952, "s": 28873, "text": "Comparison between Adjacency List and Adjacency Matrix representation of Graph" }, { "code": null, "e": 29013, "s": 28952, "text": "Difference between Synchronous and Asynchronous Transmission" }, { "code": null, "e": 29049, "s": 29013, "text": "Difference between LAN, MAN and WAN" }, { "code": null, "e": 29107, "s": 29049, "text": "Difference between Prim's and Kruskal's algorithm for MST" }, { "code": null, "e": 29152, "s": 29107, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 29205, "s": 29152, "text": "Hide or show elements in HTML using display property" }, { "code": null, "e": 29274, "s": 29205, "text": "How to calculate the number of days between two dates in javascript?" }, { "code": null, "e": 29346, "s": 29274, "text": "Differences between Functional Components and Class Components in React" } ]
jQuery Effect - Slide Effect
The Slide effect can be used with show/hide/toggle. This slides the element out of the viewport. Here is the simple syntax to use this effect − selector.hide|show|toggle( "slide", {arguments}, speed ); Here is the description of all the arguments − direction − The direction of the effect. Can be "left", "right", "up", "down". Default is left. direction − The direction of the effect. Can be "left", "right", "up", "down". Default is left. distance − The distance of the effect. Is set to either the height or width of the element depending on the direction option. distance − The distance of the effect. Is set to either the height or width of the element depending on the direction option. mode − The mode of the effect. Can be "show" or "hide". Default is show. mode − The mode of the effect. Can be "show" or "hide". Default is show. Following is a simple example a simple showing the usage of this effect − <html> <head> <title>The jQuery Example</title> <script type = "text/javascript" src = "https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"> </script> <script type = "text/javascript" src = "https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.3/jquery-ui.min.js"> </script> <script type = "text/javascript" language = "javascript"> $(document).ready(function() { $("#hide").click(function(){ $(".target").hide( "slide", { direction: "down" }, 2000 ); }); $("#show").click(function(){ $(".target").show( "slide", {direction: "up" }, 2000 ); }); }); </script> <style> p {background-color:#bca; width:200px; border:1px solid green;} div{ width:100px; height:100px; background:red;} </style> </head> <body> <p>Click on any of the buttons</p> <button id = "hide"> Hide </button> <button id = "show"> Show</button> <div class = "target"> </div> </body> </html> This will produce following result − Click on any of the buttons 27 Lectures 1 hours Mahesh Kumar 27 Lectures 1.5 hours Pratik Singh 72 Lectures 4.5 hours Frahaan Hussain 60 Lectures 9 hours Eduonix Learning Solutions 17 Lectures 2 hours Sandip Bhattacharya 12 Lectures 53 mins Laurence Svekis Print Add Notes Bookmark this page
[ { "code": null, "e": 2419, "s": 2322, "text": "The Slide effect can be used with show/hide/toggle. This slides the element out of the viewport." }, { "code": null, "e": 2466, "s": 2419, "text": "Here is the simple syntax to use this effect −" }, { "code": null, "e": 2525, "s": 2466, "text": "selector.hide|show|toggle( \"slide\", {arguments}, speed );\n" }, { "code": null, "e": 2572, "s": 2525, "text": "Here is the description of all the arguments −" }, { "code": null, "e": 2668, "s": 2572, "text": "direction − The direction of the effect. Can be \"left\", \"right\", \"up\", \"down\". Default is left." }, { "code": null, "e": 2764, "s": 2668, "text": "direction − The direction of the effect. Can be \"left\", \"right\", \"up\", \"down\". Default is left." }, { "code": null, "e": 2890, "s": 2764, "text": "distance − The distance of the effect. Is set to either the height or width of the element depending on the direction option." }, { "code": null, "e": 3016, "s": 2890, "text": "distance − The distance of the effect. Is set to either the height or width of the element depending on the direction option." }, { "code": null, "e": 3089, "s": 3016, "text": "mode − The mode of the effect. Can be \"show\" or \"hide\". Default is show." }, { "code": null, "e": 3162, "s": 3089, "text": "mode − The mode of the effect. Can be \"show\" or \"hide\". Default is show." }, { "code": null, "e": 3236, "s": 3162, "text": "Following is a simple example a simple showing the usage of this effect −" }, { "code": null, "e": 4369, "s": 3236, "text": "<html>\n <head>\n <title>The jQuery Example</title>\n <script type = \"text/javascript\" \n src = \"https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js\">\n </script>\n\t\t\n <script type = \"text/javascript\" \n src = \"https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.3/jquery-ui.min.js\">\n </script>\n\t\t\n <script type = \"text/javascript\" language = \"javascript\">\n \n $(document).ready(function() {\n\n $(\"#hide\").click(function(){\n $(\".target\").hide( \"slide\", { direction: \"down\" }, 2000 );\n });\n\n $(\"#show\").click(function(){\n $(\".target\").show( \"slide\", {direction: \"up\" }, 2000 );\n });\n\t\t\t\t\n });\n\t\t\t\n </script>\n\t\t\n <style>\n p {background-color:#bca; width:200px; border:1px solid green;}\n div{ width:100px; height:100px; background:red;}\n </style>\n </head>\n\t\n <body>\n <p>Click on any of the buttons</p>\n\t\t\n <button id = \"hide\"> Hide </button>\n <button id = \"show\"> Show</button> \n \n <div class = \"target\">\n </div>\n </body>\n</html>" }, { "code": null, "e": 4406, "s": 4369, "text": "This will produce following result −" }, { "code": null, "e": 4434, "s": 4406, "text": "Click on any of the buttons" }, { "code": null, "e": 4467, "s": 4434, "text": "\n 27 Lectures \n 1 hours \n" }, { "code": null, "e": 4481, "s": 4467, "text": " Mahesh Kumar" }, { "code": null, "e": 4516, "s": 4481, "text": "\n 27 Lectures \n 1.5 hours \n" }, { "code": null, "e": 4530, "s": 4516, "text": " Pratik Singh" }, { "code": null, "e": 4565, "s": 4530, "text": "\n 72 Lectures \n 4.5 hours \n" }, { "code": null, "e": 4582, "s": 4565, "text": " Frahaan Hussain" }, { "code": null, "e": 4615, "s": 4582, "text": "\n 60 Lectures \n 9 hours \n" }, { "code": null, "e": 4643, "s": 4615, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 4676, "s": 4643, "text": "\n 17 Lectures \n 2 hours \n" }, { "code": null, "e": 4697, "s": 4676, "text": " Sandip Bhattacharya" }, { "code": null, "e": 4729, "s": 4697, "text": "\n 12 Lectures \n 53 mins\n" }, { "code": null, "e": 4746, "s": 4729, "text": " Laurence Svekis" }, { "code": null, "e": 4753, "s": 4746, "text": " Print" }, { "code": null, "e": 4764, "s": 4753, "text": " Add Notes" } ]
How to add a class on click of anchor tag using jQuery?
To add a class on click of anchor tag using jQuery, use the addClass() method. You can try to run the following code to learn how to implement adding a class on click of anchor tag using jQuery − Live Demo <html> <head> <script src = "https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script> <script> $(document).ready(function() { $("a").click(function() { $("a.active").removeClass("active"); $(this).addClass("active"); }); }); </script> <style> .active { font-size: 22px; } </style> </head> <body> <a href="#" class="">One</a> <a href="#" class="">Two</a> <p>Click any of the link above and you can see the changes.</p> </body> </html>
[ { "code": null, "e": 1258, "s": 1062, "text": "To add a class on click of anchor tag using jQuery, use the addClass() method. You can try to run the following code to learn how to implement adding a class on click of anchor tag using jQuery −" }, { "code": null, "e": 1268, "s": 1258, "text": "Live Demo" }, { "code": null, "e": 1852, "s": 1268, "text": "<html>\n <head>\n <script src = \"https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js\"></script>\n <script>\n $(document).ready(function() {\n $(\"a\").click(function() {\n $(\"a.active\").removeClass(\"active\");\n $(this).addClass(\"active\");\n });\n });\n </script>\n <style>\n .active {\n font-size: 22px; \n }\n </style>\n </head>\n <body>\n <a href=\"#\" class=\"\">One</a>\n <a href=\"#\" class=\"\">Two</a>\n <p>Click any of the link above and you can see the changes.</p>\n </body>\n</html>" } ]
Find length of the largest region in Boolean Matrix - GeeksforGeeks
09 Mar, 2022 Consider a matrix with rows and columns, where each cell contains either a ‘0’ or a ‘1’ and any cell containing a 1 is called a filled cell. Two cells are said to be connected if they are adjacent to each other horizontally, vertically, or diagonally. If one or more filled cells are also connected, they form a region. find the length of the largest region. Examples: Input : M[][5] = { 0 0 1 1 0 1 0 1 1 0 0 1 0 0 0 0 0 0 0 1 } Output : 6 In the following example, there are 2 regions one with length 1 and the other as 6. So largest region: 6 Input : M[][5] = { 0 0 1 1 0 0 0 1 1 0 0 0 0 0 0 0 0 0 0 1 } Output: 4 In the following example, there are 2 regions one with length 1 and the other as 4. So largest region: 4 Asked in: Amazon interview Solution: The idea is based on the problem or finding number of islands in Boolean 2D-matrix Approach: A cell in 2D matrix can be connected to at most 8 neighbours.So in DFS, make recursive calls for 8 neighbours of that cell.Keep a visited Hash-map to keep track of all visited cells.Also keep track of the visited 1’s in every DFS and update maximum length region. A cell in 2D matrix can be connected to at most 8 neighbours. So in DFS, make recursive calls for 8 neighbours of that cell. Keep a visited Hash-map to keep track of all visited cells. Also keep track of the visited 1’s in every DFS and update maximum length region. Below is implementation of above idea. C++ Java Python3 C# Javascript // Program to find the length of the largest// region in boolean 2D-matrix#include <bits/stdc++.h>using namespace std;#define ROW 4#define COL 5 // A function to check if// a given cell (row, col)// can be included in DFSint isSafe(int M[][COL], int row, int col, bool visited[][COL]){ // row number is in range, // column number is in // range and value is 1 // and not yet visited return (row >= 0) && (row < ROW) && (col >= 0) && (col < COL) && (M[row][col] && !visited[row][col]);} // A utility function to// do DFS for a 2D boolean// matrix. It only considers// the 8 neighbours as// adjacent verticesvoid DFS(int M[][COL], int row, int col, bool visited[][COL], int& count){ // These arrays are used // to get row and column // numbers of 8 neighbours // of a given cell static int rowNbr[] = { -1, -1, -1, 0, 0, 1, 1, 1 }; static int colNbr[] = { -1, 0, 1, -1, 1, -1, 0, 1 }; // Mark this cell as visited visited[row][col] = true; // Recur for all connected neighbours for (int k = 0; k < 8; ++k) { if (isSafe(M, row + rowNbr[k], col + colNbr[k], visited)) { // Increment region length by one count++; DFS(M, row + rowNbr[k], col + colNbr[k], visited, count); } }} // The main function that returns// largest length region// of a given boolean 2D matrixint largestRegion(int M[][COL]){ // Make a bool array to mark visited cells. // Initially all cells are unvisited bool visited[ROW][COL]; memset(visited, 0, sizeof(visited)); // Initialize result as 0 and travesle through the // all cells of given matrix int result = INT_MIN; for (int i = 0; i < ROW; ++i) { for (int j = 0; j < COL; ++j) { // If a cell with value 1 is not if (M[i][j] && !visited[i][j]) { // visited yet, then new region found int count = 1; DFS(M, i, j, visited, count); // maximum region result = max(result, count); } } } return result;} // Driver codeint main(){ int M[][COL] = { { 0, 0, 1, 1, 0 }, { 1, 0, 1, 1, 0 }, { 0, 1, 0, 0, 0 }, { 0, 0, 0, 0, 1 } }; // Function call cout << largestRegion(M); return 0;} // Java program to find the length of the largest// region in boolean 2D-matriximport java.io.*;import java.util.*; class GFG { static int ROW, COL, count; // A function to check if a given cell (row, col) // can be included in DFS static boolean isSafe(int[][] M, int row, int col, boolean[][] visited) { // row number is in range, column number is in // range and value is 1 and not yet visited return ( (row >= 0) && (row < ROW) && (col >= 0) && (col < COL) && (M[row][col] == 1 && !visited[row][col])); } // A utility function to do DFS for a 2D boolean // matrix. It only considers the 8 neighbours as // adjacent vertices static void DFS(int[][] M, int row, int col, boolean[][] visited) { // These arrays are used to get row and column // numbers of 8 neighbours of a given cell int[] rowNbr = { -1, -1, -1, 0, 0, 1, 1, 1 }; int[] colNbr = { -1, 0, 1, -1, 1, -1, 0, 1 }; // Mark this cell as visited visited[row][col] = true; // Recur for all connected neighbours for (int k = 0; k < 8; k++) { if (isSafe(M, row + rowNbr[k], col + colNbr[k], visited)) { // increment region length by one count++; DFS(M, row + rowNbr[k], col + colNbr[k], visited); } } } // The main function that returns largest length region // of a given boolean 2D matrix static int largestRegion(int[][] M) { // Make a boolean array to mark visited cells. // Initially all cells are unvisited boolean[][] visited = new boolean[ROW][COL]; // Initialize result as 0 and traverse through the // all cells of given matrix int result = 0; for (int i = 0; i < ROW; i++) { for (int j = 0; j < COL; j++) { // If a cell with value 1 is not if (M[i][j] == 1 && !visited[i][j]) { // visited yet, then new region found count = 1; DFS(M, i, j, visited); // maximum region result = Math.max(result, count); } } } return result; } // Driver code public static void main(String args[]) { int M[][] = { { 0, 0, 1, 1, 0 }, { 1, 0, 1, 1, 0 }, { 0, 1, 0, 0, 0 }, { 0, 0, 0, 0, 1 } }; ROW = 4; COL = 5; // Function call System.out.println(largestRegion(M)); }} // This code is contributed by rachana soma # Python3 program to find the length of the# largest region in boolean 2D-matrix # A function to check if a given cell# (row, col) can be included in DFS def isSafe(M, row, col, visited): global ROW, COL # row number is in range, column number is in # range and value is 1 and not yet visited return ((row >= 0) and (row < ROW) and (col >= 0) and (col < COL) and (M[row][col] and not visited[row][col])) # A utility function to do DFS for a 2D# boolean matrix. It only considers# the 8 neighbours as adjacent vertices def DFS(M, row, col, visited, count): # These arrays are used to get row and column # numbers of 8 neighbours of a given cell rowNbr = [-1, -1, -1, 0, 0, 1, 1, 1] colNbr = [-1, 0, 1, -1, 1, -1, 0, 1] # Mark this cell as visited visited[row][col] = True # Recur for all connected neighbours for k in range(8): if (isSafe(M, row + rowNbr[k], col + colNbr[k], visited)): # increment region length by one count[0] += 1 DFS(M, row + rowNbr[k], col + colNbr[k], visited, count) # The main function that returns largest# length region of a given boolean 2D matrix def largestRegion(M): global ROW, COL # Make a bool array to mark visited cells. # Initially all cells are unvisited visited = [[0] * COL for i in range(ROW)] # Initialize result as 0 and traverse # through the all cells of given matrix result = -999999999999 for i in range(ROW): for j in range(COL): # If a cell with value 1 is not if (M[i][j] and not visited[i][j]): # visited yet, then new region found count = [1] DFS(M, i, j, visited, count) # maximum region result = max(result, count[0]) return result # Driver CodeROW = 4COL = 5 M = [[0, 0, 1, 1, 0], [1, 0, 1, 1, 0], [0, 1, 0, 0, 0], [0, 0, 0, 0, 1]] # Function callprint(largestRegion(M)) # This code is contributed by PranchalK // C# program to find the length of// the largest region in boolean 2D-matrixusing System; class GFG{ static int ROW, COL, count; // A function to check if a given cell // (row, col) can be included in DFS static Boolean isSafe(int[, ] M, int row, int col, Boolean[, ] visited) { // row number is in range, column number is in // range and value is 1 and not yet visited return ( (row >= 0) && (row < ROW) && (col >= 0) && (col < COL) && (M[row, col] == 1 && !visited[row, col])); } // A utility function to do DFS for a 2D boolean // matrix. It only considers the 8 neighbours as // adjacent vertices static void DFS(int[, ] M, int row, int col, Boolean[, ] visited) { // These arrays are used to get row and column // numbers of 8 neighbours of a given cell int[] rowNbr = { -1, -1, -1, 0, 0, 1, 1, 1 }; int[] colNbr = { -1, 0, 1, -1, 1, -1, 0, 1 }; // Mark this cell as visited visited[row, col] = true; // Recur for all connected neighbours for (int k = 0; k < 8; k++) { if (isSafe(M, row + rowNbr[k], col + colNbr[k], visited)) { // increment region length by one count++; DFS(M, row + rowNbr[k], col + colNbr[k], visited); } } } // The main function that returns // largest length region of // a given boolean 2D matrix static int largestRegion(int[, ] M) { // Make a boolean array to mark visited cells. // Initially all cells are unvisited Boolean[, ] visited = new Boolean[ROW, COL]; // Initialize result as 0 and traverse // through the all cells of given matrix int result = 0; for (int i = 0; i < ROW; i++) { for (int j = 0; j < COL; j++) { // If a cell with value 1 is not if (M[i, j] == 1 && !visited[i, j]) { // visited yet, // then new region found count = 1; DFS(M, i, j, visited); // maximum region result = Math.Max(result, count); } } } return result; } // Driver code public static void Main(String[] args) { int[, ] M = { { 0, 0, 1, 1, 0 }, { 1, 0, 1, 1, 0 }, { 0, 1, 0, 0, 0 }, { 0, 0, 0, 0, 1 } }; ROW = 4; COL = 5; // Function call Console.WriteLine(largestRegion(M)); }} // This code is contributed by Rajput-Ji <script> // JavaScript program to find the length of the largest// region in boolean 2D-matrix let ROW, COL, count; // A function to check if a given cell (row, col) // can be included in DFSfunction isSafe(M,row,col,visited){ // row number is in range, column number is in // range and value is 1 and not yet visited return ( (row >= 0) && (row < ROW) && (col >= 0) && (col < COL) && (M[row][col] == 1 && !visited[row][col]));} // A utility function to do DFS for a 2D boolean // matrix. It only considers the 8 neighbours as // adjacent verticesfunction DFS(M,row,col,visited){ // These arrays are used to get row and column // numbers of 8 neighbours of a given cell let rowNbr = [ -1, -1, -1, 0, 0, 1, 1, 1 ]; let colNbr = [ -1, 0, 1, -1, 1, -1, 0, 1 ]; // Mark this cell as visited visited[row][col] = true; // Recur for all connected neighbours for (let k = 0; k < 8; k++) { if (isSafe(M, row + rowNbr[k], col + colNbr[k], visited)) { // increment region length by one count++; DFS(M, row + rowNbr[k], col + colNbr[k], visited); } }} // The main function that returns largest length region // of a given boolean 2D matrixfunction largestRegion(M){ // Make a boolean array to mark visited cells. // Initially all cells are unvisited let visited = new Array(ROW); for(let i=0;i<ROW;i++) { visited[i]=new Array(COL); for(let j=0;j<COL;j++) { visited[i][j]=false; } } // Initialize result as 0 and traverse through the // all cells of given matrix let result = 0; for (let i = 0; i < ROW; i++) { for (let j = 0; j < COL; j++) { // If a cell with value 1 is not if (M[i][j] == 1 && !visited[i][j]) { // visited yet, then new region found count = 1; DFS(M, i, j, visited); // maximum region result = Math.max(result, count); } } } return result;} // Driver codelet M=[[ 0, 0, 1, 1, 0 ], [ 1, 0, 1, 1, 0 ], [ 0, 1, 0, 0, 0 ], [ 0, 0, 0, 0, 1 ] ]; ROW = 4;COL = 5; // Function calldocument.write(largestRegion(M)); // This code is contributed by avanitrachhadiya2155 </script> 6 Complexity Analysis: Time complexity: O(ROW * COL). At worst case all the cells will be visited so time complexity is O(ROW * COL). Auxiliary Space:O(ROW * COL). To store the visited nodes O(ROW * COL) space is needed. This article is contributed by Nishant Singh. 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. naba09 PranchalKatiyar rachana soma Rajput-Ji andrew1234 nandalamit1555 avanitrachhadiya2155 surinderdawra388 Amazon BFS DFS Microsoft Samsung Graph Amazon Microsoft Samsung DFS Graph BFS Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Topological Sorting Detect Cycle in a Directed Graph Travelling Salesman Problem | Set 1 (Naive and Dynamic Programming) Ford-Fulkerson Algorithm for Maximum Flow Problem Disjoint Set (Or Union-Find) | Set 1 (Detect Cycle in an Undirected Graph) Traveling Salesman Problem (TSP) Implementation Detect cycle in an undirected graph Hamiltonian Cycle | Backtracking-6 m Coloring Problem | Backtracking-5 Dijkstra’s Algorithm for Adjacency List Representation | Greedy Algo-8
[ { "code": null, "e": 26471, "s": 26443, "text": "\n09 Mar, 2022" }, { "code": null, "e": 26830, "s": 26471, "text": "Consider a matrix with rows and columns, where each cell contains either a ‘0’ or a ‘1’ and any cell containing a 1 is called a filled cell. Two cells are said to be connected if they are adjacent to each other horizontally, vertically, or diagonally. If one or more filled cells are also connected, they form a region. find the length of the largest region." }, { "code": null, "e": 26841, "s": 26830, "text": "Examples: " }, { "code": null, "e": 27314, "s": 26841, "text": "Input : M[][5] = { 0 0 1 1 0\n 1 0 1 1 0\n 0 1 0 0 0\n 0 0 0 0 1 }\nOutput : 6 \nIn the following example, there are \n2 regions one with length 1 and the \nother as 6. So largest region: 6\n\nInput : M[][5] = { 0 0 1 1 0\n 0 0 1 1 0\n 0 0 0 0 0\n 0 0 0 0 1 }\nOutput: 4\nIn the following example, there are \n2 regions one with length 1 and the \nother as 4. So largest region: 4" }, { "code": null, "e": 27342, "s": 27314, "text": "Asked in: Amazon interview " }, { "code": null, "e": 27436, "s": 27342, "text": "Solution: The idea is based on the problem or finding number of islands in Boolean 2D-matrix " }, { "code": null, "e": 27448, "s": 27436, "text": "Approach: " }, { "code": null, "e": 27712, "s": 27448, "text": "A cell in 2D matrix can be connected to at most 8 neighbours.So in DFS, make recursive calls for 8 neighbours of that cell.Keep a visited Hash-map to keep track of all visited cells.Also keep track of the visited 1’s in every DFS and update maximum length region." }, { "code": null, "e": 27774, "s": 27712, "text": "A cell in 2D matrix can be connected to at most 8 neighbours." }, { "code": null, "e": 27837, "s": 27774, "text": "So in DFS, make recursive calls for 8 neighbours of that cell." }, { "code": null, "e": 27897, "s": 27837, "text": "Keep a visited Hash-map to keep track of all visited cells." }, { "code": null, "e": 27979, "s": 27897, "text": "Also keep track of the visited 1’s in every DFS and update maximum length region." }, { "code": null, "e": 28019, "s": 27979, "text": "Below is implementation of above idea. " }, { "code": null, "e": 28023, "s": 28019, "text": "C++" }, { "code": null, "e": 28028, "s": 28023, "text": "Java" }, { "code": null, "e": 28036, "s": 28028, "text": "Python3" }, { "code": null, "e": 28039, "s": 28036, "text": "C#" }, { "code": null, "e": 28050, "s": 28039, "text": "Javascript" }, { "code": "// Program to find the length of the largest// region in boolean 2D-matrix#include <bits/stdc++.h>using namespace std;#define ROW 4#define COL 5 // A function to check if// a given cell (row, col)// can be included in DFSint isSafe(int M[][COL], int row, int col, bool visited[][COL]){ // row number is in range, // column number is in // range and value is 1 // and not yet visited return (row >= 0) && (row < ROW) && (col >= 0) && (col < COL) && (M[row][col] && !visited[row][col]);} // A utility function to// do DFS for a 2D boolean// matrix. It only considers// the 8 neighbours as// adjacent verticesvoid DFS(int M[][COL], int row, int col, bool visited[][COL], int& count){ // These arrays are used // to get row and column // numbers of 8 neighbours // of a given cell static int rowNbr[] = { -1, -1, -1, 0, 0, 1, 1, 1 }; static int colNbr[] = { -1, 0, 1, -1, 1, -1, 0, 1 }; // Mark this cell as visited visited[row][col] = true; // Recur for all connected neighbours for (int k = 0; k < 8; ++k) { if (isSafe(M, row + rowNbr[k], col + colNbr[k], visited)) { // Increment region length by one count++; DFS(M, row + rowNbr[k], col + colNbr[k], visited, count); } }} // The main function that returns// largest length region// of a given boolean 2D matrixint largestRegion(int M[][COL]){ // Make a bool array to mark visited cells. // Initially all cells are unvisited bool visited[ROW][COL]; memset(visited, 0, sizeof(visited)); // Initialize result as 0 and travesle through the // all cells of given matrix int result = INT_MIN; for (int i = 0; i < ROW; ++i) { for (int j = 0; j < COL; ++j) { // If a cell with value 1 is not if (M[i][j] && !visited[i][j]) { // visited yet, then new region found int count = 1; DFS(M, i, j, visited, count); // maximum region result = max(result, count); } } } return result;} // Driver codeint main(){ int M[][COL] = { { 0, 0, 1, 1, 0 }, { 1, 0, 1, 1, 0 }, { 0, 1, 0, 0, 0 }, { 0, 0, 0, 0, 1 } }; // Function call cout << largestRegion(M); return 0;}", "e": 30490, "s": 28050, "text": null }, { "code": "// Java program to find the length of the largest// region in boolean 2D-matriximport java.io.*;import java.util.*; class GFG { static int ROW, COL, count; // A function to check if a given cell (row, col) // can be included in DFS static boolean isSafe(int[][] M, int row, int col, boolean[][] visited) { // row number is in range, column number is in // range and value is 1 and not yet visited return ( (row >= 0) && (row < ROW) && (col >= 0) && (col < COL) && (M[row][col] == 1 && !visited[row][col])); } // A utility function to do DFS for a 2D boolean // matrix. It only considers the 8 neighbours as // adjacent vertices static void DFS(int[][] M, int row, int col, boolean[][] visited) { // These arrays are used to get row and column // numbers of 8 neighbours of a given cell int[] rowNbr = { -1, -1, -1, 0, 0, 1, 1, 1 }; int[] colNbr = { -1, 0, 1, -1, 1, -1, 0, 1 }; // Mark this cell as visited visited[row][col] = true; // Recur for all connected neighbours for (int k = 0; k < 8; k++) { if (isSafe(M, row + rowNbr[k], col + colNbr[k], visited)) { // increment region length by one count++; DFS(M, row + rowNbr[k], col + colNbr[k], visited); } } } // The main function that returns largest length region // of a given boolean 2D matrix static int largestRegion(int[][] M) { // Make a boolean array to mark visited cells. // Initially all cells are unvisited boolean[][] visited = new boolean[ROW][COL]; // Initialize result as 0 and traverse through the // all cells of given matrix int result = 0; for (int i = 0; i < ROW; i++) { for (int j = 0; j < COL; j++) { // If a cell with value 1 is not if (M[i][j] == 1 && !visited[i][j]) { // visited yet, then new region found count = 1; DFS(M, i, j, visited); // maximum region result = Math.max(result, count); } } } return result; } // Driver code public static void main(String args[]) { int M[][] = { { 0, 0, 1, 1, 0 }, { 1, 0, 1, 1, 0 }, { 0, 1, 0, 0, 0 }, { 0, 0, 0, 0, 1 } }; ROW = 4; COL = 5; // Function call System.out.println(largestRegion(M)); }} // This code is contributed by rachana soma", "e": 33275, "s": 30490, "text": null }, { "code": "# Python3 program to find the length of the# largest region in boolean 2D-matrix # A function to check if a given cell# (row, col) can be included in DFS def isSafe(M, row, col, visited): global ROW, COL # row number is in range, column number is in # range and value is 1 and not yet visited return ((row >= 0) and (row < ROW) and (col >= 0) and (col < COL) and (M[row][col] and not visited[row][col])) # A utility function to do DFS for a 2D# boolean matrix. It only considers# the 8 neighbours as adjacent vertices def DFS(M, row, col, visited, count): # These arrays are used to get row and column # numbers of 8 neighbours of a given cell rowNbr = [-1, -1, -1, 0, 0, 1, 1, 1] colNbr = [-1, 0, 1, -1, 1, -1, 0, 1] # Mark this cell as visited visited[row][col] = True # Recur for all connected neighbours for k in range(8): if (isSafe(M, row + rowNbr[k], col + colNbr[k], visited)): # increment region length by one count[0] += 1 DFS(M, row + rowNbr[k], col + colNbr[k], visited, count) # The main function that returns largest# length region of a given boolean 2D matrix def largestRegion(M): global ROW, COL # Make a bool array to mark visited cells. # Initially all cells are unvisited visited = [[0] * COL for i in range(ROW)] # Initialize result as 0 and traverse # through the all cells of given matrix result = -999999999999 for i in range(ROW): for j in range(COL): # If a cell with value 1 is not if (M[i][j] and not visited[i][j]): # visited yet, then new region found count = [1] DFS(M, i, j, visited, count) # maximum region result = max(result, count[0]) return result # Driver CodeROW = 4COL = 5 M = [[0, 0, 1, 1, 0], [1, 0, 1, 1, 0], [0, 1, 0, 0, 0], [0, 0, 0, 0, 1]] # Function callprint(largestRegion(M)) # This code is contributed by PranchalK", "e": 35328, "s": 33275, "text": null }, { "code": "// C# program to find the length of// the largest region in boolean 2D-matrixusing System; class GFG{ static int ROW, COL, count; // A function to check if a given cell // (row, col) can be included in DFS static Boolean isSafe(int[, ] M, int row, int col, Boolean[, ] visited) { // row number is in range, column number is in // range and value is 1 and not yet visited return ( (row >= 0) && (row < ROW) && (col >= 0) && (col < COL) && (M[row, col] == 1 && !visited[row, col])); } // A utility function to do DFS for a 2D boolean // matrix. It only considers the 8 neighbours as // adjacent vertices static void DFS(int[, ] M, int row, int col, Boolean[, ] visited) { // These arrays are used to get row and column // numbers of 8 neighbours of a given cell int[] rowNbr = { -1, -1, -1, 0, 0, 1, 1, 1 }; int[] colNbr = { -1, 0, 1, -1, 1, -1, 0, 1 }; // Mark this cell as visited visited[row, col] = true; // Recur for all connected neighbours for (int k = 0; k < 8; k++) { if (isSafe(M, row + rowNbr[k], col + colNbr[k], visited)) { // increment region length by one count++; DFS(M, row + rowNbr[k], col + colNbr[k], visited); } } } // The main function that returns // largest length region of // a given boolean 2D matrix static int largestRegion(int[, ] M) { // Make a boolean array to mark visited cells. // Initially all cells are unvisited Boolean[, ] visited = new Boolean[ROW, COL]; // Initialize result as 0 and traverse // through the all cells of given matrix int result = 0; for (int i = 0; i < ROW; i++) { for (int j = 0; j < COL; j++) { // If a cell with value 1 is not if (M[i, j] == 1 && !visited[i, j]) { // visited yet, // then new region found count = 1; DFS(M, i, j, visited); // maximum region result = Math.Max(result, count); } } } return result; } // Driver code public static void Main(String[] args) { int[, ] M = { { 0, 0, 1, 1, 0 }, { 1, 0, 1, 1, 0 }, { 0, 1, 0, 0, 0 }, { 0, 0, 0, 0, 1 } }; ROW = 4; COL = 5; // Function call Console.WriteLine(largestRegion(M)); }} // This code is contributed by Rajput-Ji", "e": 38131, "s": 35328, "text": null }, { "code": "<script> // JavaScript program to find the length of the largest// region in boolean 2D-matrix let ROW, COL, count; // A function to check if a given cell (row, col) // can be included in DFSfunction isSafe(M,row,col,visited){ // row number is in range, column number is in // range and value is 1 and not yet visited return ( (row >= 0) && (row < ROW) && (col >= 0) && (col < COL) && (M[row][col] == 1 && !visited[row][col]));} // A utility function to do DFS for a 2D boolean // matrix. It only considers the 8 neighbours as // adjacent verticesfunction DFS(M,row,col,visited){ // These arrays are used to get row and column // numbers of 8 neighbours of a given cell let rowNbr = [ -1, -1, -1, 0, 0, 1, 1, 1 ]; let colNbr = [ -1, 0, 1, -1, 1, -1, 0, 1 ]; // Mark this cell as visited visited[row][col] = true; // Recur for all connected neighbours for (let k = 0; k < 8; k++) { if (isSafe(M, row + rowNbr[k], col + colNbr[k], visited)) { // increment region length by one count++; DFS(M, row + rowNbr[k], col + colNbr[k], visited); } }} // The main function that returns largest length region // of a given boolean 2D matrixfunction largestRegion(M){ // Make a boolean array to mark visited cells. // Initially all cells are unvisited let visited = new Array(ROW); for(let i=0;i<ROW;i++) { visited[i]=new Array(COL); for(let j=0;j<COL;j++) { visited[i][j]=false; } } // Initialize result as 0 and traverse through the // all cells of given matrix let result = 0; for (let i = 0; i < ROW; i++) { for (let j = 0; j < COL; j++) { // If a cell with value 1 is not if (M[i][j] == 1 && !visited[i][j]) { // visited yet, then new region found count = 1; DFS(M, i, j, visited); // maximum region result = Math.max(result, count); } } } return result;} // Driver codelet M=[[ 0, 0, 1, 1, 0 ], [ 1, 0, 1, 1, 0 ], [ 0, 1, 0, 0, 0 ], [ 0, 0, 0, 0, 1 ] ]; ROW = 4;COL = 5; // Function calldocument.write(largestRegion(M)); // This code is contributed by avanitrachhadiya2155 </script>", "e": 40802, "s": 38131, "text": null }, { "code": null, "e": 40804, "s": 40802, "text": "6" }, { "code": null, "e": 40826, "s": 40804, "text": "Complexity Analysis: " }, { "code": null, "e": 40937, "s": 40826, "text": "Time complexity: O(ROW * COL). At worst case all the cells will be visited so time complexity is O(ROW * COL)." }, { "code": null, "e": 41024, "s": 40937, "text": "Auxiliary Space:O(ROW * COL). To store the visited nodes O(ROW * COL) space is needed." }, { "code": null, "e": 41321, "s": 41024, "text": "This article is contributed by Nishant Singh. 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": 41447, "s": 41321, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. " }, { "code": null, "e": 41454, "s": 41447, "text": "naba09" }, { "code": null, "e": 41470, "s": 41454, "text": "PranchalKatiyar" }, { "code": null, "e": 41483, "s": 41470, "text": "rachana soma" }, { "code": null, "e": 41493, "s": 41483, "text": "Rajput-Ji" }, { "code": null, "e": 41504, "s": 41493, "text": "andrew1234" }, { "code": null, "e": 41519, "s": 41504, "text": "nandalamit1555" }, { "code": null, "e": 41540, "s": 41519, "text": "avanitrachhadiya2155" }, { "code": null, "e": 41557, "s": 41540, "text": "surinderdawra388" }, { "code": null, "e": 41564, "s": 41557, "text": "Amazon" }, { "code": null, "e": 41568, "s": 41564, "text": "BFS" }, { "code": null, "e": 41572, "s": 41568, "text": "DFS" }, { "code": null, "e": 41582, "s": 41572, "text": "Microsoft" }, { "code": null, "e": 41590, "s": 41582, "text": "Samsung" }, { "code": null, "e": 41596, "s": 41590, "text": "Graph" }, { "code": null, "e": 41603, "s": 41596, "text": "Amazon" }, { "code": null, "e": 41613, "s": 41603, "text": "Microsoft" }, { "code": null, "e": 41621, "s": 41613, "text": "Samsung" }, { "code": null, "e": 41625, "s": 41621, "text": "DFS" }, { "code": null, "e": 41631, "s": 41625, "text": "Graph" }, { "code": null, "e": 41635, "s": 41631, "text": "BFS" }, { "code": null, "e": 41733, "s": 41635, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 41753, "s": 41733, "text": "Topological Sorting" }, { "code": null, "e": 41786, "s": 41753, "text": "Detect Cycle in a Directed Graph" }, { "code": null, "e": 41854, "s": 41786, "text": "Travelling Salesman Problem | Set 1 (Naive and Dynamic Programming)" }, { "code": null, "e": 41904, "s": 41854, "text": "Ford-Fulkerson Algorithm for Maximum Flow Problem" }, { "code": null, "e": 41979, "s": 41904, "text": "Disjoint Set (Or Union-Find) | Set 1 (Detect Cycle in an Undirected Graph)" }, { "code": null, "e": 42027, "s": 41979, "text": "Traveling Salesman Problem (TSP) Implementation" }, { "code": null, "e": 42063, "s": 42027, "text": "Detect cycle in an undirected graph" }, { "code": null, "e": 42098, "s": 42063, "text": "Hamiltonian Cycle | Backtracking-6" }, { "code": null, "e": 42134, "s": 42098, "text": "m Coloring Problem | Backtracking-5" } ]
How to create a shallow copy of SortedList Object in C# - GeeksforGeeks
01 Feb, 2019 SortedList.Clone() Method is used to create a shallow copy of a SortedList object. Syntax: public virtual object Clone(); Return Value: It returns a shallow copy of the SortedList object. The type of returned value will be Object. Note: A shallow copy of a collection copies only the elements of the collection, whether they are reference types or value types, but does not copy the objects that the references refer to. The references in the new collection point to the same objects that the references in the original collection point to. Below programs illustrate the use of above-discussed method: Example 1: // C# code to copy the // contents of one SortedList // to another SortedList. using System; using System.Collections; class Geeks { // Main Method public static void Main(String[] args) { // Creating a SortedList SortedList mySL = new SortedList(); // Adding elements to SortedList mySL.Add(1, "C"); mySL.Add(2, "C++"); mySL.Add(3, "Java"); mySL.Add(4, "C#"); // Creating a shallow copy of mySL // we need to cast it explicitly SortedList myNewSL = (SortedList)mySL.Clone(); // displaying the elements of mySL Console.WriteLine("Elements of mySL: "); for (int i = 0; i < mySL.Count; i++) { Console.WriteLine("{0}:\t{1}", mySL.GetKey(i), mySL.GetByIndex(i)); } // displaying the elements of myNewSL Console.WriteLine("\nElements of myNewSL: "); for (int i = 0; i < myNewSL.Count; i++) { Console.WriteLine("{0}:\t{1}", myNewSL.GetKey(i), myNewSL.GetByIndex(i)); } } } Elements of mySL: 1: C 2: C++ 3: Java 4: C# Elements of myNewSL: 1: C 2: C++ 3: Java 4: C# Example 2: // C# code to copy the // contents of one SortedList // to another SortedList. using System; using System.Collections; class Geeks { // Main Method public static void Main(String[] args) { // Creating a SortedList SortedList mySL = new SortedList(); // Adding elements to SortedList mySL.Add(1, "HTML"); mySL.Add(2, "CSS"); mySL.Add(3, "PHP"); mySL.Add(4, "DBMS"); // Creating a shallow copy of mySL // we need to cast it explicitly SortedList myNewSL = (SortedList)mySL.Clone(); // checking for the equality // of References mySL and myNewSL Console.WriteLine("Reference Equals: {0}", Object.ReferenceEquals(mySL, myNewSL)); // displaying the elements of mySL Console.WriteLine("Elements of mySL: "); for (int i = 0; i < mySL.Count; i++) { Console.WriteLine("{0}:\t{1}", mySL.GetKey(i), mySL.GetByIndex(i)); } // displaying the elements of myNewSL Console.WriteLine("\nElements of myNewSL: "); for (int i = 0; i < myNewSL.Count; i++) { Console.WriteLine("{0}:\t{1}", myNewSL.GetKey(i), myNewSL.GetByIndex(i)); } // Replaces the values at // index 1 of mySL mySL.SetByIndex(1, "C#"); Console.WriteLine("\nAfter Replaces Elements in mySL\n"); // displaying the elements of myNewSL Console.WriteLine("\nElements of myNewSL: "); for (int i = 0; i < myNewSL.Count; i++) { Console.WriteLine("{0}:\t{1}", myNewSL.GetKey(i), myNewSL.GetByIndex(i)); } // displaying the elements of mySL Console.WriteLine("\nElements of mySL: "); for (int i = 0; i < mySL.Count; i++) { Console.WriteLine("{0}:\t{1}", mySL.GetKey(i), mySL.GetByIndex(i)); } } } Reference Equals: False Elements of mySL: 1: HTML 2: CSS 3: PHP 4: DBMS Elements of myNewSL: 1: HTML 2: CSS 3: PHP 4: DBMS After Replaces Elements in mySL Elements of myNewSL: 1: HTML 2: CSS 3: PHP 4: DBMS Elements of mySL: 1: HTML 2: C# 3: PHP 4: DBMS Reference: https://docs.microsoft.com/en-us/dotnet/api/system.collections.sortedlist.clone?view=netframework-4.7.2 CSharp-Collections-Namespace CSharp-Collections-SortedList CSharp-method Picked C# Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. C# Dictionary with examples C# | Delegates C# | Abstract Classes Extension Method in C# C# | Replace() Method C# | String.IndexOf( ) Method | Set - 1 Introduction to .NET Framework C# | Data Types C# | Arrays HashSet in C# with Examples
[ { "code": null, "e": 25517, "s": 25489, "text": "\n01 Feb, 2019" }, { "code": null, "e": 25600, "s": 25517, "text": "SortedList.Clone() Method is used to create a shallow copy of a SortedList object." }, { "code": null, "e": 25608, "s": 25600, "text": "Syntax:" }, { "code": null, "e": 25639, "s": 25608, "text": "public virtual object Clone();" }, { "code": null, "e": 25748, "s": 25639, "text": "Return Value: It returns a shallow copy of the SortedList object. The type of returned value will be Object." }, { "code": null, "e": 26058, "s": 25748, "text": "Note: A shallow copy of a collection copies only the elements of the collection, whether they are reference types or value types, but does not copy the objects that the references refer to. The references in the new collection point to the same objects that the references in the original collection point to." }, { "code": null, "e": 26119, "s": 26058, "text": "Below programs illustrate the use of above-discussed method:" }, { "code": null, "e": 26130, "s": 26119, "text": "Example 1:" }, { "code": "// C# code to copy the // contents of one SortedList // to another SortedList. using System; using System.Collections; class Geeks { // Main Method public static void Main(String[] args) { // Creating a SortedList SortedList mySL = new SortedList(); // Adding elements to SortedList mySL.Add(1, \"C\"); mySL.Add(2, \"C++\"); mySL.Add(3, \"Java\"); mySL.Add(4, \"C#\"); // Creating a shallow copy of mySL // we need to cast it explicitly SortedList myNewSL = (SortedList)mySL.Clone(); // displaying the elements of mySL Console.WriteLine(\"Elements of mySL: \"); for (int i = 0; i < mySL.Count; i++) { Console.WriteLine(\"{0}:\\t{1}\", mySL.GetKey(i), mySL.GetByIndex(i)); } // displaying the elements of myNewSL Console.WriteLine(\"\\nElements of myNewSL: \"); for (int i = 0; i < myNewSL.Count; i++) { Console.WriteLine(\"{0}:\\t{1}\", myNewSL.GetKey(i), myNewSL.GetByIndex(i)); } } } ", "e": 27472, "s": 26130, "text": null }, { "code": null, "e": 27591, "s": 27472, "text": "Elements of mySL: \n1: C\n2: C++\n3: Java\n4: C#\n\nElements of myNewSL: \n1: C\n2: C++\n3: Java\n4: C#\n" }, { "code": null, "e": 27602, "s": 27591, "text": "Example 2:" }, { "code": "// C# code to copy the // contents of one SortedList // to another SortedList. using System; using System.Collections; class Geeks { // Main Method public static void Main(String[] args) { // Creating a SortedList SortedList mySL = new SortedList(); // Adding elements to SortedList mySL.Add(1, \"HTML\"); mySL.Add(2, \"CSS\"); mySL.Add(3, \"PHP\"); mySL.Add(4, \"DBMS\"); // Creating a shallow copy of mySL // we need to cast it explicitly SortedList myNewSL = (SortedList)mySL.Clone(); // checking for the equality // of References mySL and myNewSL Console.WriteLine(\"Reference Equals: {0}\", Object.ReferenceEquals(mySL, myNewSL)); // displaying the elements of mySL Console.WriteLine(\"Elements of mySL: \"); for (int i = 0; i < mySL.Count; i++) { Console.WriteLine(\"{0}:\\t{1}\", mySL.GetKey(i), mySL.GetByIndex(i)); } // displaying the elements of myNewSL Console.WriteLine(\"\\nElements of myNewSL: \"); for (int i = 0; i < myNewSL.Count; i++) { Console.WriteLine(\"{0}:\\t{1}\", myNewSL.GetKey(i), myNewSL.GetByIndex(i)); } // Replaces the values at // index 1 of mySL mySL.SetByIndex(1, \"C#\"); Console.WriteLine(\"\\nAfter Replaces Elements in mySL\\n\"); // displaying the elements of myNewSL Console.WriteLine(\"\\nElements of myNewSL: \"); for (int i = 0; i < myNewSL.Count; i++) { Console.WriteLine(\"{0}:\\t{1}\", myNewSL.GetKey(i), myNewSL.GetByIndex(i)); } // displaying the elements of mySL Console.WriteLine(\"\\nElements of mySL: \"); for (int i = 0; i < mySL.Count; i++) { Console.WriteLine(\"{0}:\\t{1}\", mySL.GetKey(i), mySL.GetByIndex(i)); } } } ", "e": 30085, "s": 27602, "text": null }, { "code": null, "e": 30396, "s": 30085, "text": "Reference Equals: False\nElements of mySL: \n1: HTML\n2: CSS\n3: PHP\n4: DBMS\n\nElements of myNewSL: \n1: HTML\n2: CSS\n3: PHP\n4: DBMS\n\nAfter Replaces Elements in mySL\n\n\nElements of myNewSL: \n1: HTML\n2: CSS\n3: PHP\n4: DBMS\n\nElements of mySL: \n1: HTML\n2: C#\n3: PHP\n4: DBMS\n" }, { "code": null, "e": 30407, "s": 30396, "text": "Reference:" }, { "code": null, "e": 30511, "s": 30407, "text": "https://docs.microsoft.com/en-us/dotnet/api/system.collections.sortedlist.clone?view=netframework-4.7.2" }, { "code": null, "e": 30540, "s": 30511, "text": "CSharp-Collections-Namespace" }, { "code": null, "e": 30570, "s": 30540, "text": "CSharp-Collections-SortedList" }, { "code": null, "e": 30584, "s": 30570, "text": "CSharp-method" }, { "code": null, "e": 30591, "s": 30584, "text": "Picked" }, { "code": null, "e": 30594, "s": 30591, "text": "C#" }, { "code": null, "e": 30692, "s": 30594, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30720, "s": 30692, "text": "C# Dictionary with examples" }, { "code": null, "e": 30735, "s": 30720, "text": "C# | Delegates" }, { "code": null, "e": 30757, "s": 30735, "text": "C# | Abstract Classes" }, { "code": null, "e": 30780, "s": 30757, "text": "Extension Method in C#" }, { "code": null, "e": 30802, "s": 30780, "text": "C# | Replace() Method" }, { "code": null, "e": 30842, "s": 30802, "text": "C# | String.IndexOf( ) Method | Set - 1" }, { "code": null, "e": 30873, "s": 30842, "text": "Introduction to .NET Framework" }, { "code": null, "e": 30889, "s": 30873, "text": "C# | Data Types" }, { "code": null, "e": 30901, "s": 30889, "text": "C# | Arrays" } ]
XAML - Custom Controls
XAML has one of the most powerful features provided to create custom controls which make it very easy to create feature-rich and customizable controls. Custom controls are used when all the built-in controls provided by Microsoft are not fulfilling your criteria or you don’t want to pay for 3rd party controls. In this chapter, you will learn how to create custom controls. Before we start taking a look at Custom Controls, let's take a quick look at a User Control first. User Controls provide a technique to collect and combine different built-in controls together and package them into re-usable XAML. User controls are used in the following scenarios − If the control consists of existing controls, i.e., you can create a single control of multiple, already existing controls. If the control consists of existing controls, i.e., you can create a single control of multiple, already existing controls. If the control don't need support for theming. User Controls do not support complex customization, control templates, and also difficult to style. If the control don't need support for theming. User Controls do not support complex customization, control templates, and also difficult to style. If a developer prefers to write controls using the code-behind model where a view and then a direct code is written behind for event handlers. If a developer prefers to write controls using the code-behind model where a view and then a direct code is written behind for event handlers. You won't be sharing your control across applications. You won't be sharing your control across applications. Let’s take an example of User control and follow the steps given below − Step 1 − Create a new WPF project and then right-click on your solution and select Add > New Item... Step 1 − Create a new WPF project and then right-click on your solution and select Add > New Item... Step 2 − The following dialog will open, now select User Control (WPF) and name it MyUserControl. Step 2 − The following dialog will open, now select User Control (WPF) and name it MyUserControl. Step 3 − Click on the Add button and you will see that two new files (MyUserControl.xaml and MyUserControl.cs) will be added in your solution. Step 3 − Click on the Add button and you will see that two new files (MyUserControl.xaml and MyUserControl.cs) will be added in your solution. Given below is the XAML code in which a button and a textbox is created with some properties in MyUserControl.xaml file. <UserControl x:Class = "XAMLUserControl.MyUserControl" xmlns = "http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x = "http://schemas.microsoft.com/winfx/2006/xaml" xmlns:mc = "http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:d = "http://schemas.microsoft.com/expression/blend/2008" mc:Ignorable = "d" d:DesignHeight = "300" d:DesignWidth = "300"> <Grid> <TextBox Height = "23" HorizontalAlignment = "Left" Margin = "80,49,0,0" Name = "txtBox" VerticalAlignment = "Top" Width = "200" /> <Button Content = "Click Me" Height = "23" HorizontalAlignment = "Left" Margin = "96,88,0,0" Name = "button" VerticalAlignment = "Top" Width = "75" Click = "button_Click" /> </Grid> </UserControl> Given below is the C# code for button click event in MyUserControl.cs file which updates the textbox. using System; using System.Windows; using System.Windows.Controls; namespace XAMLUserControl { /// <summary> /// Interaction logic for MyUserControl.xaml /// </summary> public partial class MyUserControl : UserControl { public MyUserControl() { InitializeComponent(); } private void button_Click(object sender, RoutedEventArgs e) { txtBox.Text = "You have just clicked the button"; } } } Here is implementation in MainWindow.xaml to add the user control. <Window x:Class = "XAMLUserControl.MainWindow" xmlns = "http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x = "http://schemas.microsoft.com/winfx/2006/xaml" xmlns:control = "clr-namespace:XAMLUserControl" Title = "MainWindow" Height = "350" Width = "525"> <Grid> <control:MyUserControl/> </Grid> </Window> When you compile and execute the above code, it will produce the following output − Now click on the "Click Me" button and you will see that the textbox text is updated. A custom control is a class which offers its own style and template which are normally defined in generic.xaml. Custom controls are used in following scenarios, If the control doesn't exist and you have to create it from scratch. If the control doesn't exist and you have to create it from scratch. If you want to extend or add functionality to a preexisting control by adding an extra property or an extra functionality to fit your specific scenario. If you want to extend or add functionality to a preexisting control by adding an extra property or an extra functionality to fit your specific scenario. If your controls need to support theming and styling. If your controls need to support theming and styling. If you want to share you control across applications. If you want to share you control across applications. Let’s take an example of custom control and follow the steps given below. Step 1 − Create a new WPF project and then right-click on your solution and select Add > New Item... Step 1 − Create a new WPF project and then right-click on your solution and select Add > New Item... Step 2 − The following dialog box will open. Now select Custom Control (WPF) and name it MyCustomControl. Step 2 − The following dialog box will open. Now select Custom Control (WPF) and name it MyCustomControl. Step 3 − Click on the Add button and you will see that two new files (Themes/Generic.xaml and MyCustomControl.cs) will be added in your solution. Step 3 − Click on the Add button and you will see that two new files (Themes/Generic.xaml and MyCustomControl.cs) will be added in your solution. Given below is the XAML code in which style is set for the custom control in Generic.xaml file. <ResourceDictionary xmlns = "http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x = "http://schemas.microsoft.com/winfx/2006/xaml" xmlns:local = "clr-namespace:XAMLCustomControls"> <Style TargetType = "{x:Type local:MyCustomControl}" BasedOn = "{StaticResource {x:Type Button}}"> <Setter Property = "Background" Value = "LightSalmon"/> <Setter Property = "Foreground" Value = "Blue"/> </Style> </ResourceDictionary> Given below is the C# code for MyCustomControl class which is inherited from the button class and in the constructor, it overrides the metadata. using System; using System.Windows; using System.Windows.Controls; namespace XAMLCustomControls { public class MyCustomControl : Button { static MyCustomControl() { DefaultStyleKeyProperty.OverrideMetadata(typeof(MyCustomControl), new FrameworkPropertyMetadata(typeof(MyCustomControl))); } } } Given below is the custom control click event implementation in C# which updates the text of the text block. using System; using System.Windows; using System.Windows.Controls; namespace XAMLCustomControls { /// <summary> /// Interaction logic for MainWindow.xaml /// </summary> public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); } private void customControl_Click(object sender, RoutedEventArgs e) { txtBlock.Text = "You have just click your custom control"; } } } Here is the implementation in MainWindow.xaml to add the custom control and a TextBlock. <Window x:Class = "XAMLCustomControls.MainWindow" xmlns = "http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x = "http://schemas.microsoft.com/winfx/2006/xaml" xmlns:control = "clr-namespace:XAMLCustomControls" Title = "MainWindow" Height = "350" Width = "604"> <StackPanel> <control:MyCustomControl x:Name = "customControl" Content = "Click Me" Width = "70" Margin = "10" Click = "customControl_Click"/> <TextBlock Name = "txtBlock" Width = "250" Height = "30"/> </StackPanel> </Window> When you compile and execute the above code, it will produce the following output. Observe the output contains a custom control which is a customized button. Now click on the customized button. You will see that the text block text is updated. Print Add Notes Bookmark this page
[ { "code": null, "e": 2235, "s": 1923, "text": "XAML has one of the most powerful features provided to create custom controls which make it very easy to create feature-rich and customizable controls. Custom controls are used when all the built-in controls provided by Microsoft are not fulfilling your criteria or you don’t want to pay for 3rd party controls." }, { "code": null, "e": 2397, "s": 2235, "text": "In this chapter, you will learn how to create custom controls. Before we start taking a look at Custom Controls, let's take a quick look at a User Control first." }, { "code": null, "e": 2581, "s": 2397, "text": "User Controls provide a technique to collect and combine different built-in controls together and package them into re-usable XAML. User controls are used in the following scenarios −" }, { "code": null, "e": 2705, "s": 2581, "text": "If the control consists of existing controls, i.e., you can create a single control of multiple, already existing controls." }, { "code": null, "e": 2829, "s": 2705, "text": "If the control consists of existing controls, i.e., you can create a single control of multiple, already existing controls." }, { "code": null, "e": 2976, "s": 2829, "text": "If the control don't need support for theming. User Controls do not support complex customization, control templates, and also difficult to style." }, { "code": null, "e": 3123, "s": 2976, "text": "If the control don't need support for theming. User Controls do not support complex customization, control templates, and also difficult to style." }, { "code": null, "e": 3266, "s": 3123, "text": "If a developer prefers to write controls using the code-behind model where a view and then a direct code is written behind for event handlers." }, { "code": null, "e": 3409, "s": 3266, "text": "If a developer prefers to write controls using the code-behind model where a view and then a direct code is written behind for event handlers." }, { "code": null, "e": 3464, "s": 3409, "text": "You won't be sharing your control across applications." }, { "code": null, "e": 3519, "s": 3464, "text": "You won't be sharing your control across applications." }, { "code": null, "e": 3592, "s": 3519, "text": "Let’s take an example of User control and follow the steps given below −" }, { "code": null, "e": 3693, "s": 3592, "text": "Step 1 − Create a new WPF project and then right-click on your solution and select Add > New Item..." }, { "code": null, "e": 3794, "s": 3693, "text": "Step 1 − Create a new WPF project and then right-click on your solution and select Add > New Item..." }, { "code": null, "e": 3892, "s": 3794, "text": "Step 2 − The following dialog will open, now select User Control (WPF) and name it MyUserControl." }, { "code": null, "e": 3990, "s": 3892, "text": "Step 2 − The following dialog will open, now select User Control (WPF) and name it MyUserControl." }, { "code": null, "e": 4133, "s": 3990, "text": "Step 3 − Click on the Add button and you will see that two new files (MyUserControl.xaml and MyUserControl.cs) will be added in your solution." }, { "code": null, "e": 4276, "s": 4133, "text": "Step 3 − Click on the Add button and you will see that two new files (MyUserControl.xaml and MyUserControl.cs) will be added in your solution." }, { "code": null, "e": 4397, "s": 4276, "text": "Given below is the XAML code in which a button and a textbox is created with some properties in MyUserControl.xaml file." }, { "code": null, "e": 5183, "s": 4397, "text": "<UserControl x:Class = \"XAMLUserControl.MyUserControl\" \n xmlns = \"http://schemas.microsoft.com/winfx/2006/xaml/presentation\"\n xmlns:x = \"http://schemas.microsoft.com/winfx/2006/xaml\" \n xmlns:mc = \"http://schemas.openxmlformats.org/markup-compatibility/2006\"\n xmlns:d = \"http://schemas.microsoft.com/expression/blend/2008\"\n mc:Ignorable = \"d\" d:DesignHeight = \"300\" d:DesignWidth = \"300\">\n\t\n <Grid>\n <TextBox Height = \"23\" HorizontalAlignment = \"Left\" \n Margin = \"80,49,0,0\" Name = \"txtBox\" VerticalAlignment = \"Top\" Width = \"200\" />\n <Button Content = \"Click Me\" Height = \"23\" \n HorizontalAlignment = \"Left\" Margin = \"96,88,0,0\" Name = \"button\" \n VerticalAlignment = \"Top\" Width = \"75\" Click = \"button_Click\" />\n </Grid>\n\t\n</UserControl>" }, { "code": null, "e": 5285, "s": 5183, "text": "Given below is the C# code for button click event in MyUserControl.cs file which updates the textbox." }, { "code": null, "e": 5744, "s": 5285, "text": "using System; \nusing System.Windows; \nusing System.Windows.Controls;\n\nnamespace XAMLUserControl {\n /// <summary> \n /// Interaction logic for MyUserControl.xaml\n /// </summary> \n\t\n public partial class MyUserControl : UserControl {\n public MyUserControl() {\n InitializeComponent(); \n }\n private void button_Click(object sender, RoutedEventArgs e) { \n txtBox.Text = \"You have just clicked the button\"; \n } \n }\n}" }, { "code": null, "e": 5811, "s": 5744, "text": "Here is implementation in MainWindow.xaml to add the user control." }, { "code": null, "e": 6162, "s": 5811, "text": "<Window x:Class = \"XAMLUserControl.MainWindow\" \n xmlns = \"http://schemas.microsoft.com/winfx/2006/xaml/presentation\"\n xmlns:x = \"http://schemas.microsoft.com/winfx/2006/xaml\"\n xmlns:control = \"clr-namespace:XAMLUserControl\" \n Title = \"MainWindow\" Height = \"350\" Width = \"525\">\n\t\n <Grid>\n <control:MyUserControl/>\n </Grid>\n\t\n</Window>" }, { "code": null, "e": 6246, "s": 6162, "text": "When you compile and execute the above code, it will produce the following output −" }, { "code": null, "e": 6332, "s": 6246, "text": "Now click on the \"Click Me\" button and you will see that the textbox text is updated." }, { "code": null, "e": 6493, "s": 6332, "text": "A custom control is a class which offers its own style and template which are normally defined in generic.xaml. Custom controls are used in following scenarios," }, { "code": null, "e": 6562, "s": 6493, "text": "If the control doesn't exist and you have to create it from scratch." }, { "code": null, "e": 6631, "s": 6562, "text": "If the control doesn't exist and you have to create it from scratch." }, { "code": null, "e": 6784, "s": 6631, "text": "If you want to extend or add functionality to a preexisting control by adding an extra property or an extra functionality to fit your specific scenario." }, { "code": null, "e": 6937, "s": 6784, "text": "If you want to extend or add functionality to a preexisting control by adding an extra property or an extra functionality to fit your specific scenario." }, { "code": null, "e": 6991, "s": 6937, "text": "If your controls need to support theming and styling." }, { "code": null, "e": 7045, "s": 6991, "text": "If your controls need to support theming and styling." }, { "code": null, "e": 7099, "s": 7045, "text": "If you want to share you control across applications." }, { "code": null, "e": 7153, "s": 7099, "text": "If you want to share you control across applications." }, { "code": null, "e": 7227, "s": 7153, "text": "Let’s take an example of custom control and follow the steps given below." }, { "code": null, "e": 7328, "s": 7227, "text": "Step 1 − Create a new WPF project and then right-click on your solution and select Add > New Item..." }, { "code": null, "e": 7429, "s": 7328, "text": "Step 1 − Create a new WPF project and then right-click on your solution and select Add > New Item..." }, { "code": null, "e": 7535, "s": 7429, "text": "Step 2 − The following dialog box will open. Now select Custom Control (WPF) and name it MyCustomControl." }, { "code": null, "e": 7641, "s": 7535, "text": "Step 2 − The following dialog box will open. Now select Custom Control (WPF) and name it MyCustomControl." }, { "code": null, "e": 7787, "s": 7641, "text": "Step 3 − Click on the Add button and you will see that two new files (Themes/Generic.xaml and MyCustomControl.cs) will be added in your solution." }, { "code": null, "e": 7933, "s": 7787, "text": "Step 3 − Click on the Add button and you will see that two new files (Themes/Generic.xaml and MyCustomControl.cs) will be added in your solution." }, { "code": null, "e": 8029, "s": 7933, "text": "Given below is the XAML code in which style is set for the custom control in Generic.xaml file." }, { "code": null, "e": 8498, "s": 8029, "text": "<ResourceDictionary \n xmlns = \"http://schemas.microsoft.com/winfx/2006/xaml/presentation\"\n xmlns:x = \"http://schemas.microsoft.com/winfx/2006/xaml\"\n xmlns:local = \"clr-namespace:XAMLCustomControls\">\n\t\n <Style TargetType = \"{x:Type local:MyCustomControl}\"\n BasedOn = \"{StaticResource {x:Type Button}}\"> \n <Setter Property = \"Background\" Value = \"LightSalmon\"/>\n <Setter Property = \"Foreground\" Value = \"Blue\"/>\n </Style>\n\t\n</ResourceDictionary>" }, { "code": null, "e": 8643, "s": 8498, "text": "Given below is the C# code for MyCustomControl class which is inherited from the button class and in the constructor, it overrides the metadata." }, { "code": null, "e": 8980, "s": 8643, "text": "using System; \nusing System.Windows; \nusing System.Windows.Controls;\n\nnamespace XAMLCustomControls {\n public class MyCustomControl : Button {\n static MyCustomControl() {\n DefaultStyleKeyProperty.OverrideMetadata(typeof(MyCustomControl), \n new FrameworkPropertyMetadata(typeof(MyCustomControl)));\n }\n }\n}" }, { "code": null, "e": 9089, "s": 8980, "text": "Given below is the custom control click event implementation in C# which updates the text of the text block." }, { "code": null, "e": 9554, "s": 9089, "text": "using System; \nusing System.Windows; \nusing System.Windows.Controls;\n\nnamespace XAMLCustomControls {\n /// <summary> \n /// Interaction logic for MainWindow.xaml \n /// </summary> \n\t\n public partial class MainWindow : Window {\n public MainWindow() { \n InitializeComponent(); \n }\n private void customControl_Click(object sender, RoutedEventArgs e) {\n txtBlock.Text = \"You have just click your custom control\"; \n } \n }\n}" }, { "code": null, "e": 9643, "s": 9554, "text": "Here is the implementation in MainWindow.xaml to add the custom control and a TextBlock." }, { "code": null, "e": 10191, "s": 9643, "text": "<Window x:Class = \"XAMLCustomControls.MainWindow\" \n xmlns = \"http://schemas.microsoft.com/winfx/2006/xaml/presentation\"\n xmlns:x = \"http://schemas.microsoft.com/winfx/2006/xaml\"\n xmlns:control = \"clr-namespace:XAMLCustomControls\" Title = \"MainWindow\"\n Height = \"350\" Width = \"604\">\n\t\n <StackPanel>\n <control:MyCustomControl x:Name = \"customControl\" \n Content = \"Click Me\" Width = \"70\" Margin = \"10\" Click = \"customControl_Click\"/>\n <TextBlock Name = \"txtBlock\" Width = \"250\" Height = \"30\"/>\n </StackPanel>\n\t\n</Window>" }, { "code": null, "e": 10349, "s": 10191, "text": "When you compile and execute the above code, it will produce the following output. Observe the output contains a custom control which is a customized button." }, { "code": null, "e": 10435, "s": 10349, "text": "Now click on the customized button. You will see that the text block text is updated." }, { "code": null, "e": 10442, "s": 10435, "text": " Print" }, { "code": null, "e": 10453, "s": 10442, "text": " Add Notes" } ]
Remember and copy passwords to clipboard using Pyperclip module in Python - GeeksforGeeks
19 Feb, 2020 It is always a difficult job to remember all our passwords for different accounts. So this is a really simple Python program which uses sys module to obtain account name as argument form the command terminal and pyperclip module to paste the respective account’s password to the clipboard. Pyperclip module does not come pre-installed with Python. To install it type the below command in the terminal. pip install pyperclip Examples : Command terminal Input : name_of_program.py facebookCommand terminal Output : Password : shubham456, for facebook account has been copied to the clipboard Command terminal Input : name_of_program.py AyushiCommand terminal Output : No such account record exists Approach : We initialize a dictionary with keys as account names and passwords as their values. Here sys.argv is the list of command-line arguments passed to the Python program, sys.argv[0] is the name of the Python program and sys.argv[1] corresponds to the first argument written by the user. Then the program checks whether such an account (key) exists in the dictionary or not if such an account exists then it copies the password to the clipboard and displays a corresponding message. If no such account exists then the program displays a message that “No such account record exits”. Below is the implementation of above approach : import sys, pyperclip # function to copy account passwords# to clipboarddef manager(account): # dictionary in which keys are account # name and values are their passwords passwords ={ "email" : "Ayushi123", "facebook" : "shubham456", "instagram" : "Ayushi789", "geeksforgeeks" : "Ninja1" } if account in passwords: # copies password to clipboard pyperclip.copy(passwords[account]) print("Password :", passwords[account], ", for", account, "account", "has been copied to the clipboard") else : print("No such account record exits") # Driver functionif __name__ == "__main__": # command line argument that is name of # account passed to program through cmd account = sys.argv[1] # calling manager function manager(account) # This article has been contributed by# Shubham Singh Chauhan Output : python-utility Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Read a file line by line in Python How to Install PIP on Windows ? Enumerate() in Python Different ways to create Pandas Dataframe Iterate over a list in Python Python String | replace() Reading and Writing to text files in Python *args and **kwargs in Python Create a Pandas DataFrame from Lists
[ { "code": null, "e": 26450, "s": 26422, "text": "\n19 Feb, 2020" }, { "code": null, "e": 26740, "s": 26450, "text": "It is always a difficult job to remember all our passwords for different accounts. So this is a really simple Python program which uses sys module to obtain account name as argument form the command terminal and pyperclip module to paste the respective account’s password to the clipboard." }, { "code": null, "e": 26852, "s": 26740, "text": "Pyperclip module does not come pre-installed with Python. To install it type the below command in the terminal." }, { "code": null, "e": 26874, "s": 26852, "text": "pip install pyperclip" }, { "code": null, "e": 26885, "s": 26874, "text": "Examples :" }, { "code": null, "e": 27040, "s": 26885, "text": "Command terminal Input : name_of_program.py facebookCommand terminal Output : Password : shubham456, for facebook account has been copied to the clipboard" }, { "code": null, "e": 27146, "s": 27040, "text": "Command terminal Input : name_of_program.py AyushiCommand terminal Output : No such account record exists" }, { "code": null, "e": 27441, "s": 27146, "text": "Approach : We initialize a dictionary with keys as account names and passwords as their values. Here sys.argv is the list of command-line arguments passed to the Python program, sys.argv[0] is the name of the Python program and sys.argv[1] corresponds to the first argument written by the user." }, { "code": null, "e": 27735, "s": 27441, "text": "Then the program checks whether such an account (key) exists in the dictionary or not if such an account exists then it copies the password to the clipboard and displays a corresponding message. If no such account exists then the program displays a message that “No such account record exits”." }, { "code": null, "e": 27783, "s": 27735, "text": "Below is the implementation of above approach :" }, { "code": "import sys, pyperclip # function to copy account passwords# to clipboarddef manager(account): # dictionary in which keys are account # name and values are their passwords passwords ={ \"email\" : \"Ayushi123\", \"facebook\" : \"shubham456\", \"instagram\" : \"Ayushi789\", \"geeksforgeeks\" : \"Ninja1\" } if account in passwords: # copies password to clipboard pyperclip.copy(passwords[account]) print(\"Password :\", passwords[account], \", for\", account, \"account\", \"has been copied to the clipboard\") else : print(\"No such account record exits\") # Driver functionif __name__ == \"__main__\": # command line argument that is name of # account passed to program through cmd account = sys.argv[1] # calling manager function manager(account) # This article has been contributed by# Shubham Singh Chauhan", "e": 28762, "s": 27783, "text": null }, { "code": null, "e": 28771, "s": 28762, "text": "Output :" }, { "code": null, "e": 28786, "s": 28771, "text": "python-utility" }, { "code": null, "e": 28793, "s": 28786, "text": "Python" }, { "code": null, "e": 28891, "s": 28793, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28909, "s": 28891, "text": "Python Dictionary" }, { "code": null, "e": 28944, "s": 28909, "text": "Read a file line by line in Python" }, { "code": null, "e": 28976, "s": 28944, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 28998, "s": 28976, "text": "Enumerate() in Python" }, { "code": null, "e": 29040, "s": 28998, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 29070, "s": 29040, "text": "Iterate over a list in Python" }, { "code": null, "e": 29096, "s": 29070, "text": "Python String | replace()" }, { "code": null, "e": 29140, "s": 29096, "text": "Reading and Writing to text files in Python" }, { "code": null, "e": 29169, "s": 29140, "text": "*args and **kwargs in Python" } ]
How to get website links using Invoke-WebRequest in PowerShell?
To get the links present on the website using PowerShell, we can first retrieve the data from the webpage using the Invoke-WebRequest cmdlet. $req = Invoke-WebRequest -uri "https://theautomationcode.com" $req To retrieve only links we can use that property and there you will also find some sub-properties like InnerHTML, Innertext, href, etc as shown in the output. $req = Invoke-WebRequest -uri "https://theautomationcode.com" $req.Links innerHTML : Scripts innerText : Scripts outerHTML : <A href="https://theautomationcode.com/scripts/">Scripts</A> outerText : Scripts tagName : A href : https://theautomationcode.com/scripts/ We need only links so we will use the href property. $req.Links | Select -ExpandProperty href https://theautomationcode.com/2020/11/ https://theautomationcode.com/author/chiragce17/ https://theautomationcode.com/category/powershell/ https://theautomationcode.com/category/troubleshooting/
[ { "code": null, "e": 1204, "s": 1062, "text": "To get the links present on the website using PowerShell, we can first retrieve the data from the webpage using the Invoke-WebRequest cmdlet." }, { "code": null, "e": 1271, "s": 1204, "text": "$req = Invoke-WebRequest -uri \"https://theautomationcode.com\"\n$req" }, { "code": null, "e": 1429, "s": 1271, "text": "To retrieve only links we can use that property and there you will also find some sub-properties like InnerHTML, Innertext, href, etc as shown in the output." }, { "code": null, "e": 1502, "s": 1429, "text": "$req = Invoke-WebRequest -uri \"https://theautomationcode.com\"\n$req.Links" }, { "code": null, "e": 1702, "s": 1502, "text": "innerHTML : Scripts\ninnerText : Scripts\nouterHTML : <A href=\"https://theautomationcode.com/scripts/\">Scripts</A>\nouterText : Scripts\ntagName : A\nhref : https://theautomationcode.com/scripts/ " }, { "code": null, "e": 1755, "s": 1702, "text": "We need only links so we will use the href property." }, { "code": null, "e": 1796, "s": 1755, "text": "$req.Links | Select -ExpandProperty href" }, { "code": null, "e": 1991, "s": 1796, "text": "https://theautomationcode.com/2020/11/\nhttps://theautomationcode.com/author/chiragce17/\nhttps://theautomationcode.com/category/powershell/\nhttps://theautomationcode.com/category/troubleshooting/" } ]
Swap Column Values in SQL Server - GeeksforGeeks
05 Nov, 2020 Introduction (Swap Column Values in SQL Server) :If you are a developer and have learned the programming languages, you might think that you will need a third variable or another temporary storage location to swap the values. Here, as you are a SQL Server DBA, you can simply swap them using a single update statement. Example and Application features :It happens that SQL user might enter incorrect values in the database columns, the next task is to swap those values. Syntax :Syntax to write a query to swap column values in SQL server. UPDATE [tablename] SET [col1] = [col2], [col2] = [col1] GO Let us suppose we need to swap columns in any table in the SQL server. Example –Let us suppose we have below the table “geek_demo”. Select * from geek_demo ; Output : Now, to update the column or to swap the column used the following query given below. UPDATE [geek_demo] SET [FirstName] = [LastName], [LastName] = [FirstName] GO Now, let’s see the output. Select * from geek_demo ; Output : SQL-Server SQL SQL Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. SQL Trigger | Student Database SQL Interview Questions CTE in SQL How to Update Multiple Columns in Single Update Statement in SQL? SQL | GROUP BY Difference between DELETE, DROP and TRUNCATE SQL | Views MySQL | Group_CONCAT() Function How to Create a Table With Multiple Foreign Keys in SQL? Difference between DELETE and TRUNCATE
[ { "code": null, "e": 25285, "s": 25257, "text": "\n05 Nov, 2020" }, { "code": null, "e": 25604, "s": 25285, "text": "Introduction (Swap Column Values in SQL Server) :If you are a developer and have learned the programming languages, you might think that you will need a third variable or another temporary storage location to swap the values. Here, as you are a SQL Server DBA, you can simply swap them using a single update statement." }, { "code": null, "e": 25756, "s": 25604, "text": "Example and Application features :It happens that SQL user might enter incorrect values in the database columns, the next task is to swap those values." }, { "code": null, "e": 25825, "s": 25756, "text": "Syntax :Syntax to write a query to swap column values in SQL server." }, { "code": null, "e": 25888, "s": 25825, "text": "UPDATE [tablename]\nSET [col1] = [col2],\n [col2] = [col1]\nGO\n" }, { "code": null, "e": 25959, "s": 25888, "text": "Let us suppose we need to swap columns in any table in the SQL server." }, { "code": null, "e": 26020, "s": 25959, "text": "Example –Let us suppose we have below the table “geek_demo”." }, { "code": null, "e": 26047, "s": 26020, "text": "Select * from geek_demo ;\n" }, { "code": null, "e": 26056, "s": 26047, "text": "Output :" }, { "code": null, "e": 26142, "s": 26056, "text": "Now, to update the column or to swap the column used the following query given below." }, { "code": null, "e": 26221, "s": 26142, "text": "UPDATE [geek_demo]\nSET [FirstName] = [LastName], \n[LastName] = [FirstName]\nGO\n" }, { "code": null, "e": 26248, "s": 26221, "text": "Now, let’s see the output." }, { "code": null, "e": 26274, "s": 26248, "text": "Select * from geek_demo ;" }, { "code": null, "e": 26283, "s": 26274, "text": "Output :" }, { "code": null, "e": 26294, "s": 26283, "text": "SQL-Server" }, { "code": null, "e": 26298, "s": 26294, "text": "SQL" }, { "code": null, "e": 26302, "s": 26298, "text": "SQL" }, { "code": null, "e": 26400, "s": 26302, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26431, "s": 26400, "text": "SQL Trigger | Student Database" }, { "code": null, "e": 26455, "s": 26431, "text": "SQL Interview Questions" }, { "code": null, "e": 26466, "s": 26455, "text": "CTE in SQL" }, { "code": null, "e": 26532, "s": 26466, "text": "How to Update Multiple Columns in Single Update Statement in SQL?" }, { "code": null, "e": 26547, "s": 26532, "text": "SQL | GROUP BY" }, { "code": null, "e": 26592, "s": 26547, "text": "Difference between DELETE, DROP and TRUNCATE" }, { "code": null, "e": 26604, "s": 26592, "text": "SQL | Views" }, { "code": null, "e": 26636, "s": 26604, "text": "MySQL | Group_CONCAT() Function" }, { "code": null, "e": 26693, "s": 26636, "text": "How to Create a Table With Multiple Foreign Keys in SQL?" } ]
Count Pairs Of Consecutive Zeros - GeeksforGeeks
22 Jan, 2022 Consider a sequence that starts with a 1 on a machine. At each successive step, the machine simultaneously transforms each digit 0 into the sequence 10 and each digit 1 into the sequence 01. After the first time step, the sequence 01 is obtained; after the second, the sequence 1001, after the third, the sequence 01101001 and so on.How many pairs of consecutive zeros will appear in the sequence after n steps?Examples : Input : Number of steps = 3 Output: 1 // After 3rd step sequence will be 01101001 Input : Number of steps = 4 Output: 3 // After 4rd step sequence will be 1001011001101001 Input : Number of steps = 5 Output: 5 // After 3rd step sequence will be 01101001100101101001011001101001 This is a simple reasoning problem. If we see the sequence very carefully , then we will be able to find a pattern for given sequence. If n=1 sequence will be {01} so number of pairs of consecutive zeros are 0, If n = 2 sequence will be {1001} so number of pairs of consecutive zeros are 1, If n=3 sequence will be {01101001} so number of pairs of consecutive zeros are 1, If n=4 sequence will be {1001011001101001} so number of pairs of consecutive zeros are 3.So length of the sequence will always be a power of 2. We can see after length 12 sequence is repeating and in lengths of 12. And in a segment of length 12, there are total 2 pairs of consecutive zeros. Hence we can generalize the given pattern q = (2^n/12) and total pairs of consecutive zeros will be 2*q+1. C++ Java Python3 C# PHP Javascript // C++ program to find number of consecutive// 0s in a sequence#include<bits/stdc++.h>using namespace std; // Function to find number of consecutive Zero Pairs// Here n is number of stepsint consecutiveZeroPairs(int n){ // Base cases if (n==1) return 0; if (n==2 || n==3) return 1; // Calculating how many times divisible by 12, i.e., // count total number repeating segments of length 12 int q = (pow(2, n) / 12); // number of consecutive Zero Pairs return 2 * q + 1;} // Driver codeint main(){ int n = 5; cout << consecutiveZeroPairs(n) << endl; return 0;} //Java program to find number of// consecutive 0s in a sequenceimport java.io.*;import java.math.*; class GFG { // Function to find number of consecutive // Zero Pairs. Here n is number of steps static int consecutiveZeroPairs(int n) { // Base cases if (n == 1) return 0; if (n == 2 || n == 3) return 1; // Calculating how many times divisible // by 12, i.e.,count total number // repeating segments of length 12 int q = ((int)(Math.pow(2, n)) / 12); // number of consecutive Zero Pairs return (2 * q + 1); } // Driver code public static void main(String args[]) { int n = 5; System.out.println(consecutiveZeroPairs(n)); }} // This code is contributed by Nikita Tiwari. # Python program to find number of# consecutive 0s in a sequenceimport math # Function to find number of consecutive# Zero Pairs. Here n is number of stepsdef consecutiveZeroPairs(n) : # Base cases if (n == 1) : return 0 if (n == 2 or n == 3) : return 1 # Calculating how many times divisible # by 12, i.e.,count total number # repeating segments of length 12 q =(int) (pow(2,n) / 12) # number of consecutive Zero Pairs return 2 * q + 1 # Driver coden = 5print (consecutiveZeroPairs(n)) #This code is contributed by Nikita Tiwari. // C# program to find number of// consecutive 0s in a sequenceusing System; class GFG { // Function to find number of // consecutive Zero Pairs. // Here n is number of steps static int consecutiveZeroPairs(int n) { // Base cases if (n == 1) return 0; if (n == 2 || n == 3) return 1; // Calculating how many times divisible // by 12, i.e.,count total number // repeating segments of length 12 int q = ((int)(Math.Pow(2, n)) / 12); // number of consecutive Zero Pairs return (2 * q + 1); } // Driver Code public static void Main() { int n = 5; Console.Write(consecutiveZeroPairs(n)); }} // This code is contributed by Nitin mittal. <?php// PHP program to find number// of consecutive 0s in a sequence // Function to find number// of consecutive Zero Pairs// Here n is number of stepsfunction consecutiveZeroPairs($n){ // Base cases if ($n == 1) return 0; if ($n == 2 || $n == 3) return 1; // Calculating how many times // divisible by 12, i.e., count // total number repeating segments // of length 12 $q = floor(pow(2, $n) / 12); // number of consecutive Zero Pairs return 2 * $q + 1;} // Driver code$n = 5;echo consecutiveZeroPairs($n) ; // This code is contributed// by nitin mittal.?> <script>//javascript program to find number of// consecutive 0s in a sequence // Function to find number of consecutive // Zero Pairs. Here n is number of steps function consecutiveZeroPairs(n) { // Base cases if (n == 1) return 0; if (n == 2 || n == 3) return 1; // Calculating how many times divisible // by 12, i.e.,count total number // repeating segments of length 12 var q =(parseInt((Math.pow(2, n)) / 12)); // number of consecutive Zero Pairs return (2 * q + 1); } // Driver code var n = 5; document.write(consecutiveZeroPairs(n)); // This code is contributed by umadevi9616</script> Output : 5 This article is contributed by Shashank Mishra ( Gullu ). this article is reviewed by team GeeksForGeeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. nitin mittal umadevi9616 amartyaghoshgfg Combinatorial Combinatorial Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Combinations with repetitions Ways to sum to N using Natural Numbers up to K with repetitions allowed Largest number by rearranging digits of a given positive or negative number Given number of matches played, find number of teams in tournament Generate all possible combinations of at most X characters from a given array Number of Simple Graph with N Vertices and M Edges Largest substring with same Characters Minimum cost to convert 1 to N by multiplying X or right rotation of digits Print all Strong numbers less than or equal to N Combinations from n arrays picking one element from each array
[ { "code": null, "e": 25398, "s": 25370, "text": "\n22 Jan, 2022" }, { "code": null, "e": 25822, "s": 25398, "text": "Consider a sequence that starts with a 1 on a machine. At each successive step, the machine simultaneously transforms each digit 0 into the sequence 10 and each digit 1 into the sequence 01. After the first time step, the sequence 01 is obtained; after the second, the sequence 1001, after the third, the sequence 01101001 and so on.How many pairs of consecutive zeros will appear in the sequence after n steps?Examples : " }, { "code": null, "e": 26104, "s": 25822, "text": "Input : Number of steps = 3\nOutput: 1\n// After 3rd step sequence will be 01101001\n\nInput : Number of steps = 4\nOutput: 3\n// After 4rd step sequence will be 1001011001101001\n\nInput : Number of steps = 5\nOutput: 5\n// After 3rd step sequence will be 01101001100101101001011001101001" }, { "code": null, "e": 26880, "s": 26106, "text": "This is a simple reasoning problem. If we see the sequence very carefully , then we will be able to find a pattern for given sequence. If n=1 sequence will be {01} so number of pairs of consecutive zeros are 0, If n = 2 sequence will be {1001} so number of pairs of consecutive zeros are 1, If n=3 sequence will be {01101001} so number of pairs of consecutive zeros are 1, If n=4 sequence will be {1001011001101001} so number of pairs of consecutive zeros are 3.So length of the sequence will always be a power of 2. We can see after length 12 sequence is repeating and in lengths of 12. And in a segment of length 12, there are total 2 pairs of consecutive zeros. Hence we can generalize the given pattern q = (2^n/12) and total pairs of consecutive zeros will be 2*q+1. " }, { "code": null, "e": 26884, "s": 26880, "text": "C++" }, { "code": null, "e": 26889, "s": 26884, "text": "Java" }, { "code": null, "e": 26897, "s": 26889, "text": "Python3" }, { "code": null, "e": 26900, "s": 26897, "text": "C#" }, { "code": null, "e": 26904, "s": 26900, "text": "PHP" }, { "code": null, "e": 26915, "s": 26904, "text": "Javascript" }, { "code": "// C++ program to find number of consecutive// 0s in a sequence#include<bits/stdc++.h>using namespace std; // Function to find number of consecutive Zero Pairs// Here n is number of stepsint consecutiveZeroPairs(int n){ // Base cases if (n==1) return 0; if (n==2 || n==3) return 1; // Calculating how many times divisible by 12, i.e., // count total number repeating segments of length 12 int q = (pow(2, n) / 12); // number of consecutive Zero Pairs return 2 * q + 1;} // Driver codeint main(){ int n = 5; cout << consecutiveZeroPairs(n) << endl; return 0;}", "e": 27523, "s": 26915, "text": null }, { "code": "//Java program to find number of// consecutive 0s in a sequenceimport java.io.*;import java.math.*; class GFG { // Function to find number of consecutive // Zero Pairs. Here n is number of steps static int consecutiveZeroPairs(int n) { // Base cases if (n == 1) return 0; if (n == 2 || n == 3) return 1; // Calculating how many times divisible // by 12, i.e.,count total number // repeating segments of length 12 int q = ((int)(Math.pow(2, n)) / 12); // number of consecutive Zero Pairs return (2 * q + 1); } // Driver code public static void main(String args[]) { int n = 5; System.out.println(consecutiveZeroPairs(n)); }} // This code is contributed by Nikita Tiwari.", "e": 28331, "s": 27523, "text": null }, { "code": "# Python program to find number of# consecutive 0s in a sequenceimport math # Function to find number of consecutive# Zero Pairs. Here n is number of stepsdef consecutiveZeroPairs(n) : # Base cases if (n == 1) : return 0 if (n == 2 or n == 3) : return 1 # Calculating how many times divisible # by 12, i.e.,count total number # repeating segments of length 12 q =(int) (pow(2,n) / 12) # number of consecutive Zero Pairs return 2 * q + 1 # Driver coden = 5print (consecutiveZeroPairs(n)) #This code is contributed by Nikita Tiwari.", "e": 28906, "s": 28331, "text": null }, { "code": "// C# program to find number of// consecutive 0s in a sequenceusing System; class GFG { // Function to find number of // consecutive Zero Pairs. // Here n is number of steps static int consecutiveZeroPairs(int n) { // Base cases if (n == 1) return 0; if (n == 2 || n == 3) return 1; // Calculating how many times divisible // by 12, i.e.,count total number // repeating segments of length 12 int q = ((int)(Math.Pow(2, n)) / 12); // number of consecutive Zero Pairs return (2 * q + 1); } // Driver Code public static void Main() { int n = 5; Console.Write(consecutiveZeroPairs(n)); }} // This code is contributed by Nitin mittal.", "e": 29677, "s": 28906, "text": null }, { "code": "<?php// PHP program to find number// of consecutive 0s in a sequence // Function to find number// of consecutive Zero Pairs// Here n is number of stepsfunction consecutiveZeroPairs($n){ // Base cases if ($n == 1) return 0; if ($n == 2 || $n == 3) return 1; // Calculating how many times // divisible by 12, i.e., count // total number repeating segments // of length 12 $q = floor(pow(2, $n) / 12); // number of consecutive Zero Pairs return 2 * $q + 1;} // Driver code$n = 5;echo consecutiveZeroPairs($n) ; // This code is contributed// by nitin mittal.?>", "e": 30280, "s": 29677, "text": null }, { "code": "<script>//javascript program to find number of// consecutive 0s in a sequence // Function to find number of consecutive // Zero Pairs. Here n is number of steps function consecutiveZeroPairs(n) { // Base cases if (n == 1) return 0; if (n == 2 || n == 3) return 1; // Calculating how many times divisible // by 12, i.e.,count total number // repeating segments of length 12 var q =(parseInt((Math.pow(2, n)) / 12)); // number of consecutive Zero Pairs return (2 * q + 1); } // Driver code var n = 5; document.write(consecutiveZeroPairs(n)); // This code is contributed by umadevi9616</script>", "e": 30994, "s": 30280, "text": null }, { "code": null, "e": 31005, "s": 30994, "text": "Output : " }, { "code": null, "e": 31007, "s": 31005, "text": "5" }, { "code": null, "e": 31239, "s": 31007, "text": "This article is contributed by Shashank Mishra ( Gullu ). this article is reviewed by team GeeksForGeeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. " }, { "code": null, "e": 31252, "s": 31239, "text": "nitin mittal" }, { "code": null, "e": 31264, "s": 31252, "text": "umadevi9616" }, { "code": null, "e": 31280, "s": 31264, "text": "amartyaghoshgfg" }, { "code": null, "e": 31294, "s": 31280, "text": "Combinatorial" }, { "code": null, "e": 31308, "s": 31294, "text": "Combinatorial" }, { "code": null, "e": 31406, "s": 31308, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 31415, "s": 31406, "text": "Comments" }, { "code": null, "e": 31428, "s": 31415, "text": "Old Comments" }, { "code": null, "e": 31458, "s": 31428, "text": "Combinations with repetitions" }, { "code": null, "e": 31530, "s": 31458, "text": "Ways to sum to N using Natural Numbers up to K with repetitions allowed" }, { "code": null, "e": 31606, "s": 31530, "text": "Largest number by rearranging digits of a given positive or negative number" }, { "code": null, "e": 31673, "s": 31606, "text": "Given number of matches played, find number of teams in tournament" }, { "code": null, "e": 31751, "s": 31673, "text": "Generate all possible combinations of at most X characters from a given array" }, { "code": null, "e": 31802, "s": 31751, "text": "Number of Simple Graph with N Vertices and M Edges" }, { "code": null, "e": 31841, "s": 31802, "text": "Largest substring with same Characters" }, { "code": null, "e": 31917, "s": 31841, "text": "Minimum cost to convert 1 to N by multiplying X or right rotation of digits" }, { "code": null, "e": 31966, "s": 31917, "text": "Print all Strong numbers less than or equal to N" } ]
C# program to determine if any two integers in array sum to given integer
The following is our array − int[] arr = new int[] { 7, 4, 6, 2 }; Let’s say the given intger that should be equal to sum of two other integers is − int res = 8; To get the sum and find the equality. for (int i = 0; i < arr.Length; i++) { for (int j = 0; j < arr.Length; j++) { if (i != j) { int sum = arr[i] + arr[j]; if (sum == res) { Console.WriteLine(arr[i]); } } } } using System; using System.Collections.Generic; namespace Demo { public class Program { public static void Main(string[] args) { int[] arr = new int[] { 7, 4, 6, 2 }; // given integer int res = 8; Console.WriteLine("Given Integer {0}: ", res); Console.WriteLine("Sum of:"); for (int i = 0; i < arr.Length; i++) { for (int j = 0; j < arr.Length; j++) { if (i != j) { int sum = arr[i] + arr[j]; if (sum == res) { Console.WriteLine(arr[i]); } } } } } } }
[ { "code": null, "e": 1091, "s": 1062, "text": "The following is our array −" }, { "code": null, "e": 1141, "s": 1091, "text": "int[] arr = new int[] {\n 7,\n 4,\n 6,\n 2\n};" }, { "code": null, "e": 1223, "s": 1141, "text": "Let’s say the given intger that should be equal to sum of two other integers is −" }, { "code": null, "e": 1236, "s": 1223, "text": "int res = 8;" }, { "code": null, "e": 1274, "s": 1236, "text": "To get the sum and find the equality." }, { "code": null, "e": 1503, "s": 1274, "text": "for (int i = 0; i < arr.Length; i++) {\n for (int j = 0; j < arr.Length; j++) {\n if (i != j) {\n int sum = arr[i] + arr[j];\n if (sum == res) {\n Console.WriteLine(arr[i]);\n }\n }\n }\n}" }, { "code": null, "e": 2223, "s": 1503, "text": "using System;\nusing System.Collections.Generic;\n\nnamespace Demo {\n public class Program {\n public static void Main(string[] args) {\n int[] arr = new int[] {\n 7,\n 4,\n 6,\n 2\n };\n // given integer\n int res = 8;\n Console.WriteLine(\"Given Integer {0}: \", res);\n Console.WriteLine(\"Sum of:\");\n for (int i = 0; i < arr.Length; i++) {\n for (int j = 0; j < arr.Length; j++) {\n if (i != j) {\n int sum = arr[i] + arr[j];\n if (sum == res) {\n Console.WriteLine(arr[i]);\n }\n }\n }\n }\n }\n }\n}" } ]
Built-in objects in Python (builtins)
The builtins module is automatically loaded every time Python interpreter starts, either as a top level execution environment or as interactive session. The Object class, which happens to be the base class for all Python objects, is defined in this module. All built-in data type classes such as numbers, string, list etc are defined in this module. The BaseException class, as well as all built-in exceptions, are also defined in it. Further, all built-in functions are also defined in the built-ins module. Since this module is imported in the current session automatically, normally it is not imported explicitly. All the built-in functions used in the executable code are by default considered to be from built-ins module. For example >>> len('hello') 5 is implicitly equivalent to >>> import builtins >>> builtins.len('hello') 5 However, explicit import of this module is required when there is also a user defined function of the same name as built-in function. Python interpreter gives higher precedence to user defined function. Hence, if the code contains both user defined as well as built-in function of the same name, the latter must be prefixed with built-ins module. def len(string): print ('local len() function') print ('calling len() function in builtins module') import builtins l = builtins.len(string) print ('length:',l) string = "Hello World" len(string) Output local len() function calling len() function in builtins module length: 11 Most modules have the name __builtins__ made available as part of their globals. The value of __builtins__ is normally either this module or the value of this module’s __dict__attribute. >>> import math >>> globals() {'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <class '_frozen_importlib.BuiltinImporter'>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>, 'math': <module 'math' (built-in)>}
[ { "code": null, "e": 1571, "s": 1062, "text": "The builtins module is automatically loaded every time Python interpreter starts, either as a top level execution environment or as interactive session. The Object class, which happens to be the base class for all Python objects, is defined in this module. All built-in data type classes such as numbers, string, list etc are defined in this module. The BaseException class, as well as all built-in exceptions, are also defined in it. Further, all built-in functions are also defined in the built-ins module." }, { "code": null, "e": 1801, "s": 1571, "text": "Since this module is imported in the current session automatically, normally it is not imported explicitly. All the built-in functions used in the executable code are by default considered to be from built-ins module. For example" }, { "code": null, "e": 1820, "s": 1801, "text": ">>> len('hello')\n5" }, { "code": null, "e": 1848, "s": 1820, "text": "is implicitly equivalent to" }, { "code": null, "e": 1896, "s": 1848, "text": ">>> import builtins\n>>> builtins.len('hello')\n5" }, { "code": null, "e": 2243, "s": 1896, "text": "However, explicit import of this module is required when there is also a user defined function of the same name as built-in function. Python interpreter gives higher precedence to user defined function. Hence, if the code contains both user defined as well as built-in function of the same name, the latter must be prefixed with built-ins module." }, { "code": null, "e": 2439, "s": 2243, "text": "def len(string):\nprint ('local len() function')\nprint ('calling len() function in builtins module')\nimport builtins\nl = builtins.len(string)\nprint ('length:',l)\nstring = \"Hello World\"\nlen(string)" }, { "code": null, "e": 2446, "s": 2439, "text": "Output" }, { "code": null, "e": 2520, "s": 2446, "text": "local len() function\ncalling len() function in builtins module\nlength: 11" }, { "code": null, "e": 2707, "s": 2520, "text": "Most modules have the name __builtins__ made available as part of their globals. The value of __builtins__ is normally either this module or the value of this module’s __dict__attribute." }, { "code": null, "e": 2984, "s": 2707, "text": ">>> import math\n>>> globals()\n{'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <class '_frozen_importlib.BuiltinImporter'>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>, 'math': <module 'math' (built-in)>}" } ]
How can I loop over entries in JSON using Python?
You can parse JSON files using the json module in Python. This module parses the json and puts it in a dict. You can then get the values from this like a normal dict. For example, if you have a json with the following content − { "id": "file", "value": "File", "popup": { "menuitem": [ {"value": "New", "onclick": "CreateNewDoc()"}, {"value": "Open", "onclick": "OpenDoc()"}, {"value": "Close", "onclick": "CloseDoc()"} ] } } You can load it in your python program and loop over its keys in the following way − import json f = open('data.json') data = json.load(f) f.close() # Now you can use data as a normal dict: for (k, v) in data.items(): print("Key: " + k) print("Value: " + str(v)) This will give the output − Key: id Value: file Key: value Value: File Key: popup Value: {'menuitem': [{'value': 'New', 'onclick': 'CreateNewDoc()'}, {'value': 'Open', 'onclick': 'OpenDoc()'}, {'value': 'Close', 'onclick': 'CloseDoc()'}]}
[ { "code": null, "e": 1290, "s": 1062, "text": "You can parse JSON files using the json module in Python. This module parses the json and puts it in a dict. You can then get the values from this like a normal dict. For example, if you have a json with the following content −" }, { "code": null, "e": 1530, "s": 1290, "text": "{\n \"id\": \"file\",\n \"value\": \"File\",\n \"popup\": {\n \"menuitem\": [\n {\"value\": \"New\", \"onclick\": \"CreateNewDoc()\"},\n {\"value\": \"Open\", \"onclick\": \"OpenDoc()\"},\n {\"value\": \"Close\", \"onclick\": \"CloseDoc()\"}\n ]\n }\n}" }, { "code": null, "e": 1615, "s": 1530, "text": "You can load it in your python program and loop over its keys in the following way −" }, { "code": null, "e": 1800, "s": 1615, "text": "import json\nf = open('data.json')\ndata = json.load(f)\nf.close()\n\n# Now you can use data as a normal dict:\nfor (k, v) in data.items():\n print(\"Key: \" + k)\n print(\"Value: \" + str(v))" }, { "code": null, "e": 1828, "s": 1800, "text": "This will give the output −" }, { "code": null, "e": 2041, "s": 1828, "text": "Key: id\nValue: file\nKey: value\nValue: File\nKey: popup\nValue: {'menuitem': [{'value': 'New', 'onclick': 'CreateNewDoc()'}, {'value': 'Open', 'onclick': 'OpenDoc()'}, {'value': 'Close', 'onclick': 'CloseDoc()'}]}\n\n" } ]
A Deep Dive into Lane Detection with Hough Transform | by Nushaine Ferdinand | Towards Data Science
Lane line detection is one of the essential components of self-driving cars. There are many approaches to doing this. Here, we’ll look at the simplest approach using Hough Transform. Alright, let’s dive into it! So before we get started, we need a place to write our code. The IDE (environment) that I recommend is Jupyter Notebooks. It has a nice, minimalistic interface yet is really powerful at the same time. Also, Jupyter Notebooks are awesome for visualizing data. Here’s the download link: docs.anaconda.com Now that you have Anaconda installed and Jupyter is working, let’s get some data! You can download the test images, videos and source code for the algorithm from my Github repo. Now we’re ready to build the algorithm. This article is divided into three parts: Part 1: Gausian Blur + Canny Edge Detection Part 2: Hough Transform Part 3: Optimizing + Displaying the Lines Parts 1 and 3 are focused on coding and Part 2 is more theory-oriented. Okay, let's dive into the first part. The first thing we need to do is import required libraries. import numpy as npimport cv2import matplotlib.pyplot as plt Here we imported 3 libraries: Line 1: Numpy is used for performing mathematical computations. We’re gonna use it to create and manipulate arrays Line 2: OpenCV is a library used to make computer vision able for anyone to do (a.k.a simplifying them for beginners). Line 3: Matplotlib is used to visualize the images. Next, let’s load in an image from our collection to test our algorithm image_path = r"D:\users\new owner\Desktop\TKS\Article Lane Detection\udacity\solidWhiteCurve.jpg"image1 = cv2.imread(image_path)plt.imshow(image1) Here, we load the image into the notebook in line 4, then we’re going to read the image and visualize it in lines 5 and 6. Now its time to manipulate the image. We’re going to do three things here in particular: def grey(image): return cv2.cvtColor(image, cv2.COLOR_RGB2GRAY)def gauss(image): return cv2.GaussianBlur(image, (5, 5), 0)def canny(image): edges = cv2.Canny(image,50,150) return edges Okay, in this last code block we defined 3 functions: Greyscale the image: This helps by increasing the contrast of the colours, making it easier to identify changes in pixel intensity. Gaussian Filter: The purpose of the gaussian filter is to reduce noise in the image. We do this because the gradients in Canny are really sensitive to noise, so we want to eliminate the most noise possible. The cv2.GaussianBlur function takes three parameters: The img parameter defines the image we’re going to normalize (reduce noise). The ksize parameter defines the dimensions of the kernel which we’re going to convolute (pass over) the image. This kernel convolution is how the noise reduction takes place. This function uses a kernel called the Gaussian Kernel, which is used for normalizing images. The sigma parameter defines the standard deviation along the x-axis. The standard deviation measures the spread of the pixels in the image. We want the pixel spread to be consistent, hence a 0 standard deviation. Canny: This is where we detect the edges in the image. What it does is it calculates the change of pixel intensity (change in brightness) in a certain section in an image. Luckily, this is made very simple by OpenCV. The cv2.Canny function has 3 parameters, (img, threshold-1, threshold-2). The img parameter defines the image that we're going to detect edges on. The threshold-1 parameter filters all gradients lower than this number (they aren’t considered as edges). The threshold-2 parameter determines the value for which an edge should be considered valid. Any gradient in between the two thresholds will be considered if it is attached to another gradient who is above threshold-2. Now that we’ve defined all the edges in the image, we need to isolate the edges that correspond with the lane lines. Here’s how we’re going to do that def region(image): height, width = image.shape triangle = np.array([ [(100, height), (475, 325), (width, height)] ]) mask = np.zeros_like(image) mask = cv2.fillPoly(mask, triangle, 255) mask = cv2.bitwise_and(image, mask) return mask This function will isolate a certain hard-coded region in the image where the lane lines are. It takes one parameter, the Canny image and outputs the isolated region. In line 1, we’re going to extract the image dimensions using the numpy.shape function. In line 2–4, we’re going to define the dimensions of a triangle, which is the region we want to isolate. In line 5 and 6, we’re going to create a black plane and then we’re going to define a white triangle with the dimensions that we defined in line 2. In line 7, we’re going to perform the bitwise and operation which allows us to isolate the edges that correspond with the lane lines. Let’s dive deeper into the operation. In our image, there are two-pixel intensities: black and white. Black pixels have a value of 0, and white pixels have a value of 255. In 8-bit binary, 0 translates to 00000000 and 255 translates to 11111111. For the bitwise and operation, we’re going to use the pixel’s binary values. Now, here’s when the magic happens. We’re going to multiply two pixels in the exact same location on img1 and img2 (we’ll define img1 as the plane with the edge detections and img2 as the mask that we created). For example, the pixel at (0, 0) on img1 will be multiplied with the pixel at the point (0, 0) in img2 (and likewise for every other pixel in every other location on the image). If the (0,0) pixel in img1 is white (meaning it is an edge) and the (0,0) pixel in img2 is black (meaning this point isn’t part of the isolated section where our lane lines are), the operation would look like 11111111* 0000000, which equals 0000000 (a black pixel). We would repeat this operation for every pixel on the image, resulting in only the edges in the mask outputting. Now that we’ve defined the edges that we want, let's define the function which turns these edges into lines. lines = cv2.HoughLinesP(isolated, rho=2, theta=np.pi/180, threshold=100, np.array([]), minLineLength=40, maxLineGap=5) So A LOT is happening in this one line. This one line of code is the heart of the whole algorithm. It is called Hough Transform, the part that turns those clusters of white pixels from our isolated region into actual lines. Parameter 1: The isolated gradients Parameter 2 and 3: Defining the bin size, 2 is the value for rho and np.pi/180 is the value for theta Parameter 4: Minimum intersections needed per bin to be considered a line (in our case, its 100 intersections) Parameter 5: Placeholder array Parameter 6: Minimum Line length Parameter 7: Maximum Line gap Now if those seemed like gibberish, this next part dives into the nuts and bolts behind the algorithm. So you can come back to this part after you finish reading part 2, and hopefully, it will make more sense. Just a quick note, this section is solely theory. If you want to skip this part, you can continue to Part 3, but I encourage you to read through it. The mathematics under the hood of Hough Transform is truly spectacular. Anyways, here it is! Let’s talk Hough Transform. In the cartesian plane (x and y-axis), lines are defined by the formula y=mx+b, where x and y correspond to a specific point on that line and m and b correspond to the slope and y-intercept. A regular line plotted in the cartesian plane has 2 parameters (m and b), meaning a line is defined by these values. Also, it is important to note that lines in the cartesian plane are plotted as a function of their x and y values, meaning that we are displaying the line with respect to how many (x, y) pairs make up this specific line (there is an infinite amount of x, y pairs that makeup any line, hence the reason why lines stretch to infinity). However, it is possible to plot lines as a function of its m and b values. This is done in a plane called Hough Space. To understand the Hough Transform algorithm, we need to understand how Hough Space works. In our use case, we can sum up Hough Space into two lines Points on the Cartesian plane turn into lines in Hough Space Lines in the Cartesian plane turn into points in Hough Space But, why? Think of the concept of a line. A line is basically an infinitely long grouping of points arranged orderly one after the other. Since on the Cartesian plane, we’re plotting lines as a function of x and y, lines are displayed as infinitely long because there is an infinite number of (x, y) pairs that make up this line. Now in Hough Space, we’re plotting lines as a function of their m and b values. And since each line has its only one m and b value per cartesian line, this line would be represented as a point. For example, the equation y=2x+1 represents a single line on the Cartesian Plane. Its m and b values are ‘2’ and ‘1’ respectively, and those are the only possible m and b values for this equation. On the other hand, this equation could have many values for x and y that would make this equation come true (left side=right side). So if I were to plot this equation using its m and b values, I would only use the point (2, 1). If I were to plot this equation using its x and y values, I would have an infinite amount of options because there are infinite (x, y) pairs. So why are lines in the Hough Space are represented as points in the Cartesian Plane (if you understood the theory well from the previous explanation, I challenge you to figure this question out on without reading the explanation.). Now let's think of a point on the cartesian plane. A point on the cartesian plane has only one possible (x, y) pair that can represent it, hence the reason it is a point and is not infinitely long. What is also true about a point is that there is an infinite amount of possible lines that can pass through this point. In other words, there is an infinite amount of equations (in the form of y=mx + b) that this point can satisfy (LS=RS). Currently, in the Cartesian Plane, we’re plotting this point with respect to its x and y values. But in Hough Space, we’re plotting this point with respect to its m and b values, and since there are infinite lines that pass through this point, the result in the Hough Space will be a line which is infinitely long. For example, let's take the point (3, 4). Some lines that could pass through this point are: y= -4x+16, y= -8/3x + 12 and y= -4/3x + 8 (there are infinite lines but I’m using 3 for simplicity). If you would plot each of those lines in Hough Space([-4, 16], [-8/3, 12], [-4/3, 8]), the points that represent each line in cartesian space will form one line in Hough Space (this is the line which corresponds with the point (3, 4)). Neat, huh? Now if what if we’d place another point in the cartesian plane? How would this turn out in the Hough Space? Well, by using the Hough Space, we can actually find the line of best fit for these two points on the Cartesian Plane. We can do this by plotting the lines in Hough Space that correspond with the 2 points in cartesian space and find the point where these 2 lines intersect in Hough Space(a.k.a their POI, point of intersection). Next, get the m and b coordinates of the point where the 2 lines intersect in Hough Space and use those m and b values to form a line in the Cartesian Plane. This line will be the line of best fit for our data. Just to sum up what we’ve been talking about, Lines in the cartesian plane are represented as points in Hough Space Points in the cartesian plane are represented as lines in the Hough Space You can find the line of best fit of two points in cartesian space by finding the m and b coordinates of the POI of the two lines that correspond with these points in Hough Space, then forming a line based on these m and b values. While these concepts are really cool and all, why do they matter? Well, remember Canny Edge detection which I mentioned before which uses gradients to measure the pixel intensities in an image and output edges. At their core, gradients are simply points on the image. So what we can do is we can find the line of best fit for each set of points (the cluster of gradients on the left of the image and the gradients on the right on the image). These lines of best fit are our lane lines. To get a better understanding of how this works, let's take yet another deep dive! So I just explained how we can find the line of best fit by looking at the m and b values of the POI of the two lines which correspond to the points in Hough Space. However, when our dataset grows, there isn’t always going to be one line which perfectly fits our data. This is why we’re going to have to use bins instead. When incorporating bins, we’re going to divide the Hough Plane into equally spaced sections. Each section is called a bin. By focusing on the number of POI’s in a bin, it allows us to determine a line which has a good correlation with our data. Upon finding the bin with the most intersections, you would then use the m and b values which correspond with that bin and form a line in the cartesian space. This line will be the line of best fit for our data. But HOLD UP! That’s not it. We almost overlooked a colossal error! In a vertical line, the slope is infinity. We can’t represent infinity in Hough Space. This would result in the program crashing. So instead of using y=mx+b for the equation of a line, we’ll use P (rho) and θ (theta) to define a line. This is also known as the polar coordinate system. In the polar coordinate system, lines are represented with the equation P=xsinθ + ysinθ. Before we dive deeper, let's define the meanings of these variables: P represents the distance from the origin which is perpendicular to the line. θ represents the angle of depression from the positive x-axis to the line. xcosθ represents the distance in the x direction. ysinθ represents the distance in the y direction. By using the polar coordinate system, there won’t be any errors, even if we have a vertical line. For example, let’s take the point (6, 4), and substitute it into the equation P=xcosθ+ysinθ. Now, let's take the vertical line that would pass through this point, x=6 and sub it into the polar equation for a line, P = 6cos(90) + 4sin(90). θ is 90 degrees for a vertical line since it the angle of depression from the positive x-axis to the line itself is 90 degrees. Another way to represent θ is π/2 (in radians). If you want to learn more about radians and why we use them, here is a good video, however, its not necessary to know what radians are. X and Y take the values of the point (6, 4) since this is the point that we are using in this example. Now let’s work this equation out P = 6cos(90) + 4sin(90)P = 6(1) + 4(0)P = 6 As you can see, we don’t end up with an error. In fact, we didn’t even have to do this calculation, since we technically already know what P is even before we start. Note how P is equal to the x value. Since the line is vertical, the only type of line that is perpendicular to it is a horizontal line. Since this horizontal line starts at the origin, this is the same thing as saying the amount of distance travelled on the x-axis from the origin. So now that’s out of the way, are we ready to get back to coding? Not just yet. Remember before when we plotted points in the cartesian plane, we’d end up with lines in Hough Space? Well, when we use polar coordinates, we’d end up with a curve instead of a line. However, the concept remains the same. We’re going to find the bin which has the most intersections and use those m and b values to determine the line of best fit. So that’s it! I hope you enjoyed that deep dive into the math behind Hough Transform. Now, let’s get back to coding! Now this section about averaging out the lines is made to optimize the algorithm. If we don’t average out the lines, they appear very choppy, since the cv2.HoughLinesP outputs a bunch of mini line segments instead of one big line. To average the lines, we’re going to define a function called “average”. def average(image, lines): left = [] right = [] for line in lines: print(line) x1, y1, x2, y2 = line.reshape(4) parameters = np.polyfit((x1, x2), (y1, y2), 1) slope = parameters[0] y_int = parameters[1] if slope < 0: left.append((slope, y_int)) else: right.append((slope, y_int)) This function averages out the lines made in the cv2.HoughLinesP function. It will find the average slope and y-intercept of the line segments on the left and the right and output two solid lines instead (one on the left and other on the right). In the output of the cv2.HoughLinesP function, each line segment has 2 coordinates: one denotes the start of the line and the other marks the end of the line. Using these coordinates, we’re going to calculate the slopes and y-intercepts of each line segment. Then, we’re going to collect all the slopes of the line segments and classify each line segment into either the list corresponding with the left line or the right line (negative slope = left line, positive slope = right line). Line 4: Loop through the array of lines Line 5: Extract the (x, y) values of the 2 points from each line segment Line 6–9: Determine the slope and y-intercept of each line segment. Line 10–13: Add the negative slopes to the list for the left lines and the positive slope to the list with the right lines. NOTE: Normally, a positive slope=left line and a negative slope=right line but in our case, the image’s y-axis is inversed, hence the reason why the slopes are inversed (all images in OpenCV have inversed y-axes). Next, we have to take the average of the slopes and y-intercepts from both lists. right_avg = np.average(right, axis=0) left_avg = np.average(left, axis=0) left_line = make_points(image, left_avg) right_line = make_points(image, right_avg) return np.array([left_line, right_line]) Note: Do not place this code inside the for loop. Lines 1–2: Takes the average of all the line segments on for both lists (the left side and the right side). Lines 3–4: Calculates the start point and endpoint for each line. (We’ll define make_points function in the next section) Line 5: Output the 2 coordinates for each line Now that we have the average slope and y-intercept for both lists, let’s define the start and endpoints for both lists. def make_points(image, average): slope, y_int = average y1 = image.shape[0] y2 = int(y1 * (3/5)) x1 = int((y1 — y_int) // slope) x2 = int((y2 — y_int) // slope) return np.array([x1, y1, x2, y2]) This function takes 2 parameters, the image with the lane lines and the list with the average slope and y_int of the line, and outputs the starting and ending points for each line. Line 1: Define the function Line 2: Get the average slope and y-intercept Line 3–4: Define the height of the lines (the same for both left and right) Lines 5–6: Calculate x coordinates by rearranging the equation of a line, from y=mx+b to x = (y-b) / m Line 7: Output the sets of coordinates Just to elaborate a bit further, in line 1, we use the y1 value as the height of the image. This is because in OpenCV, the y-axis is inverted, so the 0 is at the top and the height of the image is at the origin (refer to the image below). Also, in Line 2, we multiplied y1 by 3/5. This is because we want the line to start at the origin (y1) and end 2/5 up the image (it's 2/5 since the y-axis is invested, instead of 3/5 up from 0, we see 2/5 down from the max height). However, this function does not display the lines, it only calculates the points necessary to display these lines. Next, we’re going to create a function which takes these points and makes lines out of them. def display_lines(image, lines): lines_image = np.zeros_like(image) if lines is not None: for line in lines: x1, y1, x2, y2 = line cv2.line(lines_image, (x1, y1), (x2, y2), (255, 0, 0), 10) return lines_image This function takes in two parameters: the image which we want to display the lines on and the lane lines which were outputted from the average function. Line 2: create a blacked-out image with the same dimensions of our original image Line 3: Make sure that the lists with the line points aren’t empty Line 4–5: Loop through the lists, and extract the two pairs of (x, y) coordinates Line 6: Create the line and paste it onto the blacked-out image Line 7: Output the black image with the lines You may be wondering, why don’t we append the lines onto the real image instead of a black image. Well, the raw image is a little too bright, so it would be nice if we’d darken it a bit to see the lane lines a little more clearly (yes, I know, it's not that big of a deal, but it's always nice to find ways to make the algorithm better) So all we have to do is call the cv2.addWeighted function. lanes = cv2.addWeighted(copy, 0.8, black_lines, 1, 1) This function gives a weight of 0.8 to each pixel in the actual image, making them slightly darker (each pixel is multiplied by 0.8). Likewise, we give a weight of 1 to the blacked-out image with all the lane lines, so all the pixels in that keep the same intensity, making it stand out. We’re almost at the end of the road (*pun intended). All we have to do is call these functions, so let’s do that right now: copy = np.copy(image1)grey = grey(copy)gaus = gauss(grey)edges = canny(gaus,50,150)isolated = region(edges)lines = cv2.HoughLinesP(isolated, 2, np.pi/180, 100, np.array([]), minLineLength=40, maxLineGap=5)averaged_lines = average(copy, lines)black_lines = display_lines(copy, averaged_lines)lanes = cv2.addWeighted(copy, 0.8, black_lines, 1, 1)cv2.imshow("lanes", lanes)cv2.waitKey(0) Here, we simply call all the functions that we previously defined, then we output the result on lines 12. The cv2.waitKey function is used to tell the program how long to display the image for. We passed “0” into the function, meaning it will wait until a key is pressed to close the output window. Here’s what the output looks like We can also apply this same algorithm to a video. video = r”D:\users\new owner\Desktop\TKS\Article Lane Detection\test2_v2_Trim.mp4"cap = cv2.VideoCapture(video)while(cap.isOpened()): ret, frame = cap.read() if ret == True:#----THE PREVIOUS ALGORITHM----# gaus = gauss(frame) edges = cv2.Canny(gaus,50,150) isolated = region(edges) lines = cv2.HoughLinesP(isolated, 2, np.pi/180, 50, np.array([]), minLineLength=40, maxLineGap=5) averaged_lines = average(frame, lines) black_lines = display_lines(frame, averaged_lines) lanes = cv2.ad1dWeighted(frame, 0.8, black_lines, 1, 1) cv2.imshow(“frame”, lanes)#----THE PREVIOUS ALGORITHM----# if cv2.waitKey(10) & 0xFF == ord(‘q’): break else: breakcap.release() cv2.destroyAllWindows() This code applies the algorithm that we created for images into a video. Remember, a video is just a bunch of pictures that appear one after another really quickly. Line 1–2: Define the path to the video Line 3–4: Capture the video (using cv2.videoCapture), and loop through all the frames Line 5–6: Read the frame, and if there is a frame, continue Lines 10–18: Copy the code from the previous algorithm, and replace all the places where we use copy with frame, because we want to make sure we’re operating on the video’s frame not the image from the previous function. Lines 22–23: Display each frame for 10 seconds, and if the button “q” is pressed, exit the loop. Lines 24–25: Its a continuation of the if statement at lines 5–6, but all its doing is if there isn’t any frame, exit the loop. Lines 26–27: Close the video Alright, you just built an algorithm that can detect lane lines! I hope you enjoyed building this algorithm, but don’t stop here, this is just an intro project into the world of computer vision. Nevertheless, you can brag about building this to your friends :) Use Gaussian Blur to remove all noise from the image Use canny edge detection to isolate edges in the image Use Bitwise And function to isolate edges which correspond to the lane lines Use Hough Transform to turn the edges into lines If you’re curious, here are the key terms that relate to this algorithm which you can research more in-depth. Gaussian Blur Bitwise And Binary Canny Edge Detection Hough Transform Gradients Polar Coordinates OpenCV Lane Line Detection Super well-crafted youtube video. This is where I learned about lane detection, and in fact, my code in this article mostly comes from this video. An article by my friend about the same topic. So where to go after this? There are many things to explore in the world of computer vision. Here are some choices: Look into more advanced methods of detecting lines. Hint: Check the Udacity Self-Driving Car Nanodegree Syllabus. Look into different computer vision algorithms, here's a great website Look into CNN’s, here are my articles on the theory and the code. Apply this into a self-driving RC car on Arduino/RasperryPi And many more.... Thanks for reading my article, I really hope you enjoyed it and got some value out of it. I am a 16-year-old computer vision and autonomous vehicles enthusiast who loves building all sorts of machine learning and deep learning projects. If you have any questions, concerns, requests for tutorials, or just want to say hi, you can contact me on Linkedin or Email me.
[ { "code": null, "e": 383, "s": 171, "text": "Lane line detection is one of the essential components of self-driving cars. There are many approaches to doing this. Here, we’ll look at the simplest approach using Hough Transform. Alright, let’s dive into it!" }, { "code": null, "e": 668, "s": 383, "text": "So before we get started, we need a place to write our code. The IDE (environment) that I recommend is Jupyter Notebooks. It has a nice, minimalistic interface yet is really powerful at the same time. Also, Jupyter Notebooks are awesome for visualizing data. Here’s the download link:" }, { "code": null, "e": 686, "s": 668, "text": "docs.anaconda.com" }, { "code": null, "e": 904, "s": 686, "text": "Now that you have Anaconda installed and Jupyter is working, let’s get some data! You can download the test images, videos and source code for the algorithm from my Github repo. Now we’re ready to build the algorithm." }, { "code": null, "e": 946, "s": 904, "text": "This article is divided into three parts:" }, { "code": null, "e": 990, "s": 946, "text": "Part 1: Gausian Blur + Canny Edge Detection" }, { "code": null, "e": 1014, "s": 990, "text": "Part 2: Hough Transform" }, { "code": null, "e": 1056, "s": 1014, "text": "Part 3: Optimizing + Displaying the Lines" }, { "code": null, "e": 1166, "s": 1056, "text": "Parts 1 and 3 are focused on coding and Part 2 is more theory-oriented. Okay, let's dive into the first part." }, { "code": null, "e": 1226, "s": 1166, "text": "The first thing we need to do is import required libraries." }, { "code": null, "e": 1286, "s": 1226, "text": "import numpy as npimport cv2import matplotlib.pyplot as plt" }, { "code": null, "e": 1316, "s": 1286, "text": "Here we imported 3 libraries:" }, { "code": null, "e": 1431, "s": 1316, "text": "Line 1: Numpy is used for performing mathematical computations. We’re gonna use it to create and manipulate arrays" }, { "code": null, "e": 1550, "s": 1431, "text": "Line 2: OpenCV is a library used to make computer vision able for anyone to do (a.k.a simplifying them for beginners)." }, { "code": null, "e": 1602, "s": 1550, "text": "Line 3: Matplotlib is used to visualize the images." }, { "code": null, "e": 1673, "s": 1602, "text": "Next, let’s load in an image from our collection to test our algorithm" }, { "code": null, "e": 1820, "s": 1673, "text": "image_path = r\"D:\\users\\new owner\\Desktop\\TKS\\Article Lane Detection\\udacity\\solidWhiteCurve.jpg\"image1 = cv2.imread(image_path)plt.imshow(image1)" }, { "code": null, "e": 1943, "s": 1820, "text": "Here, we load the image into the notebook in line 4, then we’re going to read the image and visualize it in lines 5 and 6." }, { "code": null, "e": 2032, "s": 1943, "text": "Now its time to manipulate the image. We’re going to do three things here in particular:" }, { "code": null, "e": 2229, "s": 2032, "text": "def grey(image): return cv2.cvtColor(image, cv2.COLOR_RGB2GRAY)def gauss(image): return cv2.GaussianBlur(image, (5, 5), 0)def canny(image): edges = cv2.Canny(image,50,150) return edges" }, { "code": null, "e": 2283, "s": 2229, "text": "Okay, in this last code block we defined 3 functions:" }, { "code": null, "e": 2415, "s": 2283, "text": "Greyscale the image: This helps by increasing the contrast of the colours, making it easier to identify changes in pixel intensity." }, { "code": null, "e": 2676, "s": 2415, "text": "Gaussian Filter: The purpose of the gaussian filter is to reduce noise in the image. We do this because the gradients in Canny are really sensitive to noise, so we want to eliminate the most noise possible. The cv2.GaussianBlur function takes three parameters:" }, { "code": null, "e": 2753, "s": 2676, "text": "The img parameter defines the image we’re going to normalize (reduce noise)." }, { "code": null, "e": 3022, "s": 2753, "text": "The ksize parameter defines the dimensions of the kernel which we’re going to convolute (pass over) the image. This kernel convolution is how the noise reduction takes place. This function uses a kernel called the Gaussian Kernel, which is used for normalizing images." }, { "code": null, "e": 3235, "s": 3022, "text": "The sigma parameter defines the standard deviation along the x-axis. The standard deviation measures the spread of the pixels in the image. We want the pixel spread to be consistent, hence a 0 standard deviation." }, { "code": null, "e": 3452, "s": 3235, "text": "Canny: This is where we detect the edges in the image. What it does is it calculates the change of pixel intensity (change in brightness) in a certain section in an image. Luckily, this is made very simple by OpenCV." }, { "code": null, "e": 3526, "s": 3452, "text": "The cv2.Canny function has 3 parameters, (img, threshold-1, threshold-2)." }, { "code": null, "e": 3599, "s": 3526, "text": "The img parameter defines the image that we're going to detect edges on." }, { "code": null, "e": 3705, "s": 3599, "text": "The threshold-1 parameter filters all gradients lower than this number (they aren’t considered as edges)." }, { "code": null, "e": 3798, "s": 3705, "text": "The threshold-2 parameter determines the value for which an edge should be considered valid." }, { "code": null, "e": 3924, "s": 3798, "text": "Any gradient in between the two thresholds will be considered if it is attached to another gradient who is above threshold-2." }, { "code": null, "e": 4075, "s": 3924, "text": "Now that we’ve defined all the edges in the image, we need to isolate the edges that correspond with the lane lines. Here’s how we’re going to do that" }, { "code": null, "e": 4371, "s": 4075, "text": "def region(image): height, width = image.shape triangle = np.array([ [(100, height), (475, 325), (width, height)] ]) mask = np.zeros_like(image) mask = cv2.fillPoly(mask, triangle, 255) mask = cv2.bitwise_and(image, mask) return mask" }, { "code": null, "e": 4538, "s": 4371, "text": "This function will isolate a certain hard-coded region in the image where the lane lines are. It takes one parameter, the Canny image and outputs the isolated region." }, { "code": null, "e": 4730, "s": 4538, "text": "In line 1, we’re going to extract the image dimensions using the numpy.shape function. In line 2–4, we’re going to define the dimensions of a triangle, which is the region we want to isolate." }, { "code": null, "e": 4878, "s": 4730, "text": "In line 5 and 6, we’re going to create a black plane and then we’re going to define a white triangle with the dimensions that we defined in line 2." }, { "code": null, "e": 5050, "s": 4878, "text": "In line 7, we’re going to perform the bitwise and operation which allows us to isolate the edges that correspond with the lane lines. Let’s dive deeper into the operation." }, { "code": null, "e": 5335, "s": 5050, "text": "In our image, there are two-pixel intensities: black and white. Black pixels have a value of 0, and white pixels have a value of 255. In 8-bit binary, 0 translates to 00000000 and 255 translates to 11111111. For the bitwise and operation, we’re going to use the pixel’s binary values." }, { "code": null, "e": 5546, "s": 5335, "text": "Now, here’s when the magic happens. We’re going to multiply two pixels in the exact same location on img1 and img2 (we’ll define img1 as the plane with the edge detections and img2 as the mask that we created)." }, { "code": null, "e": 5724, "s": 5546, "text": "For example, the pixel at (0, 0) on img1 will be multiplied with the pixel at the point (0, 0) in img2 (and likewise for every other pixel in every other location on the image)." }, { "code": null, "e": 5990, "s": 5724, "text": "If the (0,0) pixel in img1 is white (meaning it is an edge) and the (0,0) pixel in img2 is black (meaning this point isn’t part of the isolated section where our lane lines are), the operation would look like 11111111* 0000000, which equals 0000000 (a black pixel)." }, { "code": null, "e": 6103, "s": 5990, "text": "We would repeat this operation for every pixel on the image, resulting in only the edges in the mask outputting." }, { "code": null, "e": 6212, "s": 6103, "text": "Now that we’ve defined the edges that we want, let's define the function which turns these edges into lines." }, { "code": null, "e": 6331, "s": 6212, "text": "lines = cv2.HoughLinesP(isolated, rho=2, theta=np.pi/180, threshold=100, np.array([]), minLineLength=40, maxLineGap=5)" }, { "code": null, "e": 6555, "s": 6331, "text": "So A LOT is happening in this one line. This one line of code is the heart of the whole algorithm. It is called Hough Transform, the part that turns those clusters of white pixels from our isolated region into actual lines." }, { "code": null, "e": 6591, "s": 6555, "text": "Parameter 1: The isolated gradients" }, { "code": null, "e": 6693, "s": 6591, "text": "Parameter 2 and 3: Defining the bin size, 2 is the value for rho and np.pi/180 is the value for theta" }, { "code": null, "e": 6804, "s": 6693, "text": "Parameter 4: Minimum intersections needed per bin to be considered a line (in our case, its 100 intersections)" }, { "code": null, "e": 6835, "s": 6804, "text": "Parameter 5: Placeholder array" }, { "code": null, "e": 6868, "s": 6835, "text": "Parameter 6: Minimum Line length" }, { "code": null, "e": 6898, "s": 6868, "text": "Parameter 7: Maximum Line gap" }, { "code": null, "e": 7108, "s": 6898, "text": "Now if those seemed like gibberish, this next part dives into the nuts and bolts behind the algorithm. So you can come back to this part after you finish reading part 2, and hopefully, it will make more sense." }, { "code": null, "e": 7350, "s": 7108, "text": "Just a quick note, this section is solely theory. If you want to skip this part, you can continue to Part 3, but I encourage you to read through it. The mathematics under the hood of Hough Transform is truly spectacular. Anyways, here it is!" }, { "code": null, "e": 7569, "s": 7350, "text": "Let’s talk Hough Transform. In the cartesian plane (x and y-axis), lines are defined by the formula y=mx+b, where x and y correspond to a specific point on that line and m and b correspond to the slope and y-intercept." }, { "code": null, "e": 8020, "s": 7569, "text": "A regular line plotted in the cartesian plane has 2 parameters (m and b), meaning a line is defined by these values. Also, it is important to note that lines in the cartesian plane are plotted as a function of their x and y values, meaning that we are displaying the line with respect to how many (x, y) pairs make up this specific line (there is an infinite amount of x, y pairs that makeup any line, hence the reason why lines stretch to infinity)." }, { "code": null, "e": 8229, "s": 8020, "text": "However, it is possible to plot lines as a function of its m and b values. This is done in a plane called Hough Space. To understand the Hough Transform algorithm, we need to understand how Hough Space works." }, { "code": null, "e": 8287, "s": 8229, "text": "In our use case, we can sum up Hough Space into two lines" }, { "code": null, "e": 8348, "s": 8287, "text": "Points on the Cartesian plane turn into lines in Hough Space" }, { "code": null, "e": 8409, "s": 8348, "text": "Lines in the Cartesian plane turn into points in Hough Space" }, { "code": null, "e": 8419, "s": 8409, "text": "But, why?" }, { "code": null, "e": 8739, "s": 8419, "text": "Think of the concept of a line. A line is basically an infinitely long grouping of points arranged orderly one after the other. Since on the Cartesian plane, we’re plotting lines as a function of x and y, lines are displayed as infinitely long because there is an infinite number of (x, y) pairs that make up this line." }, { "code": null, "e": 8933, "s": 8739, "text": "Now in Hough Space, we’re plotting lines as a function of their m and b values. And since each line has its only one m and b value per cartesian line, this line would be represented as a point." }, { "code": null, "e": 9262, "s": 8933, "text": "For example, the equation y=2x+1 represents a single line on the Cartesian Plane. Its m and b values are ‘2’ and ‘1’ respectively, and those are the only possible m and b values for this equation. On the other hand, this equation could have many values for x and y that would make this equation come true (left side=right side)." }, { "code": null, "e": 9500, "s": 9262, "text": "So if I were to plot this equation using its m and b values, I would only use the point (2, 1). If I were to plot this equation using its x and y values, I would have an infinite amount of options because there are infinite (x, y) pairs." }, { "code": null, "e": 9733, "s": 9500, "text": "So why are lines in the Hough Space are represented as points in the Cartesian Plane (if you understood the theory well from the previous explanation, I challenge you to figure this question out on without reading the explanation.)." }, { "code": null, "e": 9931, "s": 9733, "text": "Now let's think of a point on the cartesian plane. A point on the cartesian plane has only one possible (x, y) pair that can represent it, hence the reason it is a point and is not infinitely long." }, { "code": null, "e": 10171, "s": 9931, "text": "What is also true about a point is that there is an infinite amount of possible lines that can pass through this point. In other words, there is an infinite amount of equations (in the form of y=mx + b) that this point can satisfy (LS=RS)." }, { "code": null, "e": 10486, "s": 10171, "text": "Currently, in the Cartesian Plane, we’re plotting this point with respect to its x and y values. But in Hough Space, we’re plotting this point with respect to its m and b values, and since there are infinite lines that pass through this point, the result in the Hough Space will be a line which is infinitely long." }, { "code": null, "e": 10680, "s": 10486, "text": "For example, let's take the point (3, 4). Some lines that could pass through this point are: y= -4x+16, y= -8/3x + 12 and y= -4/3x + 8 (there are infinite lines but I’m using 3 for simplicity)." }, { "code": null, "e": 10916, "s": 10680, "text": "If you would plot each of those lines in Hough Space([-4, 16], [-8/3, 12], [-4/3, 8]), the points that represent each line in cartesian space will form one line in Hough Space (this is the line which corresponds with the point (3, 4))." }, { "code": null, "e": 11154, "s": 10916, "text": "Neat, huh? Now if what if we’d place another point in the cartesian plane? How would this turn out in the Hough Space? Well, by using the Hough Space, we can actually find the line of best fit for these two points on the Cartesian Plane." }, { "code": null, "e": 11364, "s": 11154, "text": "We can do this by plotting the lines in Hough Space that correspond with the 2 points in cartesian space and find the point where these 2 lines intersect in Hough Space(a.k.a their POI, point of intersection)." }, { "code": null, "e": 11575, "s": 11364, "text": "Next, get the m and b coordinates of the point where the 2 lines intersect in Hough Space and use those m and b values to form a line in the Cartesian Plane. This line will be the line of best fit for our data." }, { "code": null, "e": 11621, "s": 11575, "text": "Just to sum up what we’ve been talking about," }, { "code": null, "e": 11691, "s": 11621, "text": "Lines in the cartesian plane are represented as points in Hough Space" }, { "code": null, "e": 11765, "s": 11691, "text": "Points in the cartesian plane are represented as lines in the Hough Space" }, { "code": null, "e": 11996, "s": 11765, "text": "You can find the line of best fit of two points in cartesian space by finding the m and b coordinates of the POI of the two lines that correspond with these points in Hough Space, then forming a line based on these m and b values." }, { "code": null, "e": 12207, "s": 11996, "text": "While these concepts are really cool and all, why do they matter? Well, remember Canny Edge detection which I mentioned before which uses gradients to measure the pixel intensities in an image and output edges." }, { "code": null, "e": 12565, "s": 12207, "text": "At their core, gradients are simply points on the image. So what we can do is we can find the line of best fit for each set of points (the cluster of gradients on the left of the image and the gradients on the right on the image). These lines of best fit are our lane lines. To get a better understanding of how this works, let's take yet another deep dive!" }, { "code": null, "e": 12834, "s": 12565, "text": "So I just explained how we can find the line of best fit by looking at the m and b values of the POI of the two lines which correspond to the points in Hough Space. However, when our dataset grows, there isn’t always going to be one line which perfectly fits our data." }, { "code": null, "e": 13132, "s": 12834, "text": "This is why we’re going to have to use bins instead. When incorporating bins, we’re going to divide the Hough Plane into equally spaced sections. Each section is called a bin. By focusing on the number of POI’s in a bin, it allows us to determine a line which has a good correlation with our data." }, { "code": null, "e": 13344, "s": 13132, "text": "Upon finding the bin with the most intersections, you would then use the m and b values which correspond with that bin and form a line in the cartesian space. This line will be the line of best fit for our data." }, { "code": null, "e": 13411, "s": 13344, "text": "But HOLD UP! That’s not it. We almost overlooked a colossal error!" }, { "code": null, "e": 13697, "s": 13411, "text": "In a vertical line, the slope is infinity. We can’t represent infinity in Hough Space. This would result in the program crashing. So instead of using y=mx+b for the equation of a line, we’ll use P (rho) and θ (theta) to define a line. This is also known as the polar coordinate system." }, { "code": null, "e": 13855, "s": 13697, "text": "In the polar coordinate system, lines are represented with the equation P=xsinθ + ysinθ. Before we dive deeper, let's define the meanings of these variables:" }, { "code": null, "e": 13933, "s": 13855, "text": "P represents the distance from the origin which is perpendicular to the line." }, { "code": null, "e": 14008, "s": 13933, "text": "θ represents the angle of depression from the positive x-axis to the line." }, { "code": null, "e": 14058, "s": 14008, "text": "xcosθ represents the distance in the x direction." }, { "code": null, "e": 14108, "s": 14058, "text": "ysinθ represents the distance in the y direction." }, { "code": null, "e": 14445, "s": 14108, "text": "By using the polar coordinate system, there won’t be any errors, even if we have a vertical line. For example, let’s take the point (6, 4), and substitute it into the equation P=xcosθ+ysinθ. Now, let's take the vertical line that would pass through this point, x=6 and sub it into the polar equation for a line, P = 6cos(90) + 4sin(90)." }, { "code": null, "e": 14757, "s": 14445, "text": "θ is 90 degrees for a vertical line since it the angle of depression from the positive x-axis to the line itself is 90 degrees. Another way to represent θ is π/2 (in radians). If you want to learn more about radians and why we use them, here is a good video, however, its not necessary to know what radians are." }, { "code": null, "e": 14860, "s": 14757, "text": "X and Y take the values of the point (6, 4) since this is the point that we are using in this example." }, { "code": null, "e": 14893, "s": 14860, "text": "Now let’s work this equation out" }, { "code": null, "e": 14937, "s": 14893, "text": "P = 6cos(90) + 4sin(90)P = 6(1) + 4(0)P = 6" }, { "code": null, "e": 15385, "s": 14937, "text": "As you can see, we don’t end up with an error. In fact, we didn’t even have to do this calculation, since we technically already know what P is even before we start. Note how P is equal to the x value. Since the line is vertical, the only type of line that is perpendicular to it is a horizontal line. Since this horizontal line starts at the origin, this is the same thing as saying the amount of distance travelled on the x-axis from the origin." }, { "code": null, "e": 15648, "s": 15385, "text": "So now that’s out of the way, are we ready to get back to coding? Not just yet. Remember before when we plotted points in the cartesian plane, we’d end up with lines in Hough Space? Well, when we use polar coordinates, we’d end up with a curve instead of a line." }, { "code": null, "e": 15812, "s": 15648, "text": "However, the concept remains the same. We’re going to find the bin which has the most intersections and use those m and b values to determine the line of best fit." }, { "code": null, "e": 15929, "s": 15812, "text": "So that’s it! I hope you enjoyed that deep dive into the math behind Hough Transform. Now, let’s get back to coding!" }, { "code": null, "e": 16160, "s": 15929, "text": "Now this section about averaging out the lines is made to optimize the algorithm. If we don’t average out the lines, they appear very choppy, since the cv2.HoughLinesP outputs a bunch of mini line segments instead of one big line." }, { "code": null, "e": 16233, "s": 16160, "text": "To average the lines, we’re going to define a function called “average”." }, { "code": null, "e": 16593, "s": 16233, "text": "def average(image, lines): left = [] right = [] for line in lines: print(line) x1, y1, x2, y2 = line.reshape(4) parameters = np.polyfit((x1, x2), (y1, y2), 1) slope = parameters[0] y_int = parameters[1] if slope < 0: left.append((slope, y_int)) else: right.append((slope, y_int))" }, { "code": null, "e": 16839, "s": 16593, "text": "This function averages out the lines made in the cv2.HoughLinesP function. It will find the average slope and y-intercept of the line segments on the left and the right and output two solid lines instead (one on the left and other on the right)." }, { "code": null, "e": 17098, "s": 16839, "text": "In the output of the cv2.HoughLinesP function, each line segment has 2 coordinates: one denotes the start of the line and the other marks the end of the line. Using these coordinates, we’re going to calculate the slopes and y-intercepts of each line segment." }, { "code": null, "e": 17325, "s": 17098, "text": "Then, we’re going to collect all the slopes of the line segments and classify each line segment into either the list corresponding with the left line or the right line (negative slope = left line, positive slope = right line)." }, { "code": null, "e": 17365, "s": 17325, "text": "Line 4: Loop through the array of lines" }, { "code": null, "e": 17438, "s": 17365, "text": "Line 5: Extract the (x, y) values of the 2 points from each line segment" }, { "code": null, "e": 17506, "s": 17438, "text": "Line 6–9: Determine the slope and y-intercept of each line segment." }, { "code": null, "e": 17630, "s": 17506, "text": "Line 10–13: Add the negative slopes to the list for the left lines and the positive slope to the list with the right lines." }, { "code": null, "e": 17844, "s": 17630, "text": "NOTE: Normally, a positive slope=left line and a negative slope=right line but in our case, the image’s y-axis is inversed, hence the reason why the slopes are inversed (all images in OpenCV have inversed y-axes)." }, { "code": null, "e": 17926, "s": 17844, "text": "Next, we have to take the average of the slopes and y-intercepts from both lists." }, { "code": null, "e": 18141, "s": 17926, "text": " right_avg = np.average(right, axis=0) left_avg = np.average(left, axis=0) left_line = make_points(image, left_avg) right_line = make_points(image, right_avg) return np.array([left_line, right_line])" }, { "code": null, "e": 18191, "s": 18141, "text": "Note: Do not place this code inside the for loop." }, { "code": null, "e": 18299, "s": 18191, "text": "Lines 1–2: Takes the average of all the line segments on for both lists (the left side and the right side)." }, { "code": null, "e": 18421, "s": 18299, "text": "Lines 3–4: Calculates the start point and endpoint for each line. (We’ll define make_points function in the next section)" }, { "code": null, "e": 18468, "s": 18421, "text": "Line 5: Output the 2 coordinates for each line" }, { "code": null, "e": 18588, "s": 18468, "text": "Now that we have the average slope and y-intercept for both lists, let’s define the start and endpoints for both lists." }, { "code": null, "e": 18785, "s": 18588, "text": "def make_points(image, average): slope, y_int = average y1 = image.shape[0] y2 = int(y1 * (3/5)) x1 = int((y1 — y_int) // slope) x2 = int((y2 — y_int) // slope) return np.array([x1, y1, x2, y2])" }, { "code": null, "e": 18966, "s": 18785, "text": "This function takes 2 parameters, the image with the lane lines and the list with the average slope and y_int of the line, and outputs the starting and ending points for each line." }, { "code": null, "e": 18994, "s": 18966, "text": "Line 1: Define the function" }, { "code": null, "e": 19040, "s": 18994, "text": "Line 2: Get the average slope and y-intercept" }, { "code": null, "e": 19116, "s": 19040, "text": "Line 3–4: Define the height of the lines (the same for both left and right)" }, { "code": null, "e": 19219, "s": 19116, "text": "Lines 5–6: Calculate x coordinates by rearranging the equation of a line, from y=mx+b to x = (y-b) / m" }, { "code": null, "e": 19258, "s": 19219, "text": "Line 7: Output the sets of coordinates" }, { "code": null, "e": 19497, "s": 19258, "text": "Just to elaborate a bit further, in line 1, we use the y1 value as the height of the image. This is because in OpenCV, the y-axis is inverted, so the 0 is at the top and the height of the image is at the origin (refer to the image below)." }, { "code": null, "e": 19729, "s": 19497, "text": "Also, in Line 2, we multiplied y1 by 3/5. This is because we want the line to start at the origin (y1) and end 2/5 up the image (it's 2/5 since the y-axis is invested, instead of 3/5 up from 0, we see 2/5 down from the max height)." }, { "code": null, "e": 19937, "s": 19729, "text": "However, this function does not display the lines, it only calculates the points necessary to display these lines. Next, we’re going to create a function which takes these points and makes lines out of them." }, { "code": null, "e": 20156, "s": 19937, "text": "def display_lines(image, lines): lines_image = np.zeros_like(image) if lines is not None: for line in lines: x1, y1, x2, y2 = line cv2.line(lines_image, (x1, y1), (x2, y2), (255, 0, 0), 10) return lines_image" }, { "code": null, "e": 20310, "s": 20156, "text": "This function takes in two parameters: the image which we want to display the lines on and the lane lines which were outputted from the average function." }, { "code": null, "e": 20392, "s": 20310, "text": "Line 2: create a blacked-out image with the same dimensions of our original image" }, { "code": null, "e": 20459, "s": 20392, "text": "Line 3: Make sure that the lists with the line points aren’t empty" }, { "code": null, "e": 20541, "s": 20459, "text": "Line 4–5: Loop through the lists, and extract the two pairs of (x, y) coordinates" }, { "code": null, "e": 20605, "s": 20541, "text": "Line 6: Create the line and paste it onto the blacked-out image" }, { "code": null, "e": 20651, "s": 20605, "text": "Line 7: Output the black image with the lines" }, { "code": null, "e": 20988, "s": 20651, "text": "You may be wondering, why don’t we append the lines onto the real image instead of a black image. Well, the raw image is a little too bright, so it would be nice if we’d darken it a bit to see the lane lines a little more clearly (yes, I know, it's not that big of a deal, but it's always nice to find ways to make the algorithm better)" }, { "code": null, "e": 21047, "s": 20988, "text": "So all we have to do is call the cv2.addWeighted function." }, { "code": null, "e": 21101, "s": 21047, "text": "lanes = cv2.addWeighted(copy, 0.8, black_lines, 1, 1)" }, { "code": null, "e": 21389, "s": 21101, "text": "This function gives a weight of 0.8 to each pixel in the actual image, making them slightly darker (each pixel is multiplied by 0.8). Likewise, we give a weight of 1 to the blacked-out image with all the lane lines, so all the pixels in that keep the same intensity, making it stand out." }, { "code": null, "e": 21513, "s": 21389, "text": "We’re almost at the end of the road (*pun intended). All we have to do is call these functions, so let’s do that right now:" }, { "code": null, "e": 21898, "s": 21513, "text": "copy = np.copy(image1)grey = grey(copy)gaus = gauss(grey)edges = canny(gaus,50,150)isolated = region(edges)lines = cv2.HoughLinesP(isolated, 2, np.pi/180, 100, np.array([]), minLineLength=40, maxLineGap=5)averaged_lines = average(copy, lines)black_lines = display_lines(copy, averaged_lines)lanes = cv2.addWeighted(copy, 0.8, black_lines, 1, 1)cv2.imshow(\"lanes\", lanes)cv2.waitKey(0)" }, { "code": null, "e": 22197, "s": 21898, "text": "Here, we simply call all the functions that we previously defined, then we output the result on lines 12. The cv2.waitKey function is used to tell the program how long to display the image for. We passed “0” into the function, meaning it will wait until a key is pressed to close the output window." }, { "code": null, "e": 22231, "s": 22197, "text": "Here’s what the output looks like" }, { "code": null, "e": 22281, "s": 22231, "text": "We can also apply this same algorithm to a video." }, { "code": null, "e": 23004, "s": 22281, "text": "video = r”D:\\users\\new owner\\Desktop\\TKS\\Article Lane Detection\\test2_v2_Trim.mp4\"cap = cv2.VideoCapture(video)while(cap.isOpened()): ret, frame = cap.read() if ret == True:#----THE PREVIOUS ALGORITHM----# gaus = gauss(frame) edges = cv2.Canny(gaus,50,150) isolated = region(edges) lines = cv2.HoughLinesP(isolated, 2, np.pi/180, 50, np.array([]), minLineLength=40, maxLineGap=5) averaged_lines = average(frame, lines) black_lines = display_lines(frame, averaged_lines) lanes = cv2.ad1dWeighted(frame, 0.8, black_lines, 1, 1) cv2.imshow(“frame”, lanes)#----THE PREVIOUS ALGORITHM----# if cv2.waitKey(10) & 0xFF == ord(‘q’): break else: breakcap.release() cv2.destroyAllWindows()" }, { "code": null, "e": 23169, "s": 23004, "text": "This code applies the algorithm that we created for images into a video. Remember, a video is just a bunch of pictures that appear one after another really quickly." }, { "code": null, "e": 23208, "s": 23169, "text": "Line 1–2: Define the path to the video" }, { "code": null, "e": 23294, "s": 23208, "text": "Line 3–4: Capture the video (using cv2.videoCapture), and loop through all the frames" }, { "code": null, "e": 23354, "s": 23294, "text": "Line 5–6: Read the frame, and if there is a frame, continue" }, { "code": null, "e": 23575, "s": 23354, "text": "Lines 10–18: Copy the code from the previous algorithm, and replace all the places where we use copy with frame, because we want to make sure we’re operating on the video’s frame not the image from the previous function." }, { "code": null, "e": 23672, "s": 23575, "text": "Lines 22–23: Display each frame for 10 seconds, and if the button “q” is pressed, exit the loop." }, { "code": null, "e": 23800, "s": 23672, "text": "Lines 24–25: Its a continuation of the if statement at lines 5–6, but all its doing is if there isn’t any frame, exit the loop." }, { "code": null, "e": 23829, "s": 23800, "text": "Lines 26–27: Close the video" }, { "code": null, "e": 24090, "s": 23829, "text": "Alright, you just built an algorithm that can detect lane lines! I hope you enjoyed building this algorithm, but don’t stop here, this is just an intro project into the world of computer vision. Nevertheless, you can brag about building this to your friends :)" }, { "code": null, "e": 24143, "s": 24090, "text": "Use Gaussian Blur to remove all noise from the image" }, { "code": null, "e": 24198, "s": 24143, "text": "Use canny edge detection to isolate edges in the image" }, { "code": null, "e": 24275, "s": 24198, "text": "Use Bitwise And function to isolate edges which correspond to the lane lines" }, { "code": null, "e": 24324, "s": 24275, "text": "Use Hough Transform to turn the edges into lines" }, { "code": null, "e": 24434, "s": 24324, "text": "If you’re curious, here are the key terms that relate to this algorithm which you can research more in-depth." }, { "code": null, "e": 24448, "s": 24434, "text": "Gaussian Blur" }, { "code": null, "e": 24467, "s": 24448, "text": "Bitwise And Binary" }, { "code": null, "e": 24488, "s": 24467, "text": "Canny Edge Detection" }, { "code": null, "e": 24504, "s": 24488, "text": "Hough Transform" }, { "code": null, "e": 24514, "s": 24504, "text": "Gradients" }, { "code": null, "e": 24532, "s": 24514, "text": "Polar Coordinates" }, { "code": null, "e": 24559, "s": 24532, "text": "OpenCV Lane Line Detection" }, { "code": null, "e": 24706, "s": 24559, "text": "Super well-crafted youtube video. This is where I learned about lane detection, and in fact, my code in this article mostly comes from this video." }, { "code": null, "e": 24752, "s": 24706, "text": "An article by my friend about the same topic." }, { "code": null, "e": 24868, "s": 24752, "text": "So where to go after this? There are many things to explore in the world of computer vision. Here are some choices:" }, { "code": null, "e": 24982, "s": 24868, "text": "Look into more advanced methods of detecting lines. Hint: Check the Udacity Self-Driving Car Nanodegree Syllabus." }, { "code": null, "e": 25053, "s": 24982, "text": "Look into different computer vision algorithms, here's a great website" }, { "code": null, "e": 25119, "s": 25053, "text": "Look into CNN’s, here are my articles on the theory and the code." }, { "code": null, "e": 25179, "s": 25119, "text": "Apply this into a self-driving RC car on Arduino/RasperryPi" }, { "code": null, "e": 25197, "s": 25179, "text": "And many more...." } ]
Number of pairs whose sum is a power of 2 - GeeksforGeeks
15 Nov, 2021 Given an array arr[] of positive integers, the task is to count the maximum possible number of pairs (arr[i], arr[j]) such that arr[i] + arr[j] is a power of 2. Note: One element can be used at most once to form a pair.Examples: Input: arr[] = {3, 11, 14, 5, 13} Output: 2 All valid pairs are (13, 3) and (11, 5) both sum up to 16 which is a power of 2. We could have used (3, 5) but by doing so maximum of 1 pair could only be formed. Therefore, (3, 5) is not optimal.Input: arr[] = {1, 2, 3} Output: 1 1 and 3 can be paired to form 4, which is a power of 2. A simple solution is to consider every pair and check if sum of this pair is a power of 2 or not. Time Complexity of this solution is O(n * n)An Efficient Approach: is to find the largest element from the array say X then find the largest element from the rest of the array elements Y such that Y ≤ X and X + Y is a power of 2. This is an optimal selection of pair because even if Y makes a valid pair with some other element say Z then Z will be left to pair with an element other than Y (if possible) to maximize the number of valid pairs. C++ Java Python3 C# Javascript // C++ implementation of above approach#include <bits/stdc++.h>using namespace std; // Function to return the count of valid pairsint countPairs(int a[], int n){ // Storing occurrences of each element unordered_map<int, int> mp; for (int i = 0; i < n; i++) mp[a[i]]++; // Sort the array in decreasing order sort(a, a + n, greater<int>()); // Start taking largest element each time int count = 0; for (int i = 0; i < n; i++) { // If element has already been paired if (mp[a[i]] < 1) continue; // Find the number which is greater than // a[i] and power of two int cur = 1; while (cur <= a[i]) cur <<= 1; // If there is a number which adds up with a[i] // to form a power of two if (mp[cur - a[i]]) { // Edge case when a[i] and crr - a[i] is same // and we have only one occurrence of a[i] then // it cannot be paired if (cur - a[i] == a[i] and mp[a[i]] == 1) continue; count++; // Remove already paired elements mp[cur - a[i]]--; mp[a[i]]--; } } // Return the count return count;} // Driver codeint main(){ int a[] = { 3, 11, 14, 5, 13 }; int n = sizeof(a) / sizeof(a[0]); cout << countPairs(a, n); return 0;} // Java implementation of above approachimport java.util.TreeMap; class Count{ // Function to return the count of valid pairs static int countPairs(int[] a, int n) { // To keep the element in sorted order TreeMap<Integer, Integer> map = new TreeMap<>(); for (int i = 0; i < n; i++) { map.put(a[i], 1); } // Start taking largest element each time int count = 0; for (int i = 0; i < n; i++) { // If element has already been paired if (map.get(a[i]) < 1) continue; // Find the number which is greater than // a[i] and power of two int cur = 1; while (cur <= a[i]) cur <<= 1; // If there is a number which adds up with a[i] // to form a power of two if (map.containsKey(cur - a[i])) { // Edge case when a[i] and crr - a[i] is same // and we have only one occurrence of a[i] then // it cannot be paired if (cur - a[i] == a[i] && map.get(a[i]) == 1) continue; count++; // Remove already paired elements map.put(cur - a[i], map.get(cur - a[i]) - 1); map.put(a[i], map.get(a[i]) - 1); } } // Return the count return count; } // Driver code public static void main(String[] args) { int[] a = { 3, 11, 14, 5, 13 }; int n = a.length; System.out.println(countPairs(a, n)); }} // This code is contributed by Vivekkumar Singh # Python3 implementation of above approach # Function to return the count# of valid pairsdef countPairs(a, n) : # Storing occurrences of each element mp = dict.fromkeys(a, 0) for i in range(n) : mp[a[i]] += 1 # Sort the array in decreasing order a.sort(reverse = True) # Start taking largest element # each time count = 0 for i in range(n) : # If element has already been paired if (mp[a[i]] < 1) : continue # Find the number which is greater # than a[i] and power of two cur = 1 while (cur <= a[i]) : cur = cur << 1 # If there is a number which adds # up with a[i] to form a power of two if (cur - a[i] in mp.keys()) : # Edge case when a[i] and crr - a[i] # is same and we have only one occurrence # of a[i] then it cannot be paired if (cur - a[i] == a[i] and mp[a[i]] == 1) : continue count += 1 # Remove already paired elements mp[cur - a[i]] -= 1 mp[a[i]] -= 1 # Return the count return count # Driver codeif __name__ == "__main__" : a = [ 3, 11, 14, 5, 13 ] n = len(a) print(countPairs(a, n)) # This code is contributed by Ryuga // C# implementation of above approachusing System;using System.Collections.Generic; class GFG{ // Function to return the count of valid pairs static int countPairs(int[] a, int n) { // To keep the element in sorted order Dictionary<int, int> map = new Dictionary<int, int>(); for (int i = 0; i < n; i++) { if(!map.ContainsKey(a[i])) map.Add(a[i], 1); } // Start taking largest element each time int count = 0; for (int i = 0; i < n; i++) { // If element has already been paired if (map[a[i]] < 1) continue; // Find the number which is greater than // a[i] and power of two int cur = 1; while (cur <= a[i]) cur <<= 1; // If there is a number which adds up // with a[i] to form a power of two if (map.ContainsKey(cur - a[i])) { // Edge case when a[i] and crr - a[i] // is same and we have only one occurrence // of a[i] then it cannot be paired if (cur - a[i] == a[i] && map[a[i]] == 1) continue; count++; // Remove already paired elements map[cur - a[i]] = map[cur - a[i]] - 1; map[a[i]] = map[a[i]] - 1; } } // Return the count return count; } // Driver code public static void Main(String[] args) { int[] a = { 3, 11, 14, 5, 13 }; int n = a.Length; Console.WriteLine(countPairs(a, n)); }} // This code is contributed by Princi Singh <script> // JavaScript Program to implement// the above approach // Function to return the count of valid pairs function countPairs(a, n) { // To keep the element in sorted order let map = new Map(); for (let i = 0; i < n; i++) { map.set(a[i], 1); } // Start taking largest element each time let count = 0; for (let i = 0; i < n; i++) { // If element has already been paired if (map.get(a[i]) < 1) continue; // Find the number which is greater than // a[i] and power of two let cur = 1; while (cur <= a[i]) cur <<= 1; // If there is a number which adds up with a[i] // to form a power of two if (map.has(cur - a[i])) { // Edge case when a[i] and crr - a[i] is same // and we have only one occurrence of a[i] then // it cannot be paired if (cur - a[i] == a[i] && map.get(a[i]) == 1) continue; count++; // Remove already paired elements map.set(cur - a[i], map.get(cur - a[i]) - 1); map.set(a[i], map.get(a[i]) - 1); } } // Return the count return count; } // Driver Code let a = [ 3, 11, 14, 5, 13 ]; let n = a.length; document.write(countPairs(a, n)); </script> 2 Note that the below operation in above code can be done in O(1) time using the last approach discussed in Smallest power of 2 greater than or equal to n C // Find the number which is greater than// a[i] and power of twoint cur = 1;while (cur <= a[i]) cur <<= 1; After optimizing above expression, time complexity of this solution becomes O(n Log n) ankthon Vivekkumar Singh princi singh susmitakundugoaldanga sumitgumber28 Arrays Bit Magic C++ Programs Hash Sorting Arrays Hash Bit Magic Sorting Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Stack Data Structure (Introduction and Program) Top 50 Array Coding Problems for Interviews Introduction to Arrays Linear Search Maximum and minimum of an array using minimum number of comparisons Bitwise Operators in C/C++ Left Shift and Right Shift Operators in C/C++ Cyclic Redundancy Check and Modulo-2 Division Travelling Salesman Problem | Set 1 (Naive and Dynamic Programming) Little and Big Endian Mystery
[ { "code": null, "e": 24803, "s": 24775, "text": "\n15 Nov, 2021" }, { "code": null, "e": 25034, "s": 24803, "text": "Given an array arr[] of positive integers, the task is to count the maximum possible number of pairs (arr[i], arr[j]) such that arr[i] + arr[j] is a power of 2. Note: One element can be used at most once to form a pair.Examples: " }, { "code": null, "e": 25367, "s": 25034, "text": "Input: arr[] = {3, 11, 14, 5, 13} Output: 2 All valid pairs are (13, 3) and (11, 5) both sum up to 16 which is a power of 2. We could have used (3, 5) but by doing so maximum of 1 pair could only be formed. Therefore, (3, 5) is not optimal.Input: arr[] = {1, 2, 3} Output: 1 1 and 3 can be paired to form 4, which is a power of 2. " }, { "code": null, "e": 25912, "s": 25369, "text": "A simple solution is to consider every pair and check if sum of this pair is a power of 2 or not. Time Complexity of this solution is O(n * n)An Efficient Approach: is to find the largest element from the array say X then find the largest element from the rest of the array elements Y such that Y ≤ X and X + Y is a power of 2. This is an optimal selection of pair because even if Y makes a valid pair with some other element say Z then Z will be left to pair with an element other than Y (if possible) to maximize the number of valid pairs. " }, { "code": null, "e": 25916, "s": 25912, "text": "C++" }, { "code": null, "e": 25921, "s": 25916, "text": "Java" }, { "code": null, "e": 25929, "s": 25921, "text": "Python3" }, { "code": null, "e": 25932, "s": 25929, "text": "C#" }, { "code": null, "e": 25943, "s": 25932, "text": "Javascript" }, { "code": "// C++ implementation of above approach#include <bits/stdc++.h>using namespace std; // Function to return the count of valid pairsint countPairs(int a[], int n){ // Storing occurrences of each element unordered_map<int, int> mp; for (int i = 0; i < n; i++) mp[a[i]]++; // Sort the array in decreasing order sort(a, a + n, greater<int>()); // Start taking largest element each time int count = 0; for (int i = 0; i < n; i++) { // If element has already been paired if (mp[a[i]] < 1) continue; // Find the number which is greater than // a[i] and power of two int cur = 1; while (cur <= a[i]) cur <<= 1; // If there is a number which adds up with a[i] // to form a power of two if (mp[cur - a[i]]) { // Edge case when a[i] and crr - a[i] is same // and we have only one occurrence of a[i] then // it cannot be paired if (cur - a[i] == a[i] and mp[a[i]] == 1) continue; count++; // Remove already paired elements mp[cur - a[i]]--; mp[a[i]]--; } } // Return the count return count;} // Driver codeint main(){ int a[] = { 3, 11, 14, 5, 13 }; int n = sizeof(a) / sizeof(a[0]); cout << countPairs(a, n); return 0;}", "e": 27307, "s": 25943, "text": null }, { "code": "// Java implementation of above approachimport java.util.TreeMap; class Count{ // Function to return the count of valid pairs static int countPairs(int[] a, int n) { // To keep the element in sorted order TreeMap<Integer, Integer> map = new TreeMap<>(); for (int i = 0; i < n; i++) { map.put(a[i], 1); } // Start taking largest element each time int count = 0; for (int i = 0; i < n; i++) { // If element has already been paired if (map.get(a[i]) < 1) continue; // Find the number which is greater than // a[i] and power of two int cur = 1; while (cur <= a[i]) cur <<= 1; // If there is a number which adds up with a[i] // to form a power of two if (map.containsKey(cur - a[i])) { // Edge case when a[i] and crr - a[i] is same // and we have only one occurrence of a[i] then // it cannot be paired if (cur - a[i] == a[i] && map.get(a[i]) == 1) continue; count++; // Remove already paired elements map.put(cur - a[i], map.get(cur - a[i]) - 1); map.put(a[i], map.get(a[i]) - 1); } } // Return the count return count; } // Driver code public static void main(String[] args) { int[] a = { 3, 11, 14, 5, 13 }; int n = a.length; System.out.println(countPairs(a, n)); }} // This code is contributed by Vivekkumar Singh", "e": 28964, "s": 27307, "text": null }, { "code": "# Python3 implementation of above approach # Function to return the count# of valid pairsdef countPairs(a, n) : # Storing occurrences of each element mp = dict.fromkeys(a, 0) for i in range(n) : mp[a[i]] += 1 # Sort the array in decreasing order a.sort(reverse = True) # Start taking largest element # each time count = 0 for i in range(n) : # If element has already been paired if (mp[a[i]] < 1) : continue # Find the number which is greater # than a[i] and power of two cur = 1 while (cur <= a[i]) : cur = cur << 1 # If there is a number which adds # up with a[i] to form a power of two if (cur - a[i] in mp.keys()) : # Edge case when a[i] and crr - a[i] # is same and we have only one occurrence # of a[i] then it cannot be paired if (cur - a[i] == a[i] and mp[a[i]] == 1) : continue count += 1 # Remove already paired elements mp[cur - a[i]] -= 1 mp[a[i]] -= 1 # Return the count return count # Driver codeif __name__ == \"__main__\" : a = [ 3, 11, 14, 5, 13 ] n = len(a) print(countPairs(a, n)) # This code is contributed by Ryuga", "e": 30251, "s": 28964, "text": null }, { "code": "// C# implementation of above approachusing System;using System.Collections.Generic; class GFG{ // Function to return the count of valid pairs static int countPairs(int[] a, int n) { // To keep the element in sorted order Dictionary<int, int> map = new Dictionary<int, int>(); for (int i = 0; i < n; i++) { if(!map.ContainsKey(a[i])) map.Add(a[i], 1); } // Start taking largest element each time int count = 0; for (int i = 0; i < n; i++) { // If element has already been paired if (map[a[i]] < 1) continue; // Find the number which is greater than // a[i] and power of two int cur = 1; while (cur <= a[i]) cur <<= 1; // If there is a number which adds up // with a[i] to form a power of two if (map.ContainsKey(cur - a[i])) { // Edge case when a[i] and crr - a[i] // is same and we have only one occurrence // of a[i] then it cannot be paired if (cur - a[i] == a[i] && map[a[i]] == 1) continue; count++; // Remove already paired elements map[cur - a[i]] = map[cur - a[i]] - 1; map[a[i]] = map[a[i]] - 1; } } // Return the count return count; } // Driver code public static void Main(String[] args) { int[] a = { 3, 11, 14, 5, 13 }; int n = a.Length; Console.WriteLine(countPairs(a, n)); }} // This code is contributed by Princi Singh", "e": 32017, "s": 30251, "text": null }, { "code": "<script> // JavaScript Program to implement// the above approach // Function to return the count of valid pairs function countPairs(a, n) { // To keep the element in sorted order let map = new Map(); for (let i = 0; i < n; i++) { map.set(a[i], 1); } // Start taking largest element each time let count = 0; for (let i = 0; i < n; i++) { // If element has already been paired if (map.get(a[i]) < 1) continue; // Find the number which is greater than // a[i] and power of two let cur = 1; while (cur <= a[i]) cur <<= 1; // If there is a number which adds up with a[i] // to form a power of two if (map.has(cur - a[i])) { // Edge case when a[i] and crr - a[i] is same // and we have only one occurrence of a[i] then // it cannot be paired if (cur - a[i] == a[i] && map.get(a[i]) == 1) continue; count++; // Remove already paired elements map.set(cur - a[i], map.get(cur - a[i]) - 1); map.set(a[i], map.get(a[i]) - 1); } } // Return the count return count; } // Driver Code let a = [ 3, 11, 14, 5, 13 ]; let n = a.length; document.write(countPairs(a, n)); </script>", "e": 33513, "s": 32017, "text": null }, { "code": null, "e": 33515, "s": 33513, "text": "2" }, { "code": null, "e": 33670, "s": 33517, "text": "Note that the below operation in above code can be done in O(1) time using the last approach discussed in Smallest power of 2 greater than or equal to n" }, { "code": null, "e": 33672, "s": 33670, "text": "C" }, { "code": "// Find the number which is greater than// a[i] and power of twoint cur = 1;while (cur <= a[i]) cur <<= 1;", "e": 33782, "s": 33672, "text": null }, { "code": null, "e": 33870, "s": 33782, "text": "After optimizing above expression, time complexity of this solution becomes O(n Log n) " }, { "code": null, "e": 33878, "s": 33870, "text": "ankthon" }, { "code": null, "e": 33895, "s": 33878, "text": "Vivekkumar Singh" }, { "code": null, "e": 33908, "s": 33895, "text": "princi singh" }, { "code": null, "e": 33930, "s": 33908, "text": "susmitakundugoaldanga" }, { "code": null, "e": 33944, "s": 33930, "text": "sumitgumber28" }, { "code": null, "e": 33951, "s": 33944, "text": "Arrays" }, { "code": null, "e": 33961, "s": 33951, "text": "Bit Magic" }, { "code": null, "e": 33974, "s": 33961, "text": "C++ Programs" }, { "code": null, "e": 33979, "s": 33974, "text": "Hash" }, { "code": null, "e": 33987, "s": 33979, "text": "Sorting" }, { "code": null, "e": 33994, "s": 33987, "text": "Arrays" }, { "code": null, "e": 33999, "s": 33994, "text": "Hash" }, { "code": null, "e": 34009, "s": 33999, "text": "Bit Magic" }, { "code": null, "e": 34017, "s": 34009, "text": "Sorting" }, { "code": null, "e": 34115, "s": 34017, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 34124, "s": 34115, "text": "Comments" }, { "code": null, "e": 34137, "s": 34124, "text": "Old Comments" }, { "code": null, "e": 34185, "s": 34137, "text": "Stack Data Structure (Introduction and Program)" }, { "code": null, "e": 34229, "s": 34185, "text": "Top 50 Array Coding Problems for Interviews" }, { "code": null, "e": 34252, "s": 34229, "text": "Introduction to Arrays" }, { "code": null, "e": 34266, "s": 34252, "text": "Linear Search" }, { "code": null, "e": 34334, "s": 34266, "text": "Maximum and minimum of an array using minimum number of comparisons" }, { "code": null, "e": 34361, "s": 34334, "text": "Bitwise Operators in C/C++" }, { "code": null, "e": 34407, "s": 34361, "text": "Left Shift and Right Shift Operators in C/C++" }, { "code": null, "e": 34453, "s": 34407, "text": "Cyclic Redundancy Check and Modulo-2 Division" }, { "code": null, "e": 34521, "s": 34453, "text": "Travelling Salesman Problem | Set 1 (Naive and Dynamic Programming)" } ]
Matplotlib - Simple Plot
In this chapter, we will learn how to create a simple plot with Matplotlib. We shall now display a simple line plot of angle in radians vs. its sine value in Matplotlib. To begin with, the Pyplot module from Matplotlib package is imported, with an alias plt as a matter of convention. import matplotlib.pyplot as plt Next we need an array of numbers to plot. Various array functions are defined in the NumPy library which is imported with the np alias. import numpy as np We now obtain the ndarray object of angles between 0 and 2π using the arange() function from the NumPy library. x = np.arange(0, math.pi*2, 0.05) The ndarray object serves as values on x axis of the graph. The corresponding sine values of angles in x to be displayed on y axis are obtained by the following statement − y = np.sin(x) The values from two arrays are plotted using the plot() function. plt.plot(x,y) You can set the plot title, and labels for x and y axes. You can set the plot title, and labels for x and y axes. plt.xlabel("angle") plt.ylabel("sine") plt.title('sine wave') The Plot viewer window is invoked by the show() function − plt.show() The complete program is as follows − from matplotlib import pyplot as plt import numpy as np import math #needed for definition of pi x = np.arange(0, math.pi*2, 0.05) y = np.sin(x) plt.plot(x,y) plt.xlabel("angle") plt.ylabel("sine") plt.title('sine wave') plt.show() When the above line of code is executed, the following graph is displayed − Now, use the Jupyter notebook with Matplotlib. Launch the Jupyter notebook from Anaconda navigator or command line as described earlier. In the input cell, enter import statements for Pyplot and NumPy − from matplotlib import pyplot as plt import numpy as np To display plot outputs inside the notebook itself (and not in the separate viewer), enter the following magic statement − %matplotlib inline Obtain x as the ndarray object containing angles in radians between 0 to 2π, and y as sine value of each angle − import math x = np.arange(0, math.pi*2, 0.05) y = np.sin(x) Set labels for x and y axes as well as the plot title − plt.xlabel("angle") plt.ylabel("sine") plt.title('sine wave') Finally execute the plot() function to generate the sine wave display in the notebook (no need to run the show() function) − plt.plot(x,y) After the execution of the final line of code, the following output is displayed − 63 Lectures 6 hours Abhilash Nelson 11 Lectures 4 hours DATAhill Solutions Srinivas Reddy 9 Lectures 2.5 hours DATAhill Solutions Srinivas Reddy 32 Lectures 4 hours Aipython 10 Lectures 2.5 hours Akbar Khan 63 Lectures 6 hours Anmol Print Add Notes Bookmark this page
[ { "code": null, "e": 2592, "s": 2516, "text": "In this chapter, we will learn how to create a simple plot with Matplotlib." }, { "code": null, "e": 2801, "s": 2592, "text": "We shall now display a simple line plot of angle in radians vs. its sine value in Matplotlib. To begin with, the Pyplot module from Matplotlib package is imported, with an alias plt as a matter of convention." }, { "code": null, "e": 2833, "s": 2801, "text": "import matplotlib.pyplot as plt" }, { "code": null, "e": 2969, "s": 2833, "text": "Next we need an array of numbers to plot. Various array functions are defined in the NumPy library which is imported with the np alias." }, { "code": null, "e": 2988, "s": 2969, "text": "import numpy as np" }, { "code": null, "e": 3100, "s": 2988, "text": "We now obtain the ndarray object of angles between 0 and 2π using the arange() function from the NumPy library." }, { "code": null, "e": 3134, "s": 3100, "text": "x = np.arange(0, math.pi*2, 0.05)" }, { "code": null, "e": 3307, "s": 3134, "text": "The ndarray object serves as values on x axis of the graph. The corresponding sine values of angles in x to be displayed on y axis are obtained by the following statement −" }, { "code": null, "e": 3321, "s": 3307, "text": "y = np.sin(x)" }, { "code": null, "e": 3387, "s": 3321, "text": "The values from two arrays are plotted using the plot() function." }, { "code": null, "e": 3401, "s": 3387, "text": "plt.plot(x,y)" }, { "code": null, "e": 3458, "s": 3401, "text": "You can set the plot title, and labels for x and y axes." }, { "code": null, "e": 3577, "s": 3458, "text": "You can set the plot title, and labels for x and y axes.\nplt.xlabel(\"angle\")\nplt.ylabel(\"sine\")\nplt.title('sine wave')" }, { "code": null, "e": 3636, "s": 3577, "text": "The Plot viewer window is invoked by the show() function −" }, { "code": null, "e": 3647, "s": 3636, "text": "plt.show()" }, { "code": null, "e": 3684, "s": 3647, "text": "The complete program is as follows −" }, { "code": null, "e": 3916, "s": 3684, "text": "from matplotlib import pyplot as plt\nimport numpy as np\nimport math #needed for definition of pi\nx = np.arange(0, math.pi*2, 0.05)\ny = np.sin(x)\nplt.plot(x,y)\nplt.xlabel(\"angle\")\nplt.ylabel(\"sine\")\nplt.title('sine wave')\nplt.show()" }, { "code": null, "e": 3992, "s": 3916, "text": "When the above line of code is executed, the following graph is displayed −" }, { "code": null, "e": 4039, "s": 3992, "text": "Now, use the Jupyter notebook with Matplotlib." }, { "code": null, "e": 4195, "s": 4039, "text": "Launch the Jupyter notebook from Anaconda navigator or command line as described earlier. In the input cell, enter import statements for Pyplot and NumPy −" }, { "code": null, "e": 4251, "s": 4195, "text": "from matplotlib import pyplot as plt\nimport numpy as np" }, { "code": null, "e": 4374, "s": 4251, "text": "To display plot outputs inside the notebook itself (and not in the separate viewer), enter the following magic statement −" }, { "code": null, "e": 4393, "s": 4374, "text": "%matplotlib inline" }, { "code": null, "e": 4506, "s": 4393, "text": "Obtain x as the ndarray object containing angles in radians between 0 to 2π, and y as sine value of each angle −" }, { "code": null, "e": 4566, "s": 4506, "text": "import math\nx = np.arange(0, math.pi*2, 0.05)\ny = np.sin(x)" }, { "code": null, "e": 4622, "s": 4566, "text": "Set labels for x and y axes as well as the plot title −" }, { "code": null, "e": 4684, "s": 4622, "text": "plt.xlabel(\"angle\")\nplt.ylabel(\"sine\")\nplt.title('sine wave')" }, { "code": null, "e": 4809, "s": 4684, "text": "Finally execute the plot() function to generate the sine wave display in the notebook (no need to run the show() function) −" }, { "code": null, "e": 4823, "s": 4809, "text": "plt.plot(x,y)" }, { "code": null, "e": 4906, "s": 4823, "text": "After the execution of the final line of code, the following output is displayed −" }, { "code": null, "e": 4939, "s": 4906, "text": "\n 63 Lectures \n 6 hours \n" }, { "code": null, "e": 4956, "s": 4939, "text": " Abhilash Nelson" }, { "code": null, "e": 4989, "s": 4956, "text": "\n 11 Lectures \n 4 hours \n" }, { "code": null, "e": 5024, "s": 4989, "text": " DATAhill Solutions Srinivas Reddy" }, { "code": null, "e": 5058, "s": 5024, "text": "\n 9 Lectures \n 2.5 hours \n" }, { "code": null, "e": 5093, "s": 5058, "text": " DATAhill Solutions Srinivas Reddy" }, { "code": null, "e": 5126, "s": 5093, "text": "\n 32 Lectures \n 4 hours \n" }, { "code": null, "e": 5136, "s": 5126, "text": " Aipython" }, { "code": null, "e": 5171, "s": 5136, "text": "\n 10 Lectures \n 2.5 hours \n" }, { "code": null, "e": 5183, "s": 5171, "text": " Akbar Khan" }, { "code": null, "e": 5216, "s": 5183, "text": "\n 63 Lectures \n 6 hours \n" }, { "code": null, "e": 5223, "s": 5216, "text": " Anmol" }, { "code": null, "e": 5230, "s": 5223, "text": " Print" }, { "code": null, "e": 5241, "s": 5230, "text": " Add Notes" } ]
Quickly Build and Deploy a Dashboard with Streamlit | by Maarten Grootendorst | Towards Data Science
With the launch of Streamlit, developing a dashboard for your machine learning solution has been made incredibly easy. Streamlit is an open source app framework specifically designed for ML engineers working with Python. It allows you to create a stunning looking application with only a few lines of code. I want to take this opportunity to demonstrate the apps you can build using Streamlit. But mostly, to show you the steps necessary to bring your application into production using Heroku. A few of the advantages of using Streamlit tools like Dash and Flask: It embraces Python scripting; No HTML knowledge is needed! Less code is needed to create a beautiful application No callbacks are needed since widgets are treated as variables Data caching simplifies and speeds up computation pipelines. Have a look at this post which might help you understand the architecture of Streamlit. Moreover, this post Streamlit can easily be installed with the following command: pip install streamlit Use the following command to see a demonstration of an application with example code: streamlit hello Doing this will result in the following page to be opened: Above from the streamlit hello demo above there are a few more complex demos available online for you to try out. I will list a few (including mine) below such that you will have an idea of the possibilities: This demo shows how the Udacity car dataset can be combined with object detection in less than 300 lines of code to create a complete Streamlit Demo app. First, install OpenCV so that the images can be analyzed: pip install --upgrade streamlit opencv-python Next, simply run the app: streamlit run https://raw.githubusercontent.com/streamlit/demo-self-driving/master/app.py This is a Streamlit demo to show how you can interactively visualize Uber pickups in New York City. Simply run the code below after installing Streamlit: streamlit run https://raw.githubusercontent.com/streamlit/demo-uber-nyc-pickups/master/app.py As many Board Game Geeks like myself track the scores of board game matches I decided to create an application allowing for the exploration of this data. You can view this application live here, or you can run it locally by following the steps below. Since I make use of several.py files, you first need to clone the repository: git clone https://github.com/MaartenGr/boardgame.git BoardGame Then, simply go to the folder and run Streamlit: cd BoardGamestreamlit run app.py NOTE: You can use your own data if you like by simply providing the URL to your data. In this section, I will demonstrate how to create a simple application seeing as the main purpose of this post is to prepare your project for deployment. If you want more in-depth examples check out Streamlits API or check this or this post which nicely describes many of its features. But first, let me introduce some basic features that you are likely to be using in your own apps. One of the main features of Streamlit is the usage of widgets. There are many widgets available including the following: SelectBox age = streamlit.selectbox("Choose your age: ", np.arange(18, 66, 1)) Slider age = streamlit.slider("Choose your age: ", min_value=16, max_value=66, value=35, step=1) MultiSelect artists = st.multiselect("Who are your favorite artists?", ["Michael Jackson", "Elvis Presley", "Eminem", "Billy Joel", "Madonna"]) The problem with many dashboarding tools is that data is reloaded every time you select an option or switch between pages. Fortunately, Streamlit has an amazing option allowing you to cache the data and only run it if it has not been run before. The code above shows that you can cache any function that you create. This may include loading data, but also preprocessing data or training a complex model once. Streamlit supports many visualization libraries including: Matplotlib, Altair, Vega-Lite, Plotly, Bokeh, Deck.GL, and Graphviz. It even can load audio and video! Below is a quick example of showing an Altair plot: Personally, I am a big fan of markdown and its possibilities of creating nicely looking and REAMDEs. Luckily, we can generate markdown with only a single function: NOTE: Based on the commits in the dev branch st.latex seems to be coming shortly! The Write function is the swiss-army knife of the Streamlit commands. It behaves differently based on its input. For example, if you throw in a Matplotlib figure it will automatically show you that visualization. A few examples: write(string) : Prints the formatted Markdown string. write(data_frame) : Displays the DataFrame as a table. write(dict) : Displays dictionary in an interactive widget. write(keras) : Displays a Keras model. write(plotly_fig) : Displays a Plotly figure. You can find a full overview of its possibilities here. To show how to deploy your application we first need to create a basic application. The example will be a simple demo that has two pages. On the homepage, it shows the data that we selected whereas the Exploration page allows you to visualize variables in an Altair plot. The code below gives you a Selectbox on the sidebar which allows you to select a page. The data is cached so that it does not need to reload constantly. Running the code streamlit run app.pywill show you the following page: Selecting the page Exploration will show you the following visualization: Now that we have our application it would be nice if we could host it online somewhere. That way, you can demonstrate the application that you made to others. We are going to do this by deploying it to Heroku, which is a platform as a service (PaaS) which can be used to run applications fully in the cloud. First, make sure you have the following files in your application folder: .├── app.py├── requirements.txt├── setup.sh└── Procfile You can find all these files in the repository here. To deploy the app you will first need to create an account on Heroku here. Do not worry, hosting your application is entirely Free! The main disadvantage of using a free account is that the website will go down if it has not been visited for more than half an hour. However, it will restart the moment you open the site. Next, you will need to install the Heroku Command Line Interface (CLI) here. You will use this to manage your application, run it locally, view its logs, and much more. After doing this, open your cmd.exe and cd to the application folder. Then, log in to Heroku with heroku login. You will be redirected to a login screen on your preferred browser. Finally, while having your cmd open in your application folder, first run heroku create to create a Heroku instance: Then, push all your code to that instance with git push heroku master: This will create a Heroku instance and push all code in your application folder to that instance. Now, the app should be deployed. Runheroku ps:scale web=1 to ensure that at least one instance of the app is running: Finally, open your application with heroku open: which will visit the app using your preferred browser at the URL generated by its app name: All code can be found here: github.com If you run into any problems when deploying to Heroku, please follow this page for an extensive overview of the procedure. If you are, like me, passionate about AI, Data Science or Psychology, please feel free to add me on LinkedIn.
[ { "code": null, "e": 291, "s": 172, "text": "With the launch of Streamlit, developing a dashboard for your machine learning solution has been made incredibly easy." }, { "code": null, "e": 479, "s": 291, "text": "Streamlit is an open source app framework specifically designed for ML engineers working with Python. It allows you to create a stunning looking application with only a few lines of code." }, { "code": null, "e": 666, "s": 479, "text": "I want to take this opportunity to demonstrate the apps you can build using Streamlit. But mostly, to show you the steps necessary to bring your application into production using Heroku." }, { "code": null, "e": 736, "s": 666, "text": "A few of the advantages of using Streamlit tools like Dash and Flask:" }, { "code": null, "e": 795, "s": 736, "text": "It embraces Python scripting; No HTML knowledge is needed!" }, { "code": null, "e": 849, "s": 795, "text": "Less code is needed to create a beautiful application" }, { "code": null, "e": 912, "s": 849, "text": "No callbacks are needed since widgets are treated as variables" }, { "code": null, "e": 973, "s": 912, "text": "Data caching simplifies and speeds up computation pipelines." }, { "code": null, "e": 1081, "s": 973, "text": "Have a look at this post which might help you understand the architecture of Streamlit. Moreover, this post" }, { "code": null, "e": 1143, "s": 1081, "text": "Streamlit can easily be installed with the following command:" }, { "code": null, "e": 1165, "s": 1143, "text": "pip install streamlit" }, { "code": null, "e": 1251, "s": 1165, "text": "Use the following command to see a demonstration of an application with example code:" }, { "code": null, "e": 1267, "s": 1251, "text": "streamlit hello" }, { "code": null, "e": 1326, "s": 1267, "text": "Doing this will result in the following page to be opened:" }, { "code": null, "e": 1535, "s": 1326, "text": "Above from the streamlit hello demo above there are a few more complex demos available online for you to try out. I will list a few (including mine) below such that you will have an idea of the possibilities:" }, { "code": null, "e": 1689, "s": 1535, "text": "This demo shows how the Udacity car dataset can be combined with object detection in less than 300 lines of code to create a complete Streamlit Demo app." }, { "code": null, "e": 1747, "s": 1689, "text": "First, install OpenCV so that the images can be analyzed:" }, { "code": null, "e": 1793, "s": 1747, "text": "pip install --upgrade streamlit opencv-python" }, { "code": null, "e": 1819, "s": 1793, "text": "Next, simply run the app:" }, { "code": null, "e": 1909, "s": 1819, "text": "streamlit run https://raw.githubusercontent.com/streamlit/demo-self-driving/master/app.py" }, { "code": null, "e": 2009, "s": 1909, "text": "This is a Streamlit demo to show how you can interactively visualize Uber pickups in New York City." }, { "code": null, "e": 2063, "s": 2009, "text": "Simply run the code below after installing Streamlit:" }, { "code": null, "e": 2157, "s": 2063, "text": "streamlit run https://raw.githubusercontent.com/streamlit/demo-uber-nyc-pickups/master/app.py" }, { "code": null, "e": 2408, "s": 2157, "text": "As many Board Game Geeks like myself track the scores of board game matches I decided to create an application allowing for the exploration of this data. You can view this application live here, or you can run it locally by following the steps below." }, { "code": null, "e": 2486, "s": 2408, "text": "Since I make use of several.py files, you first need to clone the repository:" }, { "code": null, "e": 2549, "s": 2486, "text": "git clone https://github.com/MaartenGr/boardgame.git BoardGame" }, { "code": null, "e": 2598, "s": 2549, "text": "Then, simply go to the folder and run Streamlit:" }, { "code": null, "e": 2631, "s": 2598, "text": "cd BoardGamestreamlit run app.py" }, { "code": null, "e": 2717, "s": 2631, "text": "NOTE: You can use your own data if you like by simply providing the URL to your data." }, { "code": null, "e": 2871, "s": 2717, "text": "In this section, I will demonstrate how to create a simple application seeing as the main purpose of this post is to prepare your project for deployment." }, { "code": null, "e": 3003, "s": 2871, "text": "If you want more in-depth examples check out Streamlits API or check this or this post which nicely describes many of its features." }, { "code": null, "e": 3101, "s": 3003, "text": "But first, let me introduce some basic features that you are likely to be using in your own apps." }, { "code": null, "e": 3222, "s": 3101, "text": "One of the main features of Streamlit is the usage of widgets. There are many widgets available including the following:" }, { "code": null, "e": 3232, "s": 3222, "text": "SelectBox" }, { "code": null, "e": 3301, "s": 3232, "text": "age = streamlit.selectbox(\"Choose your age: \", np.arange(18, 66, 1))" }, { "code": null, "e": 3308, "s": 3301, "text": "Slider" }, { "code": null, "e": 3423, "s": 3308, "text": "age = streamlit.slider(\"Choose your age: \", min_value=16, max_value=66, value=35, step=1)" }, { "code": null, "e": 3435, "s": 3423, "text": "MultiSelect" }, { "code": null, "e": 3616, "s": 3435, "text": "artists = st.multiselect(\"Who are your favorite artists?\", [\"Michael Jackson\", \"Elvis Presley\", \"Eminem\", \"Billy Joel\", \"Madonna\"])" }, { "code": null, "e": 3862, "s": 3616, "text": "The problem with many dashboarding tools is that data is reloaded every time you select an option or switch between pages. Fortunately, Streamlit has an amazing option allowing you to cache the data and only run it if it has not been run before." }, { "code": null, "e": 4025, "s": 3862, "text": "The code above shows that you can cache any function that you create. This may include loading data, but also preprocessing data or training a complex model once." }, { "code": null, "e": 4187, "s": 4025, "text": "Streamlit supports many visualization libraries including: Matplotlib, Altair, Vega-Lite, Plotly, Bokeh, Deck.GL, and Graphviz. It even can load audio and video!" }, { "code": null, "e": 4239, "s": 4187, "text": "Below is a quick example of showing an Altair plot:" }, { "code": null, "e": 4403, "s": 4239, "text": "Personally, I am a big fan of markdown and its possibilities of creating nicely looking and REAMDEs. Luckily, we can generate markdown with only a single function:" }, { "code": null, "e": 4485, "s": 4403, "text": "NOTE: Based on the commits in the dev branch st.latex seems to be coming shortly!" }, { "code": null, "e": 4698, "s": 4485, "text": "The Write function is the swiss-army knife of the Streamlit commands. It behaves differently based on its input. For example, if you throw in a Matplotlib figure it will automatically show you that visualization." }, { "code": null, "e": 4714, "s": 4698, "text": "A few examples:" }, { "code": null, "e": 4768, "s": 4714, "text": "write(string) : Prints the formatted Markdown string." }, { "code": null, "e": 4823, "s": 4768, "text": "write(data_frame) : Displays the DataFrame as a table." }, { "code": null, "e": 4883, "s": 4823, "text": "write(dict) : Displays dictionary in an interactive widget." }, { "code": null, "e": 4922, "s": 4883, "text": "write(keras) : Displays a Keras model." }, { "code": null, "e": 4968, "s": 4922, "text": "write(plotly_fig) : Displays a Plotly figure." }, { "code": null, "e": 5024, "s": 4968, "text": "You can find a full overview of its possibilities here." }, { "code": null, "e": 5296, "s": 5024, "text": "To show how to deploy your application we first need to create a basic application. The example will be a simple demo that has two pages. On the homepage, it shows the data that we selected whereas the Exploration page allows you to visualize variables in an Altair plot." }, { "code": null, "e": 5449, "s": 5296, "text": "The code below gives you a Selectbox on the sidebar which allows you to select a page. The data is cached so that it does not need to reload constantly." }, { "code": null, "e": 5520, "s": 5449, "text": "Running the code streamlit run app.pywill show you the following page:" }, { "code": null, "e": 5594, "s": 5520, "text": "Selecting the page Exploration will show you the following visualization:" }, { "code": null, "e": 5902, "s": 5594, "text": "Now that we have our application it would be nice if we could host it online somewhere. That way, you can demonstrate the application that you made to others. We are going to do this by deploying it to Heroku, which is a platform as a service (PaaS) which can be used to run applications fully in the cloud." }, { "code": null, "e": 5976, "s": 5902, "text": "First, make sure you have the following files in your application folder:" }, { "code": null, "e": 6032, "s": 5976, "text": ".├── app.py├── requirements.txt├── setup.sh└── Procfile" }, { "code": null, "e": 6085, "s": 6032, "text": "You can find all these files in the repository here." }, { "code": null, "e": 6217, "s": 6085, "text": "To deploy the app you will first need to create an account on Heroku here. Do not worry, hosting your application is entirely Free!" }, { "code": null, "e": 6406, "s": 6217, "text": "The main disadvantage of using a free account is that the website will go down if it has not been visited for more than half an hour. However, it will restart the moment you open the site." }, { "code": null, "e": 6575, "s": 6406, "text": "Next, you will need to install the Heroku Command Line Interface (CLI) here. You will use this to manage your application, run it locally, view its logs, and much more." }, { "code": null, "e": 6755, "s": 6575, "text": "After doing this, open your cmd.exe and cd to the application folder. Then, log in to Heroku with heroku login. You will be redirected to a login screen on your preferred browser." }, { "code": null, "e": 6872, "s": 6755, "text": "Finally, while having your cmd open in your application folder, first run heroku create to create a Heroku instance:" }, { "code": null, "e": 6943, "s": 6872, "text": "Then, push all your code to that instance with git push heroku master:" }, { "code": null, "e": 7074, "s": 6943, "text": "This will create a Heroku instance and push all code in your application folder to that instance. Now, the app should be deployed." }, { "code": null, "e": 7159, "s": 7074, "text": "Runheroku ps:scale web=1 to ensure that at least one instance of the app is running:" }, { "code": null, "e": 7300, "s": 7159, "text": "Finally, open your application with heroku open: which will visit the app using your preferred browser at the URL generated by its app name:" }, { "code": null, "e": 7328, "s": 7300, "text": "All code can be found here:" }, { "code": null, "e": 7339, "s": 7328, "text": "github.com" }, { "code": null, "e": 7462, "s": 7339, "text": "If you run into any problems when deploying to Heroku, please follow this page for an extensive overview of the procedure." } ]
How to implement merge sort in JavaScript?
Merge sort is an example of a divide-and-conquer type sorting-algorithm.The input of merge sort is an array of some elements, which are need to be arranged typically from least to the greatest. Merge sort divides the array in to two sub arrays and later divides each array in to another two arrays and so on until a bunch of single element arrays are left. For instance, in the following example the array [4,7,5,9,1,3,8,2] divides in to single array elements such as [4], [7], [5], [9], [1], [3], [8], [2]. It starts comparing arrays in such a manner that two arrays are compared and concatenated. In the following example, it compares two arrays at a time that is [4], [7] are compared and concatenated then [5], [9] are compared and concatenated and so on such that arrays [4,7], [5,9], [1,3], [2,8] are formed. It follows the same way that is two-two arrays are compared and concatenated to form two arrays. In the following example [4,7] and [5,9] are compared and concatenated to get an array as [4,5,7,9] and same is the case with other two arrays to form an array as [1,2,3,8]. Same rule applicable here that is the remaining two arrays compares and concatenates to get a final array as [1,2,3,4,5,7,8,9]. Live Demo <html> <body> <script> function mSort (array) { if (array.length === 1) { return array // return once we hit an array with a single item } const middle = Math.floor(array.length / 2) // get the middle item of the array rounded down const left = array.slice(0, middle) // items on the left side const right = array.slice(middle) // items on the right side document.write(middle); return merge( mSort(left), mSort(right) ) } // compare the arrays item by item and return the concatenated result function merge (left, right) { let result = [] let leftIndex = 0 let rightIndex = 0 while (leftIndex < left.length && rightIndex < right.length) { if (left[leftIndex] < right[rightIndex]) { result.push(left[leftIndex]) leftIndex++ document.write("</br>"); } else { result.push(right[rightIndex]) rightIndex++ } } return result.concat(left.slice(leftIndex)).concat(right.slice(rightIndex)) } const list = [4,7,5,9,1,3,8,2] document.write(mSort(list)); </script> </body> </html> 1,2,3,4,5,7,8,9
[ { "code": null, "e": 1257, "s": 1062, "text": "Merge sort is an example of a divide-and-conquer type sorting-algorithm.The input of merge sort is an array of some elements, which are need to be arranged typically from least to the greatest. " }, { "code": null, "e": 1571, "s": 1257, "text": "Merge sort divides the array in to two sub arrays and later divides each array in to another two arrays and so on until a bunch of single element arrays are left. For instance, in the following example the array [4,7,5,9,1,3,8,2] divides in to single array elements such as [4], [7], [5], [9], [1], [3], [8], [2]." }, { "code": null, "e": 1879, "s": 1571, "text": "It starts comparing arrays in such a manner that two arrays are compared and concatenated. In the following example, it compares two arrays at a time that is [4], [7] are compared and concatenated then [5], [9] are compared and concatenated and so on such that arrays [4,7], [5,9], [1,3], [2,8] are formed." }, { "code": null, "e": 2151, "s": 1879, "text": "It follows the same way that is two-two arrays are compared and concatenated to form two arrays. In the following example [4,7] and [5,9] are compared and concatenated to get an array as [4,5,7,9] and same is the case with other two arrays to form an array as [1,2,3,8]." }, { "code": null, "e": 2279, "s": 2151, "text": "Same rule applicable here that is the remaining two arrays compares and concatenates to get a final array as [1,2,3,4,5,7,8,9]." }, { "code": null, "e": 2289, "s": 2279, "text": "Live Demo" }, { "code": null, "e": 3492, "s": 2289, "text": "<html>\n<body>\n<script>\n function mSort (array) {\n if (array.length === 1) {\n return array // return once we hit an array with a single item\n }\n const middle = Math.floor(array.length / 2) // get the middle item of the array rounded down\n const left = array.slice(0, middle) // items on the left side\n const right = array.slice(middle) // items on the right side\n document.write(middle);\n return merge(\n mSort(left),\n mSort(right)\n )\n }\n // compare the arrays item by item and return the concatenated result\n function merge (left, right) {\n let result = []\n let leftIndex = 0\n let rightIndex = 0\n while (leftIndex < left.length && rightIndex < right.length) {\n if (left[leftIndex] < right[rightIndex]) {\n result.push(left[leftIndex])\n leftIndex++\n document.write(\"</br>\"); \n } else {\n result.push(right[rightIndex])\n rightIndex++ \n }\n }\n return result.concat(left.slice(leftIndex)).concat(right.slice(rightIndex))\n }\n const list = [4,7,5,9,1,3,8,2]\n document.write(mSort(list));\n </script>\n </body>\n </html>" }, { "code": null, "e": 3508, "s": 3492, "text": "1,2,3,4,5,7,8,9" } ]
Genetic algorithm vs. Backtracking: N-Queen Problem | by Hirad Babayan | Towards Data Science
A few months ago, I got familiar with genetic algorithms. I started to read about it and I was pretty amazed by it. One of the most famous problems solved by genetic algorithms is the n-queen problem. I implemented my genetic solver, plus the famous old backtracking solver using python 3. I implemented a Chess class (backtracking solver) and a GeneticChess class (genetic solver). These classes both have an attribute board which is a two dimension list. Each row of the list is filled with N zeros. As you know, the backtracking solver is a simple function which starts solving the problem by putting a queen on the first row of the board and tries to put the second queen on the second row in a way it wouldn’t conflict the first one. It continues putting the queens on the board row by row until it puts the last one on the n-th row. If it couldn’t fill any tile on a row it would backtrack and change the position of the previous row’s queen. The following tree describes how the backtracking algorithm solves the 4-queen problem. The backtracking solver will find the solution for us. But as the N increases it becomes slower. If N=25, it would take 322.89 seconds to find the solution and when N=26, it would take forever! So an approach is needed which could find the solution pretty much quicker. Here’s the backtracking method: def solveBackTracking(self,col):if col >= self.size: self.solutions.append(self.board) return Truefor i in range(self.size): if self.isSafe(i,col): self.board[i][col] = 1 if self.solveBackTracking(col+1) == True: return True self.board[i][col] = 0return False One way is to solve the problem using genetic algorithms. So how does genetic algorithms work? The base idea comes from what happens in the nature. In an environment, there exists some chromosomes(or gens). These chromosomes combine together and create some children in the environment. The new chromosome is a combination of its parents’ DNA and also it mutates itself. Of course, the environment has a population limit. Since each chromosome is unique from others, it is understood that some are stronger than the others. Based on the law of nature the stronger creatures will make it to the next generation and the weaker ones will die. So, we expect that each generation consists of stronger chromosomes. That’s how a genetic algorithm works. The following steps should be taken to achieve a genetic algorithm: Create a chromosome representationCreate an utility functionCreate a crossover functionCreate a mutation functionCreate the environment Create a chromosome representation Create an utility function Create a crossover function Create a mutation function Create the environment Now let’s jump into these steps to create our genetic algorithm. Basically, a chromosome (also called gen) is a representation of a solution whether it’s valid or not. How are we going to represent a n-queen solution? One way is to create a 2 dimension list filled with 0 and then, fill it with N ones representing the position of the queen. This maybe the first thing that comes to the mind but it’s not actually good. A better and simpler representation is that the chromosome is a list of length N. Each index specifies a column of the board. The value of each index is between 0 and N-1 representing the the row of a queen in a column. The Utility function is a function that determines how good is a solution. So the function takes a gen as its parameter and returns a number which is the utility. In this case our utility function will evaluate the number of conflicts based on queen positions. It is the summation of the number of conflicts on the left side of each queen. So if the utility function returns 0, we know that there are no conflicts on the board, therefore, we have our solution. def utilityFunction(self,gen): hits = 0 board = self.createBoard(self.size) self.setBoard(board,gen) col = 0 for dna in gen: try: for i in range(col-1,-1,-1): if board[dna][i] == 1: hits+=1 for i,j in zip(range(dna-1,-1,-1),range(col-1,-1,-1)): if board[i][j] == 1: hits+=1 for i,j in zip(range(dna+1,self.size,1),range(col-1,-1,-1)): if board[i][j] == 1: hits+=1 col+=1 return hits As I said, the child chromosome is a combination of its parents’ DNA. This process is called Crossover. This function is the key function that makes the Genetic algorithm faster than the backtracking solver. There exists a lot of crossover functions and you can even implement your own. The function takes two chromosomes as the parameters. These are the parents and they are going to create new children chromosomes. I decided to swap the elements of the first list with the elements of the second list whenever the difference of two elements in one of the lists is less than 2. def crossOverGens(self,firstGen,secondGen): for i in range(1,len(firstGen)): if abs(firstGen[i-1] — firstGen[i])<2: firstGen[i],secondGen[i] = secondGen[i],firstGen[i] if abs(secondGen[i-1] — secondGen[i])<2: firstGen[i],secondGen[i] = secondGen[i],firstGen[i] After the crossover process the child is created. Now the child tries to change itself somehow to decrease the utility value. After the crossover, some elements could be redundant in the gen (e.g. [1,1,2,3]). The mutation function will remove the redundant elements and fill them with the elements which weren’t used in the gen. Also a two random elements will be selected from the left side and right side of the chromosome and they will be swapped. This method may decrease the utility. def MutantGen(self,gen): bound = self.size//2 from random import randint as rand leftSideIndex = rand(0,bound) RightSideIndex = rand(bound+1,self.size-1) newGen = [] for dna in gen: if dna not in newGen: newGen.append(dna) for i in range(self.size): if i not in newGen: newGen.append(i) gen = newGen gen[leftSideIndex],gen[RightSideIndex] = gen[RightSideIndex],gen[leftSideIndex] return gen Now that we have our functions, let’s create our environment and its merciless rules. First we initialize the first generation of the chromosomes which are just some random chromosomes. After that all chromosomes are checked in order to find out whether the solution already exists or not. If it didn’t exist the chromosomes start to create children. Since the population exceeds its limit the utility of each chromosome is calculated. The ones with higher utility (higher conflicts) will be removed from the environment and the ones with a lower utility will be selected. Now the second generation is created. This loop continues creating next generations until it finds the solution. def solveGA(self): self.initializeFirstGenereation() for gen in self.env: if self.isGoalGen(gen): return gen while True: self.crossOverAndMutant() self.env = self.makeSelection() if self.goalIndex >= 0 : try: return self.goal except IndexError: print(self.goalIndex) else: continue As I mentioned, the Backtracking solver could only solve the problem at maximum N=25 which took about 322.89 seconds to find the answer. The GA solver found the solution for N=25 in just 1.83 seconds. The crossover and mutation function that I implemented aren’t the best algorithms and still I got a pretty much quick result. I tested the GA solver from N=4 up to N=66 and the maximum time took for the algorithm to solve the problem was 125.93 seconds for N=66. I have even tried N=80 and get the solution in 122.82 seconds! This is amazing! The algorithm is based on random numbers. It might seem that it would be worse than the backtracking solver but the results are quite fascinating.I pretty much recommend implementing both B-Solver and GA-Solver yourself to see the magic of the Genetic Algorithms. You can find my code at my Github link. Hope you find this article helpful!
[ { "code": null, "e": 674, "s": 172, "text": "A few months ago, I got familiar with genetic algorithms. I started to read about it and I was pretty amazed by it. One of the most famous problems solved by genetic algorithms is the n-queen problem. I implemented my genetic solver, plus the famous old backtracking solver using python 3. I implemented a Chess class (backtracking solver) and a GeneticChess class (genetic solver). These classes both have an attribute board which is a two dimension list. Each row of the list is filled with N zeros." }, { "code": null, "e": 1121, "s": 674, "text": "As you know, the backtracking solver is a simple function which starts solving the problem by putting a queen on the first row of the board and tries to put the second queen on the second row in a way it wouldn’t conflict the first one. It continues putting the queens on the board row by row until it puts the last one on the n-th row. If it couldn’t fill any tile on a row it would backtrack and change the position of the previous row’s queen." }, { "code": null, "e": 1209, "s": 1121, "text": "The following tree describes how the backtracking algorithm solves the 4-queen problem." }, { "code": null, "e": 1511, "s": 1209, "text": "The backtracking solver will find the solution for us. But as the N increases it becomes slower. If N=25, it would take 322.89 seconds to find the solution and when N=26, it would take forever! So an approach is needed which could find the solution pretty much quicker. Here’s the backtracking method:" }, { "code": null, "e": 1804, "s": 1511, "text": "def solveBackTracking(self,col):if col >= self.size: self.solutions.append(self.board) return Truefor i in range(self.size): if self.isSafe(i,col): self.board[i][col] = 1 if self.solveBackTracking(col+1) == True: return True self.board[i][col] = 0return False" }, { "code": null, "e": 1899, "s": 1804, "text": "One way is to solve the problem using genetic algorithms. So how does genetic algorithms work?" }, { "code": null, "e": 2551, "s": 1899, "text": "The base idea comes from what happens in the nature. In an environment, there exists some chromosomes(or gens). These chromosomes combine together and create some children in the environment. The new chromosome is a combination of its parents’ DNA and also it mutates itself. Of course, the environment has a population limit. Since each chromosome is unique from others, it is understood that some are stronger than the others. Based on the law of nature the stronger creatures will make it to the next generation and the weaker ones will die. So, we expect that each generation consists of stronger chromosomes. That’s how a genetic algorithm works." }, { "code": null, "e": 2619, "s": 2551, "text": "The following steps should be taken to achieve a genetic algorithm:" }, { "code": null, "e": 2755, "s": 2619, "text": "Create a chromosome representationCreate an utility functionCreate a crossover functionCreate a mutation functionCreate the environment" }, { "code": null, "e": 2790, "s": 2755, "text": "Create a chromosome representation" }, { "code": null, "e": 2817, "s": 2790, "text": "Create an utility function" }, { "code": null, "e": 2845, "s": 2817, "text": "Create a crossover function" }, { "code": null, "e": 2872, "s": 2845, "text": "Create a mutation function" }, { "code": null, "e": 2895, "s": 2872, "text": "Create the environment" }, { "code": null, "e": 2960, "s": 2895, "text": "Now let’s jump into these steps to create our genetic algorithm." }, { "code": null, "e": 3535, "s": 2960, "text": "Basically, a chromosome (also called gen) is a representation of a solution whether it’s valid or not. How are we going to represent a n-queen solution? One way is to create a 2 dimension list filled with 0 and then, fill it with N ones representing the position of the queen. This maybe the first thing that comes to the mind but it’s not actually good. A better and simpler representation is that the chromosome is a list of length N. Each index specifies a column of the board. The value of each index is between 0 and N-1 representing the the row of a queen in a column." }, { "code": null, "e": 3996, "s": 3535, "text": "The Utility function is a function that determines how good is a solution. So the function takes a gen as its parameter and returns a number which is the utility. In this case our utility function will evaluate the number of conflicts based on queen positions. It is the summation of the number of conflicts on the left side of each queen. So if the utility function returns 0, we know that there are no conflicts on the board, therefore, we have our solution." }, { "code": null, "e": 4524, "s": 3996, "text": "def utilityFunction(self,gen): hits = 0 board = self.createBoard(self.size) self.setBoard(board,gen) col = 0 for dna in gen: try: for i in range(col-1,-1,-1): if board[dna][i] == 1: hits+=1 for i,j in zip(range(dna-1,-1,-1),range(col-1,-1,-1)): if board[i][j] == 1: hits+=1 for i,j in zip(range(dna+1,self.size,1),range(col-1,-1,-1)): if board[i][j] == 1: hits+=1 col+=1 return hits" }, { "code": null, "e": 5104, "s": 4524, "text": "As I said, the child chromosome is a combination of its parents’ DNA. This process is called Crossover. This function is the key function that makes the Genetic algorithm faster than the backtracking solver. There exists a lot of crossover functions and you can even implement your own. The function takes two chromosomes as the parameters. These are the parents and they are going to create new children chromosomes. I decided to swap the elements of the first list with the elements of the second list whenever the difference of two elements in one of the lists is less than 2." }, { "code": null, "e": 5404, "s": 5104, "text": "def crossOverGens(self,firstGen,secondGen): for i in range(1,len(firstGen)): if abs(firstGen[i-1] — firstGen[i])<2: firstGen[i],secondGen[i] = secondGen[i],firstGen[i] if abs(secondGen[i-1] — secondGen[i])<2: firstGen[i],secondGen[i] = secondGen[i],firstGen[i]" }, { "code": null, "e": 5893, "s": 5404, "text": "After the crossover process the child is created. Now the child tries to change itself somehow to decrease the utility value. After the crossover, some elements could be redundant in the gen (e.g. [1,1,2,3]). The mutation function will remove the redundant elements and fill them with the elements which weren’t used in the gen. Also a two random elements will be selected from the left side and right side of the chromosome and they will be swapped. This method may decrease the utility." }, { "code": null, "e": 6358, "s": 5893, "text": "def MutantGen(self,gen): bound = self.size//2 from random import randint as rand leftSideIndex = rand(0,bound) RightSideIndex = rand(bound+1,self.size-1) newGen = [] for dna in gen: if dna not in newGen: newGen.append(dna) for i in range(self.size): if i not in newGen: newGen.append(i) gen = newGen gen[leftSideIndex],gen[RightSideIndex] = gen[RightSideIndex],gen[leftSideIndex] return gen" }, { "code": null, "e": 7044, "s": 6358, "text": "Now that we have our functions, let’s create our environment and its merciless rules. First we initialize the first generation of the chromosomes which are just some random chromosomes. After that all chromosomes are checked in order to find out whether the solution already exists or not. If it didn’t exist the chromosomes start to create children. Since the population exceeds its limit the utility of each chromosome is calculated. The ones with higher utility (higher conflicts) will be removed from the environment and the ones with a lower utility will be selected. Now the second generation is created. This loop continues creating next generations until it finds the solution." }, { "code": null, "e": 7445, "s": 7044, "text": "def solveGA(self): self.initializeFirstGenereation() for gen in self.env: if self.isGoalGen(gen): return gen while True: self.crossOverAndMutant() self.env = self.makeSelection() if self.goalIndex >= 0 : try: return self.goal except IndexError: print(self.goalIndex) else: continue" }, { "code": null, "e": 8293, "s": 7445, "text": "As I mentioned, the Backtracking solver could only solve the problem at maximum N=25 which took about 322.89 seconds to find the answer. The GA solver found the solution for N=25 in just 1.83 seconds. The crossover and mutation function that I implemented aren’t the best algorithms and still I got a pretty much quick result. I tested the GA solver from N=4 up to N=66 and the maximum time took for the algorithm to solve the problem was 125.93 seconds for N=66. I have even tried N=80 and get the solution in 122.82 seconds! This is amazing! The algorithm is based on random numbers. It might seem that it would be worse than the backtracking solver but the results are quite fascinating.I pretty much recommend implementing both B-Solver and GA-Solver yourself to see the magic of the Genetic Algorithms. You can find my code at my Github link." } ]
Data profiling in Pandas using Python - GeeksforGeeks
04 May, 2020 Pandas is one of the most popular Python library mainly used for data manipulation and analysis. When we are working with large data, many times we need to perform Exploratory Data Analysis. We need to get the detailed description about different columns available and there relation, null check, data types, missing values, etc. So, Pandas profiling is the python module which does the EDA and gives detailed description just with a few lines of code. Installation: pip install pandas-profiling Example: #import the packagesimport pandas as pdimport pandas_profiling # read the filedf = pd.read_csv('Geeks.csv') # run the profile reportprofile = df.profile_report(title='Pandas Profiling Report') # save the report as html fileprofile.to_file(output_file="pandas_profiling1.html") # save the report as json fileprofile.to_file(output_file="pandas_profiling2.json") Output: HTML File: JSON File: python-modules Python-pandas Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Python Dictionary Enumerate() in Python Read a file line by line in Python Defaultdict in Python Different ways to create Pandas Dataframe sum() function in Python Iterate over a list in Python How to Install PIP on Windows ? Deque in Python Python String | replace()
[ { "code": null, "e": 24260, "s": 24232, "text": "\n04 May, 2020" }, { "code": null, "e": 24713, "s": 24260, "text": "Pandas is one of the most popular Python library mainly used for data manipulation and analysis. When we are working with large data, many times we need to perform Exploratory Data Analysis. We need to get the detailed description about different columns available and there relation, null check, data types, missing values, etc. So, Pandas profiling is the python module which does the EDA and gives detailed description just with a few lines of code." }, { "code": null, "e": 24727, "s": 24713, "text": "Installation:" }, { "code": null, "e": 24756, "s": 24727, "text": "pip install pandas-profiling" }, { "code": null, "e": 24765, "s": 24756, "text": "Example:" }, { "code": "#import the packagesimport pandas as pdimport pandas_profiling # read the filedf = pd.read_csv('Geeks.csv') # run the profile reportprofile = df.profile_report(title='Pandas Profiling Report') # save the report as html fileprofile.to_file(output_file=\"pandas_profiling1.html\") # save the report as json fileprofile.to_file(output_file=\"pandas_profiling2.json\")", "e": 25134, "s": 24765, "text": null }, { "code": null, "e": 25142, "s": 25134, "text": "Output:" }, { "code": null, "e": 25153, "s": 25142, "text": "HTML File:" }, { "code": null, "e": 25164, "s": 25153, "text": "JSON File:" }, { "code": null, "e": 25179, "s": 25164, "text": "python-modules" }, { "code": null, "e": 25193, "s": 25179, "text": "Python-pandas" }, { "code": null, "e": 25200, "s": 25193, "text": "Python" }, { "code": null, "e": 25298, "s": 25200, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 25307, "s": 25298, "text": "Comments" }, { "code": null, "e": 25320, "s": 25307, "text": "Old Comments" }, { "code": null, "e": 25338, "s": 25320, "text": "Python Dictionary" }, { "code": null, "e": 25360, "s": 25338, "text": "Enumerate() in Python" }, { "code": null, "e": 25395, "s": 25360, "text": "Read a file line by line in Python" }, { "code": null, "e": 25417, "s": 25395, "text": "Defaultdict in Python" }, { "code": null, "e": 25459, "s": 25417, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 25484, "s": 25459, "text": "sum() function in Python" }, { "code": null, "e": 25514, "s": 25484, "text": "Iterate over a list in Python" }, { "code": null, "e": 25546, "s": 25514, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 25562, "s": 25546, "text": "Deque in Python" } ]
Rearrange a linked list such that all even and odd positioned nodes are together - GeeksforGeeks
02 Nov, 2021 Rearrange a linked list in such a way that all odd position nodes are together and all even positions node are together, Examples: Input: 1->2->3->4 Output: 1->3->2->4 Input: 10->22->30->43->56->70 Output: 10->30->56->22->43->70 The important thing in this question is to make sure that all below cases are handled 1) Empty linked list 2) A linked list with only one node 3) A linked list with only two nodes 4) A linked list with an odd number of nodes 5) A linked list with an even number of nodesThe below program maintains two pointers ‘odd’ and ‘even’ for current nodes at odd and even positions respectively. We also store the first node of even linked list so that we can attach the even list at the end of odd list after all odd and even nodes are connected together in two different lists. C++ C Java Python3 C# Javascript // C++ program to rearrange a linked list in such a// way that all odd positioned node are stored before// all even positioned nodes#include<bits/stdc++.h>using namespace std; // Linked List Nodeclass Node{ public: int data; Node* next;}; // A utility function to create a new nodeNode* newNode(int key){ Node *temp = new Node; temp->data = key; temp->next = NULL; return temp;} // Rearranges given linked list such that all even// positioned nodes are before odd positioned.// Returns new head of linked List.Node *rearrangeEvenOdd(Node *head){ // Corner case if (head == NULL) return NULL; // Initialize first nodes of even and // odd lists Node *odd = head; Node *even = head->next; // Remember the first node of even list so // that we can connect the even list at the // end of odd list. Node *evenFirst = even; while (1) { // If there are no more nodes, then connect // first node of even list to the last node // of odd list if (!odd || !even || !(even->next)) { odd->next = evenFirst; break; } // Connecting odd nodes odd->next = even->next; odd = even->next; // If there are NO more even nodes after // current odd. if (odd->next == NULL) { even->next = NULL; odd->next = evenFirst; break; } // Connecting even nodes even->next = odd->next; even = odd->next; } return head;} // A utility function to print a linked listvoid printlist(Node * node){ while (node != NULL) { cout << node->data << "->"; node = node->next; } cout << "NULL" << endl;} // Driver codeint main(void){ Node *head = newNode(1); head->next = newNode(2); head->next->next = newNode(3); head->next->next->next = newNode(4); head->next->next->next->next = newNode(5); cout << "Given Linked List\n"; printlist(head); head = rearrangeEvenOdd(head); cout << "Modified Linked List\n"; printlist(head); return 0;} // This is code is contributed by rathbhupendra // C program to rearrange a linked list in such a// way that all odd positioned node are stored before// all even positioned nodes#include<bits/stdc++.h>using namespace std; // Linked List Nodestruct Node{ int data; struct Node* next;}; // A utility function to create a new nodeNode* newNode(int key){ Node *temp = new Node; temp->data = key; temp->next = NULL; return temp;} // Rearranges given linked list such that all even// positioned nodes are before odd positioned.// Returns new head of linked List.Node *rearrangeEvenOdd(Node *head){ // Corner case if (head == NULL) return NULL; // Initialize first nodes of even and // odd lists Node *odd = head; Node *even = head->next; // Remember the first node of even list so // that we can connect the even list at the // end of odd list. Node *evenFirst = even; while (1) { // If there are no more nodes, then connect // first node of even list to the last node // of odd list if (!odd || !even || !(even->next)) { odd->next = evenFirst; break; } // Connecting odd nodes odd->next = even->next; odd = even->next; // If there are NO more even nodes after // current odd. if (odd->next == NULL) { even->next = NULL; odd->next = evenFirst; break; } // Connecting even nodes even->next = odd->next; even = odd->next; } return head;} // A utility function to print a linked listvoid printlist(Node * node){ while (node != NULL) { cout << node->data << "->"; node = node->next; } cout << "NULL" << endl;} // Driver codeint main(void){ Node *head = newNode(1); head->next = newNode(2); head->next->next = newNode(3); head->next->next->next = newNode(4); head->next->next->next->next = newNode(5); cout << "Given Linked List\n"; printlist(head); head = rearrangeEvenOdd(head); cout << "\nModified Linked List\n"; printlist(head); return 0;} // Java program to rearrange a linked list// in such a way that all odd positioned // node are stored before all even positioned nodesclass GfG{ // Linked List Nodestatic class Node{ int data; Node next;} // A utility function to create a new nodestatic Node newNode(int key){ Node temp = new Node(); temp.data = key; temp.next = null; return temp;} // Rearranges given linked list// such that all even positioned// nodes are before odd positioned.// Returns new head of linked List.static Node rearrangeEvenOdd(Node head){ // Corner case if (head == null) return null; // Initialize first nodes of even and // odd lists Node odd = head; Node even = head.next; // Remember the first node of even list so // that we can connect the even list at the // end of odd list. Node evenFirst = even; while (1 == 1) { // If there are no more nodes, // then connect first node of even // list to the last node of odd list if (odd == null || even == null || (even.next) == null) { odd.next = evenFirst; break; } // Connecting odd nodes odd.next = even.next; odd = even.next; // If there are NO more even nodes // after current odd. if (odd.next == null) { even.next = null; odd.next = evenFirst; break; } // Connecting even nodes even.next = odd.next; even = odd.next; } return head;} // A utility function to print a linked liststatic void printlist(Node node){ while (node != null) { System.out.print(node.data + "->"); node = node.next; } System.out.println("NULL") ;} // Driver codepublic static void main(String[] args){ Node head = newNode(1); head.next = newNode(2); head.next.next = newNode(3); head.next.next.next = newNode(4); head.next.next.next.next = newNode(5); System.out.println("Given Linked List"); printlist(head); head = rearrangeEvenOdd(head); System.out.println("Modified Linked List"); printlist(head);}} // This code is contributed by Prerna saini # Python3 program to rearrange a linked list# in such a way that all odd positioned# node are stored before all even positioned nodes # Linked List Nodeclass Node: def __init__(self, d): self.data = d self.next = None class LinkedList: def __init__(self): self.head = None # A utility function to create # a new node def newNode(self, key): temp = Node(key) self.next = None return temp # Rearranges given linked list # such that all even positioned # nodes are before odd positioned. # Returns new head of linked List. def rearrangeEvenOdd(self, head): # Corner case if (self.head == None): return None # Initialize first nodes of # even and odd lists odd = self.head even = self.head.next # Remember the first node of even list so # that we can connect the even list at the # end of odd list. evenFirst = even while (1 == 1): # If there are no more nodes, # then connect first node of even # list to the last node of odd list if (odd == None or even == None or (even.next) == None): odd.next = evenFirst break # Connecting odd nodes odd.next = even.next odd = even.next # If there are NO more even nodes # after current odd. if (odd.next == None): even.next = None odd.next = evenFirst break # Connecting even nodes even.next = odd.next even = odd.next return head # A utility function to print a linked list def printlist(self, node): while (node != None): print(node.data, end = "") print("->", end = "") node = node.next print ("NULL") # 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 # Driver codell = LinkedList()ll.push(5)ll.push(4)ll.push(3)ll.push(2)ll.push(1)print ("Given Linked List")ll.printlist(ll.head) start = ll.rearrangeEvenOdd(ll.head) print ("\nModified Linked List")ll.printlist(start) # This code is contributed by Prerna Saini // C# program to rearrange a linked list// in such a way that all odd positioned// node are stored before all even positioned nodesusing System; class GfG{ // Linked List Node class Node { public int data; public Node next; } // A utility function to create a new node static Node newNode(int key) { Node temp = new Node(); temp.data = key; temp.next = null; return temp; } // Rearranges given linked list // such that all even positioned // nodes are before odd positioned. // Returns new head of linked List. static Node rearrangeEvenOdd(Node head) { // Corner case if (head == null) return null; // Initialize first nodes of even and // odd lists Node odd = head; Node even = head.next; // Remember the first node of even list so // that we can connect the even list at the // end of odd list. Node evenFirst = even; while (1 == 1) { // If there are no more nodes, // then connect first node of even // list to the last node of odd list if (odd == null || even == null || (even.next) == null) { odd.next = evenFirst; break; } // Connecting odd nodes odd.next = even.next; odd = even.next; // If there are NO more even nodes // after current odd. if (odd.next == null) { even.next = null; odd.next = evenFirst; break; } // Connecting even nodes even.next = odd.next; even = odd.next; } return head; } // A utility function to print a linked list static void printlist(Node node) { while (node != null) { Console.Write(node.data + "->"); node = node.next; } Console.WriteLine("NULL") ; } // Driver code public static void Main() { Node head = newNode(1); head.next = newNode(2); head.next.next = newNode(3); head.next.next.next = newNode(4); head.next.next.next.next = newNode(5); Console.WriteLine("Given Linked List"); printlist(head); head = rearrangeEvenOdd(head); Console.WriteLine("Modified Linked List"); printlist(head); }} /* This code is contributed PrinciRaj1992 */ <script> // Javascript program to rearrange a linked list// in such a way that all odd positioned // node are stored before all even positioned nodes // Linked List Node class Node { constructor() { this.data = 0; this.next = null; } } // A utility function to create a new node function newNode(key) {var temp = new Node(); temp.data = key; temp.next = null; return temp; } // Rearranges given linked list // such that all even positioned // nodes are before odd positioned. // Returns new head of linked List. function rearrangeEvenOdd(head) { // Corner case if (head == null) return null; // Initialize first nodes of even and // odd listsvar odd = head;var even = head.next; // Remember the first node of even list so // that we can connect the even list at the // end of odd list.var evenFirst = even; while (1 == 1) { // If there are no more nodes, // then connect first node of even // list to the last node of odd list if (odd == null || even == null || (even.next) == null) { odd.next = evenFirst; break; } // Connecting odd nodes odd.next = even.next; odd = even.next; // If there are NO more even nodes // after current odd. if (odd.next == null) { even.next = null; odd.next = evenFirst; break; } // Connecting even nodes even.next = odd.next; even = odd.next; } return head; } // A utility function to print a linked list function printlist(node) { while (node != null) { document.write(node.data + "->"); node = node.next; } document.write("NULL<br/>"); } // Driver code var head = newNode(1); head.next = newNode(2); head.next.next = newNode(3); head.next.next.next = newNode(4); head.next.next.next.next = newNode(5); document.write("Given Linked List<br/>"); printlist(head); head = rearrangeEvenOdd(head); document.write("Modified Linked List<br/>"); printlist(head); // This code contributed by gauravrajput1 </script> Output: Given Linked List 1->2->3->4->5->NULL Modified Linked List 1->3->5->2->4->NULL YouTubeGeeksforGeeks500K subscribersRearrange a linked list such that all even and odd positioned nodes are together | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 7:45•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=IUKRzbJac9o" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div> This article is contributed by Harsh Parikh.Please see here another code contributed by Gautam Singh.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 prerna saini princiraj1992 rathbhupendra GauravRajput1 ankita_saini Amazon Linked List Amazon Linked List Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Delete a node in a Doubly Linked List Given a linked list which is sorted, how will you insert in sorted way Insert a node at a specific position in a linked list Circular Linked List | Set 2 (Traversal) Program to implement Singly Linked List in C++ using class Swap nodes in a linked list without swapping data Priority Queue using Linked List Circular Singly Linked List | Insertion Real-time application of Data Structures Insertion Sort for Singly Linked List
[ { "code": null, "e": 24569, "s": 24541, "text": "\n02 Nov, 2021" }, { "code": null, "e": 24701, "s": 24569, "text": "Rearrange a linked list in such a way that all odd position nodes are together and all even positions node are together, Examples: " }, { "code": null, "e": 24806, "s": 24701, "text": "Input: 1->2->3->4\nOutput: 1->3->2->4\n\nInput: 10->22->30->43->56->70\nOutput: 10->30->56->22->43->70" }, { "code": null, "e": 25380, "s": 24808, "text": "The important thing in this question is to make sure that all below cases are handled 1) Empty linked list 2) A linked list with only one node 3) A linked list with only two nodes 4) A linked list with an odd number of nodes 5) A linked list with an even number of nodesThe below program maintains two pointers ‘odd’ and ‘even’ for current nodes at odd and even positions respectively. We also store the first node of even linked list so that we can attach the even list at the end of odd list after all odd and even nodes are connected together in two different lists. " }, { "code": null, "e": 25384, "s": 25380, "text": "C++" }, { "code": null, "e": 25386, "s": 25384, "text": "C" }, { "code": null, "e": 25391, "s": 25386, "text": "Java" }, { "code": null, "e": 25399, "s": 25391, "text": "Python3" }, { "code": null, "e": 25402, "s": 25399, "text": "C#" }, { "code": null, "e": 25413, "s": 25402, "text": "Javascript" }, { "code": "// C++ program to rearrange a linked list in such a// way that all odd positioned node are stored before// all even positioned nodes#include<bits/stdc++.h>using namespace std; // Linked List Nodeclass Node{ public: int data; Node* next;}; // A utility function to create a new nodeNode* newNode(int key){ Node *temp = new Node; temp->data = key; temp->next = NULL; return temp;} // Rearranges given linked list such that all even// positioned nodes are before odd positioned.// Returns new head of linked List.Node *rearrangeEvenOdd(Node *head){ // Corner case if (head == NULL) return NULL; // Initialize first nodes of even and // odd lists Node *odd = head; Node *even = head->next; // Remember the first node of even list so // that we can connect the even list at the // end of odd list. Node *evenFirst = even; while (1) { // If there are no more nodes, then connect // first node of even list to the last node // of odd list if (!odd || !even || !(even->next)) { odd->next = evenFirst; break; } // Connecting odd nodes odd->next = even->next; odd = even->next; // If there are NO more even nodes after // current odd. if (odd->next == NULL) { even->next = NULL; odd->next = evenFirst; break; } // Connecting even nodes even->next = odd->next; even = odd->next; } return head;} // A utility function to print a linked listvoid printlist(Node * node){ while (node != NULL) { cout << node->data << \"->\"; node = node->next; } cout << \"NULL\" << endl;} // Driver codeint main(void){ Node *head = newNode(1); head->next = newNode(2); head->next->next = newNode(3); head->next->next->next = newNode(4); head->next->next->next->next = newNode(5); cout << \"Given Linked List\\n\"; printlist(head); head = rearrangeEvenOdd(head); cout << \"Modified Linked List\\n\"; printlist(head); return 0;} // This is code is contributed by rathbhupendra", "e": 27561, "s": 25413, "text": null }, { "code": "// C program to rearrange a linked list in such a// way that all odd positioned node are stored before// all even positioned nodes#include<bits/stdc++.h>using namespace std; // Linked List Nodestruct Node{ int data; struct Node* next;}; // A utility function to create a new nodeNode* newNode(int key){ Node *temp = new Node; temp->data = key; temp->next = NULL; return temp;} // Rearranges given linked list such that all even// positioned nodes are before odd positioned.// Returns new head of linked List.Node *rearrangeEvenOdd(Node *head){ // Corner case if (head == NULL) return NULL; // Initialize first nodes of even and // odd lists Node *odd = head; Node *even = head->next; // Remember the first node of even list so // that we can connect the even list at the // end of odd list. Node *evenFirst = even; while (1) { // If there are no more nodes, then connect // first node of even list to the last node // of odd list if (!odd || !even || !(even->next)) { odd->next = evenFirst; break; } // Connecting odd nodes odd->next = even->next; odd = even->next; // If there are NO more even nodes after // current odd. if (odd->next == NULL) { even->next = NULL; odd->next = evenFirst; break; } // Connecting even nodes even->next = odd->next; even = odd->next; } return head;} // A utility function to print a linked listvoid printlist(Node * node){ while (node != NULL) { cout << node->data << \"->\"; node = node->next; } cout << \"NULL\" << endl;} // Driver codeint main(void){ Node *head = newNode(1); head->next = newNode(2); head->next->next = newNode(3); head->next->next->next = newNode(4); head->next->next->next->next = newNode(5); cout << \"Given Linked List\\n\"; printlist(head); head = rearrangeEvenOdd(head); cout << \"\\nModified Linked List\\n\"; printlist(head); return 0;}", "e": 29658, "s": 27561, "text": null }, { "code": "// Java program to rearrange a linked list// in such a way that all odd positioned // node are stored before all even positioned nodesclass GfG{ // Linked List Nodestatic class Node{ int data; Node next;} // A utility function to create a new nodestatic Node newNode(int key){ Node temp = new Node(); temp.data = key; temp.next = null; return temp;} // Rearranges given linked list// such that all even positioned// nodes are before odd positioned.// Returns new head of linked List.static Node rearrangeEvenOdd(Node head){ // Corner case if (head == null) return null; // Initialize first nodes of even and // odd lists Node odd = head; Node even = head.next; // Remember the first node of even list so // that we can connect the even list at the // end of odd list. Node evenFirst = even; while (1 == 1) { // If there are no more nodes, // then connect first node of even // list to the last node of odd list if (odd == null || even == null || (even.next) == null) { odd.next = evenFirst; break; } // Connecting odd nodes odd.next = even.next; odd = even.next; // If there are NO more even nodes // after current odd. if (odd.next == null) { even.next = null; odd.next = evenFirst; break; } // Connecting even nodes even.next = odd.next; even = odd.next; } return head;} // A utility function to print a linked liststatic void printlist(Node node){ while (node != null) { System.out.print(node.data + \"->\"); node = node.next; } System.out.println(\"NULL\") ;} // Driver codepublic static void main(String[] args){ Node head = newNode(1); head.next = newNode(2); head.next.next = newNode(3); head.next.next.next = newNode(4); head.next.next.next.next = newNode(5); System.out.println(\"Given Linked List\"); printlist(head); head = rearrangeEvenOdd(head); System.out.println(\"Modified Linked List\"); printlist(head);}} // This code is contributed by Prerna saini", "e": 31850, "s": 29658, "text": null }, { "code": "# Python3 program to rearrange a linked list# in such a way that all odd positioned# node are stored before all even positioned nodes # Linked List Nodeclass Node: def __init__(self, d): self.data = d self.next = None class LinkedList: def __init__(self): self.head = None # A utility function to create # a new node def newNode(self, key): temp = Node(key) self.next = None return temp # Rearranges given linked list # such that all even positioned # nodes are before odd positioned. # Returns new head of linked List. def rearrangeEvenOdd(self, head): # Corner case if (self.head == None): return None # Initialize first nodes of # even and odd lists odd = self.head even = self.head.next # Remember the first node of even list so # that we can connect the even list at the # end of odd list. evenFirst = even while (1 == 1): # If there are no more nodes, # then connect first node of even # list to the last node of odd list if (odd == None or even == None or (even.next) == None): odd.next = evenFirst break # Connecting odd nodes odd.next = even.next odd = even.next # If there are NO more even nodes # after current odd. if (odd.next == None): even.next = None odd.next = evenFirst break # Connecting even nodes even.next = odd.next even = odd.next return head # A utility function to print a linked list def printlist(self, node): while (node != None): print(node.data, end = \"\") print(\"->\", end = \"\") node = node.next print (\"NULL\") # 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 # Driver codell = LinkedList()ll.push(5)ll.push(4)ll.push(3)ll.push(2)ll.push(1)print (\"Given Linked List\")ll.printlist(ll.head) start = ll.rearrangeEvenOdd(ll.head) print (\"\\nModified Linked List\")ll.printlist(start) # This code is contributed by Prerna Saini", "e": 34247, "s": 31850, "text": null }, { "code": "// C# program to rearrange a linked list// in such a way that all odd positioned// node are stored before all even positioned nodesusing System; class GfG{ // Linked List Node class Node { public int data; public Node next; } // A utility function to create a new node static Node newNode(int key) { Node temp = new Node(); temp.data = key; temp.next = null; return temp; } // Rearranges given linked list // such that all even positioned // nodes are before odd positioned. // Returns new head of linked List. static Node rearrangeEvenOdd(Node head) { // Corner case if (head == null) return null; // Initialize first nodes of even and // odd lists Node odd = head; Node even = head.next; // Remember the first node of even list so // that we can connect the even list at the // end of odd list. Node evenFirst = even; while (1 == 1) { // If there are no more nodes, // then connect first node of even // list to the last node of odd list if (odd == null || even == null || (even.next) == null) { odd.next = evenFirst; break; } // Connecting odd nodes odd.next = even.next; odd = even.next; // If there are NO more even nodes // after current odd. if (odd.next == null) { even.next = null; odd.next = evenFirst; break; } // Connecting even nodes even.next = odd.next; even = odd.next; } return head; } // A utility function to print a linked list static void printlist(Node node) { while (node != null) { Console.Write(node.data + \"->\"); node = node.next; } Console.WriteLine(\"NULL\") ; } // Driver code public static void Main() { Node head = newNode(1); head.next = newNode(2); head.next.next = newNode(3); head.next.next.next = newNode(4); head.next.next.next.next = newNode(5); Console.WriteLine(\"Given Linked List\"); printlist(head); head = rearrangeEvenOdd(head); Console.WriteLine(\"Modified Linked List\"); printlist(head); }} /* This code is contributed PrinciRaj1992 */", "e": 36768, "s": 34247, "text": null }, { "code": "<script> // Javascript program to rearrange a linked list// in such a way that all odd positioned // node are stored before all even positioned nodes // Linked List Node class Node { constructor() { this.data = 0; this.next = null; } } // A utility function to create a new node function newNode(key) {var temp = new Node(); temp.data = key; temp.next = null; return temp; } // Rearranges given linked list // such that all even positioned // nodes are before odd positioned. // Returns new head of linked List. function rearrangeEvenOdd(head) { // Corner case if (head == null) return null; // Initialize first nodes of even and // odd listsvar odd = head;var even = head.next; // Remember the first node of even list so // that we can connect the even list at the // end of odd list.var evenFirst = even; while (1 == 1) { // If there are no more nodes, // then connect first node of even // list to the last node of odd list if (odd == null || even == null || (even.next) == null) { odd.next = evenFirst; break; } // Connecting odd nodes odd.next = even.next; odd = even.next; // If there are NO more even nodes // after current odd. if (odd.next == null) { even.next = null; odd.next = evenFirst; break; } // Connecting even nodes even.next = odd.next; even = odd.next; } return head; } // A utility function to print a linked list function printlist(node) { while (node != null) { document.write(node.data + \"->\"); node = node.next; } document.write(\"NULL<br/>\"); } // Driver code var head = newNode(1); head.next = newNode(2); head.next.next = newNode(3); head.next.next.next = newNode(4); head.next.next.next.next = newNode(5); document.write(\"Given Linked List<br/>\"); printlist(head); head = rearrangeEvenOdd(head); document.write(\"Modified Linked List<br/>\"); printlist(head); // This code contributed by gauravrajput1 </script>", "e": 39198, "s": 36768, "text": null }, { "code": null, "e": 39207, "s": 39198, "text": "Output: " }, { "code": null, "e": 39286, "s": 39207, "text": "Given Linked List\n1->2->3->4->5->NULL\nModified Linked List\n1->3->5->2->4->NULL" }, { "code": null, "e": 40167, "s": 39288, "text": "YouTubeGeeksforGeeks500K subscribersRearrange a linked list such that all even and odd positioned nodes are together | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 7:45•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=IUKRzbJac9o\" 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": 40614, "s": 40167, "text": "This article is contributed by Harsh Parikh.Please see here another code contributed by Gautam Singh.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": 40627, "s": 40614, "text": "prerna saini" }, { "code": null, "e": 40641, "s": 40627, "text": "princiraj1992" }, { "code": null, "e": 40655, "s": 40641, "text": "rathbhupendra" }, { "code": null, "e": 40669, "s": 40655, "text": "GauravRajput1" }, { "code": null, "e": 40682, "s": 40669, "text": "ankita_saini" }, { "code": null, "e": 40689, "s": 40682, "text": "Amazon" }, { "code": null, "e": 40701, "s": 40689, "text": "Linked List" }, { "code": null, "e": 40708, "s": 40701, "text": "Amazon" }, { "code": null, "e": 40720, "s": 40708, "text": "Linked List" }, { "code": null, "e": 40818, "s": 40720, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 40827, "s": 40818, "text": "Comments" }, { "code": null, "e": 40840, "s": 40827, "text": "Old Comments" }, { "code": null, "e": 40878, "s": 40840, "text": "Delete a node in a Doubly Linked List" }, { "code": null, "e": 40949, "s": 40878, "text": "Given a linked list which is sorted, how will you insert in sorted way" }, { "code": null, "e": 41003, "s": 40949, "text": "Insert a node at a specific position in a linked list" }, { "code": null, "e": 41044, "s": 41003, "text": "Circular Linked List | Set 2 (Traversal)" }, { "code": null, "e": 41103, "s": 41044, "text": "Program to implement Singly Linked List in C++ using class" }, { "code": null, "e": 41153, "s": 41103, "text": "Swap nodes in a linked list without swapping data" }, { "code": null, "e": 41186, "s": 41153, "text": "Priority Queue using Linked List" }, { "code": null, "e": 41226, "s": 41186, "text": "Circular Singly Linked List | Insertion" }, { "code": null, "e": 41267, "s": 41226, "text": "Real-time application of Data Structures" } ]
Scala - Basic Syntax
If you have a good understanding on Java, then it will be very easy for you to learn Scala. The biggest syntactic difference between Scala and Java is that the ';' line end character is optional. When we consider a Scala program, it can be defined as a collection of objects that communicate via invoking each other’s methods. Let us now briefly look into what do class, object, methods and instance variables mean. Object − Objects have states and behaviors. An object is an instance of a class. Example − A dog has states - color, name, breed as well as behaviors - wagging, barking, and eating. Object − Objects have states and behaviors. An object is an instance of a class. Example − A dog has states - color, name, breed as well as behaviors - wagging, barking, and eating. Class − A class can be defined as a template/blueprint that describes the behaviors/states that are related to the class. Class − A class can be defined as a template/blueprint that describes the behaviors/states that are related to the class. Methods − A method is basically a behavior. A class can contain many methods. It is in methods where the logics are written, data is manipulated and all the actions are executed. Methods − A method is basically a behavior. A class can contain many methods. It is in methods where the logics are written, data is manipulated and all the actions are executed. Fields − Each object has its unique set of instance variables, which are called fields. An object's state is created by the values assigned to these fields. Fields − Each object has its unique set of instance variables, which are called fields. An object's state is created by the values assigned to these fields. Closure − A closure is a function, whose return value depends on the value of one or more variables declared outside this function. Closure − A closure is a function, whose return value depends on the value of one or more variables declared outside this function. Traits − A trait encapsulates method and field definitions, which can then be reused by mixing them into classes. Traits are used to define object types by specifying the signature of the supported methods. Traits − A trait encapsulates method and field definitions, which can then be reused by mixing them into classes. Traits are used to define object types by specifying the signature of the supported methods. We can execute a Scala program in two modes: one is interactive mode and another is script mode. Open the command prompt and use the following command to open Scala. \>scala If Scala is installed in your system, the following output will be displayed − Welcome to Scala version 2.9.0.1 Type in expressions to have them evaluated. Type :help for more information. Type the following text to the right of the Scala prompt and press the Enter key − scala> println("Hello, Scala!"); It will produce the following result − Hello, Scala! Use the following instructions to write a Scala program in script mode. Open notepad and add the following code into it. object HelloWorld { /* This is my first java program. * This will print 'Hello World' as the output */ def main(args: Array[String]) { println("Hello, world!") // prints Hello World } } Save the file as − HelloWorld.scala. Open the command prompt window and go to the directory where the program file is saved. The ‘scalac’ command is used to compile the Scala program and it will generate a few class files in the current directory. One of them will be called HelloWorld.class. This is a bytecode which will run on Java Virtual Machine (JVM) using ‘scala’ command. Use the following command to compile and execute your Scala program. \> scalac HelloWorld.scala \> scala HelloWorld Hello, World! The following are the basic syntaxes and coding conventions in Scala programming. Case Sensitivity − Scala is case-sensitive, which means identifier Hello and hello would have different meaning in Scala. Case Sensitivity − Scala is case-sensitive, which means identifier Hello and hello would have different meaning in Scala. Class Names − For all class names, the first letter should be in Upper Case. If several words are used to form a name of the class, each inner word's first letter should be in Upper Case. Example − class MyFirstScalaClass. Class Names − For all class names, the first letter should be in Upper Case. If several words are used to form a name of the class, each inner word's first letter should be in Upper Case. Example − class MyFirstScalaClass. Method Names − All method names should start with a Lower Case letter. If multiple words are used to form the name of the method, then each inner word's first letter should be in Upper Case. Example − def myMethodName() Method Names − All method names should start with a Lower Case letter. If multiple words are used to form the name of the method, then each inner word's first letter should be in Upper Case. Example − def myMethodName() Program File Name − Name of the program file should exactly match the object name. When saving the file you should save it using the object name (Remember Scala is case-sensitive) and append ‘.scala’ to the end of the name. (If the file name and the object name do not match your program will not compile). Example − Assume 'HelloWorld' is the object name. Then the file should be saved as 'HelloWorld.scala'. Program File Name − Name of the program file should exactly match the object name. When saving the file you should save it using the object name (Remember Scala is case-sensitive) and append ‘.scala’ to the end of the name. (If the file name and the object name do not match your program will not compile). Example − Assume 'HelloWorld' is the object name. Then the file should be saved as 'HelloWorld.scala'. def main(args: Array[String]) − Scala program processing starts from the main() method which is a mandatory part of every Scala Program. def main(args: Array[String]) − Scala program processing starts from the main() method which is a mandatory part of every Scala Program. All Scala components require names. Names used for objects, classes, variables and methods are called identifiers. A keyword cannot be used as an identifier and identifiers are case-sensitive. Scala supports four types of identifiers. An alphanumeric identifier starts with a letter or an underscore, which can be followed by further letters, digits, or underscores. The '$' character is a reserved keyword in Scala and should not be used in identifiers. Following are legal alphanumeric identifiers − age, salary, _value, __1_value Following are illegal identifiers − $salary, 123abc, -salary An operator identifier consists of one or more operator characters. Operator characters are printable ASCII characters such as +, :, ?, ~ or #. Following are legal operator identifiers − + ++ ::: <?> :> The Scala compiler will internally "mangle" operator identifiers to turn them into legal Java identifiers with embedded $ characters. For instance, the identifier :-> would be represented internally as $colon$minus$greater. A mixed identifier consists of an alphanumeric identifier, which is followed by an underscore and an operator identifier. Following are legal mixed identifiers − unary_+, myvar_= Here, unary_+ used as a method name defines a unary + operator and myvar_= used as method name defines an assignment operator (operator overloading). A literal identifier is an arbitrary string enclosed in back ticks (` . . . `). Following are legal literal identifiers − `x` `<clinit>` `yield` The following list shows the reserved words in Scala. These reserved words may not be used as constant or variable or any other identifier names. Scala supports single-line and multi-line comments very similar to Java. Multi-line comments may be nested, but are required to be properly nested. All characters available inside any comment are ignored by Scala compiler. object HelloWorld { /* This is my first java program. * This will print 'Hello World' as the output * This is an example of multi-line comments. */ def main(args: Array[String]) { // Prints Hello World // This is also an example of single line comment. println("Hello, world!") } } A line containing only whitespace, possibly with a comment, is known as a blank line, and Scala totally ignores it. Tokens may be separated by whitespace characters and/or comments. Scala is a line-oriented language where statements may be terminated by semicolons (;) or newlines. A semicolon at the end of a statement is usually optional. You can type one if you want but you don't have to if the statement appears by itself on a single line. On the other hand, a semicolon is required if you write multiple statements on a single line. Below syntax is the usage of multiple statements. val s = "hello"; println(s) A package is a named module of code. For example, the Lift utility package is net.liftweb.util. The package declaration is the first non-comment line in the source file as follows − package com.liftcode.stuff Scala packages can be imported so that they can be referenced in the current compilation scope. The following statement imports the contents of the scala.xml package − import scala.xml._ You can import a single class and object, for example, HashMap from the scala.collection.mutable package − import scala.collection.mutable.HashMap You can import more than one class or object from a single package, for example, TreeMap and TreeSet from the scala.collection.immutable package − import scala.collection.immutable.{TreeMap, TreeSet} A marker trait that enables dynamic invocations. Instances x of this trait allow method invocations x.meth(args) for arbitrary method names meth and argument lists args as well as field accesses x.field for arbitrary field namesfield. This feature is introduced in Scala-2.10. If a call is not natively supported by x (i.e. if type checking fails), it is rewritten according to the following rules − foo.method("blah") ~~> foo.applyDynamic("method")("blah") foo.method(x = "blah") ~~> foo.applyDynamicNamed("method")(("x", "blah")) foo.method(x = 1, 2) ~~> foo.applyDynamicNamed("method")(("x", 1), ("", 2)) foo.field ~~> foo.selectDynamic("field") foo.varia = 10 ~~> foo.updateDynamic("varia")(10) foo.arr(10) = 13 ~~> foo.selectDynamic("arr").update(10, 13) foo.arr(10) ~~> foo.applyDynamic("arr")(10) 82 Lectures 7 hours Arnab Chakraborty 23 Lectures 1.5 hours Mukund Kumar Mishra 52 Lectures 1.5 hours Bigdata Engineer 76 Lectures 5.5 hours Bigdata Engineer 69 Lectures 7.5 hours Bigdata Engineer 46 Lectures 4.5 hours Stone River ELearning Print Add Notes Bookmark this page
[ { "code": null, "e": 2194, "s": 1998, "text": "If you have a good understanding on Java, then it will be very easy for you to learn Scala. The biggest syntactic difference between Scala and Java is that the ';' line end character is optional." }, { "code": null, "e": 2414, "s": 2194, "text": "When we consider a Scala program, it can be defined as a collection of objects that communicate via invoking each other’s methods. Let us now briefly look into what do class, object, methods and instance variables mean." }, { "code": null, "e": 2596, "s": 2414, "text": "Object − Objects have states and behaviors. An object is an instance of a class. Example − A dog has states - color, name, breed as well as behaviors - wagging, barking, and eating." }, { "code": null, "e": 2778, "s": 2596, "text": "Object − Objects have states and behaviors. An object is an instance of a class. Example − A dog has states - color, name, breed as well as behaviors - wagging, barking, and eating." }, { "code": null, "e": 2901, "s": 2778, "text": "Class − A class can be defined as a template/blueprint that describes the behaviors/states that are related to the class." }, { "code": null, "e": 3024, "s": 2901, "text": "Class − A class can be defined as a template/blueprint that describes the behaviors/states that are related to the class." }, { "code": null, "e": 3203, "s": 3024, "text": "Methods − A method is basically a behavior. A class can contain many methods. It is in methods where the logics are written, data is manipulated and all the actions are executed." }, { "code": null, "e": 3382, "s": 3203, "text": "Methods − A method is basically a behavior. A class can contain many methods. It is in methods where the logics are written, data is manipulated and all the actions are executed." }, { "code": null, "e": 3539, "s": 3382, "text": "Fields − Each object has its unique set of instance variables, which are called fields. An object's state is created by the values assigned to these fields." }, { "code": null, "e": 3696, "s": 3539, "text": "Fields − Each object has its unique set of instance variables, which are called fields. An object's state is created by the values assigned to these fields." }, { "code": null, "e": 3828, "s": 3696, "text": "Closure − A closure is a function, whose return value depends on the value of one or more variables declared outside this function." }, { "code": null, "e": 3960, "s": 3828, "text": "Closure − A closure is a function, whose return value depends on the value of one or more variables declared outside this function." }, { "code": null, "e": 4167, "s": 3960, "text": "Traits − A trait encapsulates method and field definitions, which can then be reused by mixing them into classes. Traits are used to define object types by specifying the signature of the supported methods." }, { "code": null, "e": 4374, "s": 4167, "text": "Traits − A trait encapsulates method and field definitions, which can then be reused by mixing them into classes. Traits are used to define object types by specifying the signature of the supported methods." }, { "code": null, "e": 4471, "s": 4374, "text": "We can execute a Scala program in two modes: one is interactive mode and another is script mode." }, { "code": null, "e": 4540, "s": 4471, "text": "Open the command prompt and use the following command to open Scala." }, { "code": null, "e": 4549, "s": 4540, "text": "\\>scala\n" }, { "code": null, "e": 4628, "s": 4549, "text": "If Scala is installed in your system, the following output will be displayed −" }, { "code": null, "e": 4739, "s": 4628, "text": "Welcome to Scala version 2.9.0.1\nType in expressions to have them evaluated.\nType :help for more information.\n" }, { "code": null, "e": 4822, "s": 4739, "text": "Type the following text to the right of the Scala prompt and press the Enter key −" }, { "code": null, "e": 4856, "s": 4822, "text": "scala> println(\"Hello, Scala!\");\n" }, { "code": null, "e": 4895, "s": 4856, "text": "It will produce the following result −" }, { "code": null, "e": 4910, "s": 4895, "text": "Hello, Scala!\n" }, { "code": null, "e": 5031, "s": 4910, "text": "Use the following instructions to write a Scala program in script mode. Open notepad and add the following code into it." }, { "code": null, "e": 5240, "s": 5031, "text": "object HelloWorld {\n /* This is my first java program. \n * This will print 'Hello World' as the output\n */\n def main(args: Array[String]) {\n println(\"Hello, world!\") // prints Hello World\n }\n}" }, { "code": null, "e": 5277, "s": 5240, "text": "Save the file as − HelloWorld.scala." }, { "code": null, "e": 5620, "s": 5277, "text": "Open the command prompt window and go to the directory where the program file is saved. The ‘scalac’ command is used to compile the Scala program and it will generate a few class files in the current directory. One of them will be called HelloWorld.class. This is a bytecode which will run on Java Virtual Machine (JVM) using ‘scala’ command." }, { "code": null, "e": 5689, "s": 5620, "text": "Use the following command to compile and execute your Scala program." }, { "code": null, "e": 5737, "s": 5689, "text": "\\> scalac HelloWorld.scala\n\\> scala HelloWorld\n" }, { "code": null, "e": 5752, "s": 5737, "text": "Hello, World!\n" }, { "code": null, "e": 5834, "s": 5752, "text": "The following are the basic syntaxes and coding conventions in Scala programming." }, { "code": null, "e": 5956, "s": 5834, "text": "Case Sensitivity − Scala is case-sensitive, which means identifier Hello and hello would have different meaning in Scala." }, { "code": null, "e": 6078, "s": 5956, "text": "Case Sensitivity − Scala is case-sensitive, which means identifier Hello and hello would have different meaning in Scala." }, { "code": null, "e": 6301, "s": 6078, "text": "Class Names − For all class names, the first letter should be in Upper Case. If several words are used to form a name of the class, each inner word's first letter should be in Upper Case.\nExample − class MyFirstScalaClass." }, { "code": null, "e": 6489, "s": 6301, "text": "Class Names − For all class names, the first letter should be in Upper Case. If several words are used to form a name of the class, each inner word's first letter should be in Upper Case." }, { "code": null, "e": 6524, "s": 6489, "text": "Example − class MyFirstScalaClass." }, { "code": null, "e": 6744, "s": 6524, "text": "Method Names − All method names should start with a Lower Case letter. If multiple words are used to form the name of the method, then each inner word's first letter should be in Upper Case.\nExample − def myMethodName()" }, { "code": null, "e": 6935, "s": 6744, "text": "Method Names − All method names should start with a Lower Case letter. If multiple words are used to form the name of the method, then each inner word's first letter should be in Upper Case." }, { "code": null, "e": 6964, "s": 6935, "text": "Example − def myMethodName()" }, { "code": null, "e": 7374, "s": 6964, "text": "Program File Name − Name of the program file should exactly match the object name. When saving the file you should save it using the object name (Remember Scala is case-sensitive) and append ‘.scala’ to the end of the name. (If the file name and the object name do not match your program will not compile).\nExample − Assume 'HelloWorld' is the object name. Then the file should be saved as 'HelloWorld.scala'." }, { "code": null, "e": 7681, "s": 7374, "text": "Program File Name − Name of the program file should exactly match the object name. When saving the file you should save it using the object name (Remember Scala is case-sensitive) and append ‘.scala’ to the end of the name. (If the file name and the object name do not match your program will not compile)." }, { "code": null, "e": 7784, "s": 7681, "text": "Example − Assume 'HelloWorld' is the object name. Then the file should be saved as 'HelloWorld.scala'." }, { "code": null, "e": 7921, "s": 7784, "text": "def main(args: Array[String]) − Scala program processing starts from the main() method which is a mandatory part of every Scala Program." }, { "code": null, "e": 8058, "s": 7921, "text": "def main(args: Array[String]) − Scala program processing starts from the main() method which is a mandatory part of every Scala Program." }, { "code": null, "e": 8293, "s": 8058, "text": "All Scala components require names. Names used for objects, classes, variables and methods are called identifiers. A keyword cannot be used as an identifier and identifiers are case-sensitive. Scala supports four types of identifiers." }, { "code": null, "e": 8513, "s": 8293, "text": "An alphanumeric identifier starts with a letter or an underscore, which can be followed by further letters, digits, or underscores. The '$' character is a reserved keyword in Scala and should not be used in identifiers." }, { "code": null, "e": 8560, "s": 8513, "text": "Following are legal alphanumeric identifiers −" }, { "code": null, "e": 8593, "s": 8560, "text": "age, salary, _value, __1_value\n" }, { "code": null, "e": 8629, "s": 8593, "text": "Following are illegal identifiers −" }, { "code": null, "e": 8655, "s": 8629, "text": "$salary, 123abc, -salary\n" }, { "code": null, "e": 8799, "s": 8655, "text": "An operator identifier consists of one or more operator characters. Operator characters are printable ASCII characters such as +, :, ?, ~ or #." }, { "code": null, "e": 8842, "s": 8799, "text": "Following are legal operator identifiers −" }, { "code": null, "e": 8858, "s": 8842, "text": "+ ++ ::: <?> :>" }, { "code": null, "e": 9082, "s": 8858, "text": "The Scala compiler will internally \"mangle\" operator identifiers to turn them into legal Java identifiers with embedded $ characters. For instance, the identifier :-> would be represented internally as $colon$minus$greater." }, { "code": null, "e": 9204, "s": 9082, "text": "A mixed identifier consists of an alphanumeric identifier, which is followed by an underscore and an operator identifier." }, { "code": null, "e": 9244, "s": 9204, "text": "Following are legal mixed identifiers −" }, { "code": null, "e": 9263, "s": 9244, "text": "unary_+, myvar_=\n" }, { "code": null, "e": 9413, "s": 9263, "text": "Here, unary_+ used as a method name defines a unary + operator and myvar_= used as method name defines an assignment operator (operator overloading)." }, { "code": null, "e": 9493, "s": 9413, "text": "A literal identifier is an arbitrary string enclosed in back ticks (` . . . `)." }, { "code": null, "e": 9535, "s": 9493, "text": "Following are legal literal identifiers −" }, { "code": null, "e": 9559, "s": 9535, "text": "`x` `<clinit>` `yield`\n" }, { "code": null, "e": 9705, "s": 9559, "text": "The following list shows the reserved words in Scala. These reserved words may not be used as constant or variable or any other identifier names." }, { "code": null, "e": 9928, "s": 9705, "text": "Scala supports single-line and multi-line comments very similar to Java. Multi-line comments may be nested, but are required to be properly nested. All characters available inside any comment are ignored by Scala compiler." }, { "code": null, "e": 10252, "s": 9928, "text": "object HelloWorld {\n /* This is my first java program. \n * This will print 'Hello World' as the output\n * This is an example of multi-line comments.\n */\n def main(args: Array[String]) {\n // Prints Hello World\n // This is also an example of single line comment.\n println(\"Hello, world!\") \n }\n}" }, { "code": null, "e": 10434, "s": 10252, "text": "A line containing only whitespace, possibly with a comment, is known as a blank line, and Scala totally ignores it. Tokens may be separated by whitespace characters and/or comments." }, { "code": null, "e": 10841, "s": 10434, "text": "Scala is a line-oriented language where statements may be terminated by semicolons (;) or newlines. A semicolon at the end of a statement is usually optional. You can type one if you want but you don't have to if the statement appears by itself on a single line. On the other hand, a semicolon is required if you write multiple statements on a single line. Below syntax is the usage of multiple statements." }, { "code": null, "e": 10869, "s": 10841, "text": "val s = \"hello\"; println(s)" }, { "code": null, "e": 11051, "s": 10869, "text": "A package is a named module of code. For example, the Lift utility package is net.liftweb.util. The package declaration is the first non-comment line in the source file as follows −" }, { "code": null, "e": 11079, "s": 11051, "text": "package com.liftcode.stuff\n" }, { "code": null, "e": 11247, "s": 11079, "text": "Scala packages can be imported so that they can be referenced in the current compilation scope. The following statement imports the contents of the scala.xml package −" }, { "code": null, "e": 11267, "s": 11247, "text": "import scala.xml._\n" }, { "code": null, "e": 11374, "s": 11267, "text": "You can import a single class and object, for example, HashMap from the scala.collection.mutable package −" }, { "code": null, "e": 11415, "s": 11374, "text": "import scala.collection.mutable.HashMap\n" }, { "code": null, "e": 11562, "s": 11415, "text": "You can import more than one class or object from a single package, for example, TreeMap and TreeSet from the scala.collection.immutable package −" }, { "code": null, "e": 11615, "s": 11562, "text": "import scala.collection.immutable.{TreeMap, TreeSet}" }, { "code": null, "e": 11892, "s": 11615, "text": "A marker trait that enables dynamic invocations. Instances x of this trait allow method invocations x.meth(args) for arbitrary method names meth and argument lists args as well as field accesses x.field for arbitrary field namesfield. This feature is introduced in Scala-2.10." }, { "code": null, "e": 12015, "s": 11892, "text": "If a call is not natively supported by x (i.e. if type checking fails), it is rewritten according to the following rules −" }, { "code": null, "e": 12420, "s": 12015, "text": "foo.method(\"blah\") ~~> foo.applyDynamic(\"method\")(\"blah\")\nfoo.method(x = \"blah\") ~~> foo.applyDynamicNamed(\"method\")((\"x\", \"blah\"))\nfoo.method(x = 1, 2) ~~> foo.applyDynamicNamed(\"method\")((\"x\", 1), (\"\", 2))\nfoo.field ~~> foo.selectDynamic(\"field\")\nfoo.varia = 10 ~~> foo.updateDynamic(\"varia\")(10)\nfoo.arr(10) = 13 ~~> foo.selectDynamic(\"arr\").update(10, 13)\nfoo.arr(10) ~~> foo.applyDynamic(\"arr\")(10)\n" }, { "code": null, "e": 12453, "s": 12420, "text": "\n 82 Lectures \n 7 hours \n" }, { "code": null, "e": 12472, "s": 12453, "text": " Arnab Chakraborty" }, { "code": null, "e": 12507, "s": 12472, "text": "\n 23 Lectures \n 1.5 hours \n" }, { "code": null, "e": 12528, "s": 12507, "text": " Mukund Kumar Mishra" }, { "code": null, "e": 12563, "s": 12528, "text": "\n 52 Lectures \n 1.5 hours \n" }, { "code": null, "e": 12581, "s": 12563, "text": " Bigdata Engineer" }, { "code": null, "e": 12616, "s": 12581, "text": "\n 76 Lectures \n 5.5 hours \n" }, { "code": null, "e": 12634, "s": 12616, "text": " Bigdata Engineer" }, { "code": null, "e": 12669, "s": 12634, "text": "\n 69 Lectures \n 7.5 hours \n" }, { "code": null, "e": 12687, "s": 12669, "text": " Bigdata Engineer" }, { "code": null, "e": 12722, "s": 12687, "text": "\n 46 Lectures \n 4.5 hours \n" }, { "code": null, "e": 12745, "s": 12722, "text": " Stone River ELearning" }, { "code": null, "e": 12752, "s": 12745, "text": " Print" }, { "code": null, "e": 12763, "s": 12752, "text": " Add Notes" } ]
jQuery | offset() with Examples - GeeksforGeeks
30 Aug, 2021 The offset() method is an inbuilt method in jQuery which is used to set or returns the offset coordinates of the selected element.Syntax: $(selector).offset() Parameters: Parameter does not required. $(selector).offset({top:value, left:value}) Parameters: The parameter is required when set the offset. $(selector).offset( function(index, offset) ) Parameters: This method set the offset using function. The parameter used in this method is optional. The index parameter is used to return the position of set element and offset return the coordinate of selected element. Return Value: This method returns the co-ordinate of matched elements.Below examples illustrate the offset() method in jQuery:Example 1: In the code below this will return the co-ordinate of the first matched element. html <!DOCTYPE html><html> <head> <title>The offset Method</title> <script src= "https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"> </script> <!-- jQuery code to show the working of this method --> <script> $(document).ready(function() { $("button").click(function() { var Geek = $("p").offset(); alert("Top coordinate: " + Geek.top + " Left Coordinate: " + Geek.left); }); }); </script> <style> div { width: 60%; min-height: 150px; padding: 20px; font-size: 25px; border: 2px solid green; font-weight: bold; color:green; } </style> </head> <body> <!-- Click on paragraph --> <div> <p>Welcome to GeeksforGeeks!</p> <button>click Here!</button> </div> </body></html> Output: Example 2: html <!DOCTYPE html><html> <head> <title>The offset Method</title> <script src= "https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"> </script> <!-- jQuery code to show the working of this method --> <script> $(document).ready(function() { $("button").click(function() { $("p").offset({top: 100, left: 140}); }); }); </script> <style> div{ width: 300px; min-height: 100px; color:green; font-weight: bold; padding:20px; font-size: 25px; border: 2px solid green; } </style> </head> <body> <div> <!-- Click on paragraph --> <p>Welcome to GeeksforGeeks!</p> <button>Click Here!</button> </div> </body></html> Output: sweetyty jQuery-HTML/CSS JavaScript JQuery Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Remove elements from a JavaScript Array Convert a string to an integer in JavaScript Difference between var, let and const keywords in JavaScript Differences between Functional Components and Class Components in React How to append HTML code to a div using JavaScript ? JQuery | Set the value of an input text field Form validation using jQuery How to change selected value of a drop-down list using jQuery? How to change the background color after clicking the button in JavaScript ? How to fetch data from JSON file and display in HTML table using jQuery ?
[ { "code": null, "e": 26352, "s": 26324, "text": "\n30 Aug, 2021" }, { "code": null, "e": 26492, "s": 26352, "text": "The offset() method is an inbuilt method in jQuery which is used to set or returns the offset coordinates of the selected element.Syntax: " }, { "code": null, "e": 26513, "s": 26492, "text": "$(selector).offset()" }, { "code": null, "e": 26554, "s": 26513, "text": "Parameters: Parameter does not required." }, { "code": null, "e": 26598, "s": 26554, "text": "$(selector).offset({top:value, left:value})" }, { "code": null, "e": 26657, "s": 26598, "text": "Parameters: The parameter is required when set the offset." }, { "code": null, "e": 26703, "s": 26657, "text": "$(selector).offset( function(index, offset) )" }, { "code": null, "e": 26925, "s": 26703, "text": "Parameters: This method set the offset using function. The parameter used in this method is optional. The index parameter is used to return the position of set element and offset return the coordinate of selected element." }, { "code": null, "e": 27144, "s": 26925, "text": "Return Value: This method returns the co-ordinate of matched elements.Below examples illustrate the offset() method in jQuery:Example 1: In the code below this will return the co-ordinate of the first matched element. " }, { "code": null, "e": 27149, "s": 27144, "text": "html" }, { "code": "<!DOCTYPE html><html> <head> <title>The offset Method</title> <script src= \"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js\"> </script> <!-- jQuery code to show the working of this method --> <script> $(document).ready(function() { $(\"button\").click(function() { var Geek = $(\"p\").offset(); alert(\"Top coordinate: \" + Geek.top + \" Left Coordinate: \" + Geek.left); }); }); </script> <style> div { width: 60%; min-height: 150px; padding: 20px; font-size: 25px; border: 2px solid green; font-weight: bold; color:green; } </style> </head> <body> <!-- Click on paragraph --> <div> <p>Welcome to GeeksforGeeks!</p> <button>click Here!</button> </div> </body></html>", "e": 28208, "s": 27149, "text": null }, { "code": null, "e": 28217, "s": 28208, "text": "Output: " }, { "code": null, "e": 28229, "s": 28217, "text": "Example 2: " }, { "code": null, "e": 28234, "s": 28229, "text": "html" }, { "code": "<!DOCTYPE html><html> <head> <title>The offset Method</title> <script src= \"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js\"> </script> <!-- jQuery code to show the working of this method --> <script> $(document).ready(function() { $(\"button\").click(function() { $(\"p\").offset({top: 100, left: 140}); }); }); </script> <style> div{ width: 300px; min-height: 100px; color:green; font-weight: bold; padding:20px; font-size: 25px; border: 2px solid green; } </style> </head> <body> <div> <!-- Click on paragraph --> <p>Welcome to GeeksforGeeks!</p> <button>Click Here!</button> </div> </body></html>", "e": 29116, "s": 28234, "text": null }, { "code": null, "e": 29126, "s": 29116, "text": "Output: " }, { "code": null, "e": 29135, "s": 29126, "text": "sweetyty" }, { "code": null, "e": 29151, "s": 29135, "text": "jQuery-HTML/CSS" }, { "code": null, "e": 29162, "s": 29151, "text": "JavaScript" }, { "code": null, "e": 29169, "s": 29162, "text": "JQuery" }, { "code": null, "e": 29267, "s": 29169, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29307, "s": 29267, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 29352, "s": 29307, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 29413, "s": 29352, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 29485, "s": 29413, "text": "Differences between Functional Components and Class Components in React" }, { "code": null, "e": 29537, "s": 29485, "text": "How to append HTML code to a div using JavaScript ?" }, { "code": null, "e": 29583, "s": 29537, "text": "JQuery | Set the value of an input text field" }, { "code": null, "e": 29612, "s": 29583, "text": "Form validation using jQuery" }, { "code": null, "e": 29675, "s": 29612, "text": "How to change selected value of a drop-down list using jQuery?" }, { "code": null, "e": 29752, "s": 29675, "text": "How to change the background color after clicking the button in JavaScript ?" } ]
DAX Logical - SWITCH function
Evaluates an expression against a list of values and returns one of multiple possible result expressions. SWITCH ( <expression>, <value>, <result>, [<value>, <result>] ..., [<else>] ) expression Any DAX expression that returns a single scalar value, where the expression is to be evaluated multiple times for each row/context. value A constant value to be matched with the results of expression. result Any scalar expression to be evaluated, if the results of expression match the corresponding value. else Optional. Any scalar expression to be evaluated, if the result of expression doesn't match any of the value arguments. A scalar value coming from one of the result expressions, if there was a match with value, or from the else expression, if there was no match with any value. All the result expressions and the else expression must be of the same data type. = SWITCH ( [Week Day], 1, "Sunday", 2, "Monday", 3, "Tuesday", 4, "Wednesday", 5, "Thursday", 6, "Friday", 7, "Saturday", "Unknown" ) This DAX formula returns a calculated column with the names of the Week Day values. 53 Lectures 5.5 hours Abhay Gadiya 24 Lectures 2 hours Randy Minder 26 Lectures 4.5 hours Randy Minder Print Add Notes Bookmark this page
[ { "code": null, "e": 2107, "s": 2001, "text": "Evaluates an expression against a list of values and returns one of multiple possible result expressions." }, { "code": null, "e": 2190, "s": 2107, "text": "SWITCH (\n <expression>, <value>, <result>, [<value>, <result>] ..., [<else>]\n) \n" }, { "code": null, "e": 2201, "s": 2190, "text": "expression" }, { "code": null, "e": 2333, "s": 2201, "text": "Any DAX expression that returns a single scalar value, where the expression is to be evaluated multiple times for each row/context." }, { "code": null, "e": 2339, "s": 2333, "text": "value" }, { "code": null, "e": 2402, "s": 2339, "text": "A constant value to be matched with the results of expression." }, { "code": null, "e": 2409, "s": 2402, "text": "result" }, { "code": null, "e": 2508, "s": 2409, "text": "Any scalar expression to be evaluated, if the results of expression match the corresponding value." }, { "code": null, "e": 2513, "s": 2508, "text": "else" }, { "code": null, "e": 2523, "s": 2513, "text": "Optional." }, { "code": null, "e": 2632, "s": 2523, "text": "Any scalar expression to be evaluated, if the result of expression doesn't match any of the value arguments." }, { "code": null, "e": 2790, "s": 2632, "text": "A scalar value coming from one of the result expressions, if there was a match with value, or from the else expression, if there was no match with any value." }, { "code": null, "e": 2872, "s": 2790, "text": "All the result expressions and the else expression must be of the same data type." }, { "code": null, "e": 3017, "s": 2872, "text": "= SWITCH (\n [Week Day], 1, \"Sunday\", 2, \"Monday\", 3, \"Tuesday\", 4, \"Wednesday\", \n 5, \"Thursday\", 6, \"Friday\", 7, \"Saturday\", \"Unknown\"\n) " }, { "code": null, "e": 3101, "s": 3017, "text": "This DAX formula returns a calculated column with the names of the Week Day values." }, { "code": null, "e": 3136, "s": 3101, "text": "\n 53 Lectures \n 5.5 hours \n" }, { "code": null, "e": 3150, "s": 3136, "text": " Abhay Gadiya" }, { "code": null, "e": 3183, "s": 3150, "text": "\n 24 Lectures \n 2 hours \n" }, { "code": null, "e": 3197, "s": 3183, "text": " Randy Minder" }, { "code": null, "e": 3232, "s": 3197, "text": "\n 26 Lectures \n 4.5 hours \n" }, { "code": null, "e": 3246, "s": 3232, "text": " Randy Minder" }, { "code": null, "e": 3253, "s": 3246, "text": " Print" }, { "code": null, "e": 3264, "s": 3253, "text": " Add Notes" } ]
How to drop one or multiple columns in Pandas Dataframe - GeeksforGeeks
21 May, 2021 Let’s discuss how to drop one or multiple columns in Pandas Dataframe. Drop one or more than one columns from a DataFrame can be achieved in multiple ways. Create a simple dataframe with dictionary of lists, say column names are A, B, C, D, E. # Import pandas package import pandas as pd # create a dictionary with five fields eachdata = { 'A':['A1', 'A2', 'A3', 'A4', 'A5'], 'B':['B1', 'B2', 'B3', 'B4', 'B5'], 'C':['C1', 'C2', 'C3', 'C4', 'C5'], 'D':['D1', 'D2', 'D3', 'D4', 'D5'], 'E':['E1', 'E2', 'E3', 'E4', 'E5'] } # Convert the dictionary into DataFrame df = pd.DataFrame(data) df Output: YouTubeGeeksforGeeks507K subscribersHow to Remove Columns From Pandas Dataframe? | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 9:07•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=8PN1eXQGZ9c" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div> Method #1: Drop Columns from a Dataframe using drop() method. Remove specific single column. # Import pandas package import pandas as pd # create a dictionary with five fields each data = { 'A':['A1', 'A2', 'A3', 'A4', 'A5'], 'B':['B1', 'B2', 'B3', 'B4', 'B5'], 'C':['C1', 'C2', 'C3', 'C4', 'C5'], 'D':['D1', 'D2', 'D3', 'D4', 'D5'], 'E':['E1', 'E2', 'E3', 'E4', 'E5'] } # Convert the dictionary into DataFrame df = pd.DataFrame(data) # Remove column name 'A'df.drop(['A'], axis = 1) Output: Remove specific multiple columns. # Import pandas package import pandas as pd # create a dictionary with five fields eachdata = { 'A':['A1', 'A2', 'A3', 'A4', 'A5'], 'B':['B1', 'B2', 'B3', 'B4', 'B5'], 'C':['C1', 'C2', 'C3', 'C4', 'C5'], 'D':['D1', 'D2', 'D3', 'D4', 'D5'], 'E':['E1', 'E2', 'E3', 'E4', 'E5'] } # Convert the dictionary into DataFrame df = pd.DataFrame(data) # Remove two columns name is 'C' and 'D'df.drop(['C', 'D'], axis = 1) # df.drop(columns =['C', 'D']) Output: Remove columns as based on column index. # Import pandas package import pandas as pd # create a dictionary with five fields eachdata = { 'A':['A1', 'A2', 'A3', 'A4', 'A5'], 'B':['B1', 'B2', 'B3', 'B4', 'B5'], 'C':['C1', 'C2', 'C3', 'C4', 'C5'], 'D':['D1', 'D2', 'D3', 'D4', 'D5'], 'E':['E1', 'E2', 'E3', 'E4', 'E5'] } # Convert the dictionary into DataFrame df = pd.DataFrame(data) # Remove three columns as index basedf.drop(df.columns[[0, 4, 2]], axis = 1, inplace = True) df Output: Method #2: Drop Columns from a Dataframe using iloc[] and drop() method. Remove all columns between a specific column to another columns. # Import pandas package import pandas as pd# create a dictionary with five fields each data = { 'A':['A1', 'A2', 'A3', 'A4', 'A5'], 'B':['B1', 'B2', 'B3', 'B4', 'B5'], 'C':['C1', 'C2', 'C3', 'C4', 'C5'], 'D':['D1', 'D2', 'D3', 'D4', 'D5'], 'E':['E1', 'E2', 'E3', 'E4', 'E5'] } # Convert the dictionary into DataFrame df = pd.DataFrame(data) # Remove all columns between column index 1 to 3df.drop(df.iloc[:, 1:3], inplace = True, axis = 1) df Output: Method #3: Drop Columns from a Dataframe using ix() and drop() method. Remove all columns between a specific column name to another columns name. # Import pandas package import pandas as pd # create a dictionary with five fields each data = { 'A':['A1', 'A2', 'A3', 'A4', 'A5'], 'B':['B1', 'B2', 'B3', 'B4', 'B5'], 'C':['C1', 'C2', 'C3', 'C4', 'C5'], 'D':['D1', 'D2', 'D3', 'D4', 'D5'], 'E':['E1', 'E2', 'E3', 'E4', 'E5'] } # Convert the dictionary into DataFrame df = pd.DataFrame(data) # Remove all columns between column name 'B' to 'D'df.drop(df.ix[:, 'B':'D'].columns, axis = 1) Output: Method #4: Drop Columns from a Dataframe using loc[] and drop() method. Remove all columns between a specific column name to another columns name. # Import pandas package import pandas as pd # create a dictionary with five fields each data = { 'A':['A1', 'A2', 'A3', 'A4', 'A5'], 'B':['B1', 'B2', 'B3', 'B4', 'B5'], 'C':['C1', 'C2', 'C3', 'C4', 'C5'], 'D':['D1', 'D2', 'D3', 'D4', 'D5'], 'E':['E1', 'E2', 'E3', 'E4', 'E5'] } # Convert the dictionary into DataFrame df = pd.DataFrame(data) # Remove all columns between column name 'B' to 'D'df.drop(df.loc[:, 'B':'D'].columns, axis = 1) Output:Note: Different loc() and iloc() is iloc() exclude last column range element. Method #5: Drop Columns from a Dataframe by iterative way. Remove all columns between a specific column name to another columns name. # Import pandas package import pandas as pd # create a dictionary with five fields each data = { 'A':['A1', 'A2', 'A3', 'A4', 'A5'], 'B':['B1', 'B2', 'B3', 'B4', 'B5'], 'C':['C1', 'C2', 'C3', 'C4', 'C5'], 'D':['D1', 'D2', 'D3', 'D4', 'D5'], 'E':['E1', 'E2', 'E3', 'E4', 'E5'] } # Convert the dictionary into DataFrame df = pd.DataFrame(data)for col in df.columns: if 'A' in col: del df[col] df Output: pandas-dataframe-program Picked Python pandas-dataFrame Python-pandas Technical Scripter 2018 Python Technical Scripter Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Read a file line by line in Python How to Install PIP on Windows ? Enumerate() in Python Different ways to create Pandas Dataframe Iterate over a list in Python Python String | replace() Reading and Writing to text files in Python *args and **kwargs in Python Create a Pandas DataFrame from Lists
[ { "code": null, "e": 26480, "s": 26452, "text": "\n21 May, 2021" }, { "code": null, "e": 26636, "s": 26480, "text": "Let’s discuss how to drop one or multiple columns in Pandas Dataframe. Drop one or more than one columns from a DataFrame can be achieved in multiple ways." }, { "code": null, "e": 26724, "s": 26636, "text": "Create a simple dataframe with dictionary of lists, say column names are A, B, C, D, E." }, { "code": "# Import pandas package import pandas as pd # create a dictionary with five fields eachdata = { 'A':['A1', 'A2', 'A3', 'A4', 'A5'], 'B':['B1', 'B2', 'B3', 'B4', 'B5'], 'C':['C1', 'C2', 'C3', 'C4', 'C5'], 'D':['D1', 'D2', 'D3', 'D4', 'D5'], 'E':['E1', 'E2', 'E3', 'E4', 'E5'] } # Convert the dictionary into DataFrame df = pd.DataFrame(data) df", "e": 27090, "s": 26724, "text": null }, { "code": null, "e": 27098, "s": 27090, "text": "Output:" }, { "code": null, "e": 27941, "s": 27098, "text": "YouTubeGeeksforGeeks507K subscribersHow to Remove Columns From Pandas Dataframe? | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 9:07•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=8PN1eXQGZ9c\" 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": 28003, "s": 27941, "text": "Method #1: Drop Columns from a Dataframe using drop() method." }, { "code": null, "e": 28034, "s": 28003, "text": "Remove specific single column." }, { "code": "# Import pandas package import pandas as pd # create a dictionary with five fields each data = { 'A':['A1', 'A2', 'A3', 'A4', 'A5'], 'B':['B1', 'B2', 'B3', 'B4', 'B5'], 'C':['C1', 'C2', 'C3', 'C4', 'C5'], 'D':['D1', 'D2', 'D3', 'D4', 'D5'], 'E':['E1', 'E2', 'E3', 'E4', 'E5'] } # Convert the dictionary into DataFrame df = pd.DataFrame(data) # Remove column name 'A'df.drop(['A'], axis = 1)", "e": 28447, "s": 28034, "text": null }, { "code": null, "e": 28455, "s": 28447, "text": "Output:" }, { "code": null, "e": 28490, "s": 28455, "text": " Remove specific multiple columns." }, { "code": "# Import pandas package import pandas as pd # create a dictionary with five fields eachdata = { 'A':['A1', 'A2', 'A3', 'A4', 'A5'], 'B':['B1', 'B2', 'B3', 'B4', 'B5'], 'C':['C1', 'C2', 'C3', 'C4', 'C5'], 'D':['D1', 'D2', 'D3', 'D4', 'D5'], 'E':['E1', 'E2', 'E3', 'E4', 'E5'] } # Convert the dictionary into DataFrame df = pd.DataFrame(data) # Remove two columns name is 'C' and 'D'df.drop(['C', 'D'], axis = 1) # df.drop(columns =['C', 'D'])", "e": 28955, "s": 28490, "text": null }, { "code": null, "e": 28964, "s": 28955, "text": "Output: " }, { "code": null, "e": 29005, "s": 28964, "text": "Remove columns as based on column index." }, { "code": "# Import pandas package import pandas as pd # create a dictionary with five fields eachdata = { 'A':['A1', 'A2', 'A3', 'A4', 'A5'], 'B':['B1', 'B2', 'B3', 'B4', 'B5'], 'C':['C1', 'C2', 'C3', 'C4', 'C5'], 'D':['D1', 'D2', 'D3', 'D4', 'D5'], 'E':['E1', 'E2', 'E3', 'E4', 'E5'] } # Convert the dictionary into DataFrame df = pd.DataFrame(data) # Remove three columns as index basedf.drop(df.columns[[0, 4, 2]], axis = 1, inplace = True) df", "e": 29465, "s": 29005, "text": null }, { "code": null, "e": 29473, "s": 29465, "text": "Output:" }, { "code": null, "e": 29548, "s": 29475, "text": "Method #2: Drop Columns from a Dataframe using iloc[] and drop() method." }, { "code": null, "e": 29613, "s": 29548, "text": "Remove all columns between a specific column to another columns." }, { "code": "# Import pandas package import pandas as pd# create a dictionary with five fields each data = { 'A':['A1', 'A2', 'A3', 'A4', 'A5'], 'B':['B1', 'B2', 'B3', 'B4', 'B5'], 'C':['C1', 'C2', 'C3', 'C4', 'C5'], 'D':['D1', 'D2', 'D3', 'D4', 'D5'], 'E':['E1', 'E2', 'E3', 'E4', 'E5'] } # Convert the dictionary into DataFrame df = pd.DataFrame(data) # Remove all columns between column index 1 to 3df.drop(df.iloc[:, 1:3], inplace = True, axis = 1) df", "e": 30078, "s": 29613, "text": null }, { "code": null, "e": 30087, "s": 30078, "text": "Output: " }, { "code": null, "e": 30158, "s": 30087, "text": "Method #3: Drop Columns from a Dataframe using ix() and drop() method." }, { "code": null, "e": 30233, "s": 30158, "text": "Remove all columns between a specific column name to another columns name." }, { "code": "# Import pandas package import pandas as pd # create a dictionary with five fields each data = { 'A':['A1', 'A2', 'A3', 'A4', 'A5'], 'B':['B1', 'B2', 'B3', 'B4', 'B5'], 'C':['C1', 'C2', 'C3', 'C4', 'C5'], 'D':['D1', 'D2', 'D3', 'D4', 'D5'], 'E':['E1', 'E2', 'E3', 'E4', 'E5'] } # Convert the dictionary into DataFrame df = pd.DataFrame(data) # Remove all columns between column name 'B' to 'D'df.drop(df.ix[:, 'B':'D'].columns, axis = 1)", "e": 30693, "s": 30233, "text": null }, { "code": null, "e": 30701, "s": 30693, "text": "Output:" }, { "code": null, "e": 30774, "s": 30701, "text": " Method #4: Drop Columns from a Dataframe using loc[] and drop() method." }, { "code": null, "e": 30849, "s": 30774, "text": "Remove all columns between a specific column name to another columns name." }, { "code": "# Import pandas package import pandas as pd # create a dictionary with five fields each data = { 'A':['A1', 'A2', 'A3', 'A4', 'A5'], 'B':['B1', 'B2', 'B3', 'B4', 'B5'], 'C':['C1', 'C2', 'C3', 'C4', 'C5'], 'D':['D1', 'D2', 'D3', 'D4', 'D5'], 'E':['E1', 'E2', 'E3', 'E4', 'E5'] } # Convert the dictionary into DataFrame df = pd.DataFrame(data) # Remove all columns between column name 'B' to 'D'df.drop(df.loc[:, 'B':'D'].columns, axis = 1)", "e": 31310, "s": 30849, "text": null }, { "code": null, "e": 31395, "s": 31310, "text": "Output:Note: Different loc() and iloc() is iloc() exclude last column range element." }, { "code": null, "e": 31455, "s": 31395, "text": " Method #5: Drop Columns from a Dataframe by iterative way." }, { "code": null, "e": 31530, "s": 31455, "text": "Remove all columns between a specific column name to another columns name." }, { "code": "# Import pandas package import pandas as pd # create a dictionary with five fields each data = { 'A':['A1', 'A2', 'A3', 'A4', 'A5'], 'B':['B1', 'B2', 'B3', 'B4', 'B5'], 'C':['C1', 'C2', 'C3', 'C4', 'C5'], 'D':['D1', 'D2', 'D3', 'D4', 'D5'], 'E':['E1', 'E2', 'E3', 'E4', 'E5'] } # Convert the dictionary into DataFrame df = pd.DataFrame(data)for col in df.columns: if 'A' in col: del df[col] df", "e": 31956, "s": 31530, "text": null }, { "code": null, "e": 31964, "s": 31956, "text": "Output:" }, { "code": null, "e": 31989, "s": 31964, "text": "pandas-dataframe-program" }, { "code": null, "e": 31996, "s": 31989, "text": "Picked" }, { "code": null, "e": 32020, "s": 31996, "text": "Python pandas-dataFrame" }, { "code": null, "e": 32034, "s": 32020, "text": "Python-pandas" }, { "code": null, "e": 32058, "s": 32034, "text": "Technical Scripter 2018" }, { "code": null, "e": 32065, "s": 32058, "text": "Python" }, { "code": null, "e": 32084, "s": 32065, "text": "Technical Scripter" }, { "code": null, "e": 32182, "s": 32084, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 32200, "s": 32182, "text": "Python Dictionary" }, { "code": null, "e": 32235, "s": 32200, "text": "Read a file line by line in Python" }, { "code": null, "e": 32267, "s": 32235, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 32289, "s": 32267, "text": "Enumerate() in Python" }, { "code": null, "e": 32331, "s": 32289, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 32361, "s": 32331, "text": "Iterate over a list in Python" }, { "code": null, "e": 32387, "s": 32361, "text": "Python String | replace()" }, { "code": null, "e": 32431, "s": 32387, "text": "Reading and Writing to text files in Python" }, { "code": null, "e": 32460, "s": 32431, "text": "*args and **kwargs in Python" } ]
ReactJS Toast Notification - GeeksforGeeks
26 Oct, 2021 Toast Notifications are popup messages that are added so as to display a message to a user. It can be a success message, warning message, or custom message. Toast Notification is also called Toastify Notifications. This all toast notification comes under-react-toastify module so to use them we need to import this module.Prerequisites: Basics of ReactJS NodeJS: Installation of Node.js on WindowsInstallation of Node.js on Linux Installation of Node.js on Windows Installation of Node.js on Linux Already created ReactJS app Below all the steps are described order-wise to add toast-notification and their configuration. Step 1: Before moving further, firstly we have to install the react-toastify module, by running the following command in your project directory, with the help of the terminal in your src folder or you can also run this command in Visual Studio Code’s terminal in your project folder. npm add react-toastify Step 2: After installing the react-toastify module, now open your app.js file which is present inside your project directory, under the src folder, and delete code preset inside it. Step 3: Now import react-toastify module, toastify CSS file, and a caller method of toast notification. Step 4: In your app.js file, add this code to import the toastify-modules by adding the below code in your app.js import {toast} from 'react-toastify'; import 'react-toastify/dist/ReactToastify.css'; toast.configure() Example 1: By default position of notification is top right. app.js: javascript import React from 'react'; // Importing toastify moduleimport {toast} from 'react-toastify'; // Import toastify css fileimport 'react-toastify/dist/ReactToastify.css'; // toast-configuration method, // it is compulsory method.toast.configure() // This is main functionfunction GeeksforGeeks(){ // function which is called when // button is clicked const notify = ()=>{ // Calling toast method by passing string toast('Hello Geeks') } return ( <div className="GeeksforGeeks"> <button onClick={notify}>Click Me!</button> </div> );} export default GeeksforGeeks; Output: Example 2: There is a total six-position where we can show our notification. These are bottom left, bottom center, bottom right, top left, top right, and top center. To change the position we need to pass, one more argument in the toasting method along with string. See below how to configure the position of notifications. app.js: javascript import React from 'react';import {toast} from 'react-toastify';import 'react-toastify/dist/ReactToastify.css'; toast.configure()function GeeksforGeeks(){ const notify = ()=>{ toast('Hello Geeks 4', {position: toast.POSITION.BOTTOM_LEFT}) toast('Hello Geeks 6', {position: toast.POSITION.BOTTOM_RIGHT}) toast('Hello Geeks 5', {position: toast.POSITION.BOTTOM_CENTER}) toast('Hello Geeks 1', {position: toast.POSITION.TOP_LEFT}) toast('Hello Geeks 3', {position: toast.POSITION.TOP_RIGHT}) toast('Hello Geeks 2', {position: toast.POSITION.TOP_CENTER}) } return ( <div className="GeeksforGeeks"> <button onClick={notify}>Click Me!</button> </div> );} export default GeeksforGeeks; Output: Example 3: Upto now we have used default notification but there are four more built-in type notifications. These are a success, warning, info, and error. See below how to use them. app.js: javascript import React from 'react';import {toast} from 'react-toastify';import 'react-toastify/dist/ReactToastify.css'; toast.configure()function GeeksforGeeks(){ const notify = ()=>{ // inbuilt-notification toast.warning('Danger') // inbuilt-notification toast.success('successful') // inbuilt-notification toast.info('GeeksForGeeks') // inbuilt-notification toast.error('Runtime error') // default notification toast('Hello Geeks') } return ( <div className="GeeksforGeeks"> <button onClick={notify}>Click Me!</button> </div> );} export default GeeksforGeeks; Output: Example 4: By default, notifications are shown for 5second only. To configure time, we use autoClose method, and if we set the autoclose method to false, then the user has to close that notification otherwise it will remain there only. See below how to use it. app.js: javascript import React from 'react';import {toast} from 'react-toastify';import 'react-toastify/dist/ReactToastify.css'; toast.configure()function GeeksforGeeks(){ const notify = ()=>{ // Set to 10sec toast.warning('Danger', {autoClose:10000}) // Set to 3sec toast.success('successful', {autoClose:3000}) // User have to close it toast.info('GeeksForGeeks', {autoClose:false}) toast.error('Runtime error', { // Set to 15sec position: toast.POSITION.BOTTOM_LEFT, autoClose:15000}) toast('Hello Geeks')// Default } return ( <div className="GeeksforGeeks"> <button onClick={notify}>Click Me!</button> </div> );} export default GeeksforGeeks; Output: punamsingh628700 react-js JavaScript Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Remove elements from a JavaScript Array Convert a string to an integer in JavaScript Difference between var, let and const keywords in JavaScript How to calculate the number of days between two dates in javascript? File uploading in React.js Remove elements from a JavaScript Array Installation of Node.js on Linux Convert a string to an integer in JavaScript How to fetch data from an API in ReactJS ? How to insert spaces/tabs in text using HTML/CSS?
[ { "code": null, "e": 28521, "s": 28493, "text": "\n26 Oct, 2021" }, { "code": null, "e": 28859, "s": 28521, "text": "Toast Notifications are popup messages that are added so as to display a message to a user. It can be a success message, warning message, or custom message. Toast Notification is also called Toastify Notifications. This all toast notification comes under-react-toastify module so to use them we need to import this module.Prerequisites: " }, { "code": null, "e": 28877, "s": 28859, "text": "Basics of ReactJS" }, { "code": null, "e": 28952, "s": 28877, "text": "NodeJS: Installation of Node.js on WindowsInstallation of Node.js on Linux" }, { "code": null, "e": 28987, "s": 28952, "text": "Installation of Node.js on Windows" }, { "code": null, "e": 29020, "s": 28987, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 29048, "s": 29020, "text": "Already created ReactJS app" }, { "code": null, "e": 29146, "s": 29048, "text": "Below all the steps are described order-wise to add toast-notification and their configuration. " }, { "code": null, "e": 29431, "s": 29146, "text": "Step 1: Before moving further, firstly we have to install the react-toastify module, by running the following command in your project directory, with the help of the terminal in your src folder or you can also run this command in Visual Studio Code’s terminal in your project folder. " }, { "code": null, "e": 29454, "s": 29431, "text": "npm add react-toastify" }, { "code": null, "e": 29636, "s": 29454, "text": "Step 2: After installing the react-toastify module, now open your app.js file which is present inside your project directory, under the src folder, and delete code preset inside it." }, { "code": null, "e": 29740, "s": 29636, "text": "Step 3: Now import react-toastify module, toastify CSS file, and a caller method of toast notification." }, { "code": null, "e": 29856, "s": 29740, "text": "Step 4: In your app.js file, add this code to import the toastify-modules by adding the below code in your app.js " }, { "code": null, "e": 29960, "s": 29856, "text": "import {toast} from 'react-toastify';\nimport 'react-toastify/dist/ReactToastify.css';\ntoast.configure()" }, { "code": null, "e": 30023, "s": 29960, "text": "Example 1: By default position of notification is top right. " }, { "code": null, "e": 30033, "s": 30023, "text": "app.js: " }, { "code": null, "e": 30044, "s": 30033, "text": "javascript" }, { "code": "import React from 'react'; // Importing toastify moduleimport {toast} from 'react-toastify'; // Import toastify css fileimport 'react-toastify/dist/ReactToastify.css'; // toast-configuration method, // it is compulsory method.toast.configure() // This is main functionfunction GeeksforGeeks(){ // function which is called when // button is clicked const notify = ()=>{ // Calling toast method by passing string toast('Hello Geeks') } return ( <div className=\"GeeksforGeeks\"> <button onClick={notify}>Click Me!</button> </div> );} export default GeeksforGeeks;", "e": 30668, "s": 30044, "text": null }, { "code": null, "e": 30678, "s": 30668, "text": "Output: " }, { "code": null, "e": 31003, "s": 30678, "text": "Example 2: There is a total six-position where we can show our notification. These are bottom left, bottom center, bottom right, top left, top right, and top center. To change the position we need to pass, one more argument in the toasting method along with string. See below how to configure the position of notifications. " }, { "code": null, "e": 31013, "s": 31003, "text": "app.js: " }, { "code": null, "e": 31024, "s": 31013, "text": "javascript" }, { "code": "import React from 'react';import {toast} from 'react-toastify';import 'react-toastify/dist/ReactToastify.css'; toast.configure()function GeeksforGeeks(){ const notify = ()=>{ toast('Hello Geeks 4', {position: toast.POSITION.BOTTOM_LEFT}) toast('Hello Geeks 6', {position: toast.POSITION.BOTTOM_RIGHT}) toast('Hello Geeks 5', {position: toast.POSITION.BOTTOM_CENTER}) toast('Hello Geeks 1', {position: toast.POSITION.TOP_LEFT}) toast('Hello Geeks 3', {position: toast.POSITION.TOP_RIGHT}) toast('Hello Geeks 2', {position: toast.POSITION.TOP_CENTER}) } return ( <div className=\"GeeksforGeeks\"> <button onClick={notify}>Click Me!</button> </div> );} export default GeeksforGeeks;", "e": 31846, "s": 31024, "text": null }, { "code": null, "e": 31858, "s": 31848, "text": "Output: " }, { "code": null, "e": 32040, "s": 31858, "text": "Example 3: Upto now we have used default notification but there are four more built-in type notifications. These are a success, warning, info, and error. See below how to use them. " }, { "code": null, "e": 32050, "s": 32040, "text": "app.js: " }, { "code": null, "e": 32061, "s": 32050, "text": "javascript" }, { "code": "import React from 'react';import {toast} from 'react-toastify';import 'react-toastify/dist/ReactToastify.css'; toast.configure()function GeeksforGeeks(){ const notify = ()=>{ // inbuilt-notification toast.warning('Danger') // inbuilt-notification toast.success('successful') // inbuilt-notification toast.info('GeeksForGeeks') // inbuilt-notification toast.error('Runtime error') // default notification toast('Hello Geeks') } return ( <div className=\"GeeksforGeeks\"> <button onClick={notify}>Click Me!</button> </div> );} export default GeeksforGeeks;", "e": 32737, "s": 32061, "text": null }, { "code": null, "e": 32749, "s": 32739, "text": "Output: " }, { "code": null, "e": 33011, "s": 32749, "text": "Example 4: By default, notifications are shown for 5second only. To configure time, we use autoClose method, and if we set the autoclose method to false, then the user has to close that notification otherwise it will remain there only. See below how to use it. " }, { "code": null, "e": 33021, "s": 33011, "text": "app.js: " }, { "code": null, "e": 33032, "s": 33021, "text": "javascript" }, { "code": "import React from 'react';import {toast} from 'react-toastify';import 'react-toastify/dist/ReactToastify.css'; toast.configure()function GeeksforGeeks(){ const notify = ()=>{ // Set to 10sec toast.warning('Danger', {autoClose:10000}) // Set to 3sec toast.success('successful', {autoClose:3000}) // User have to close it toast.info('GeeksForGeeks', {autoClose:false}) toast.error('Runtime error', { // Set to 15sec position: toast.POSITION.BOTTOM_LEFT, autoClose:15000}) toast('Hello Geeks')// Default } return ( <div className=\"GeeksforGeeks\"> <button onClick={notify}>Click Me!</button> </div> );} export default GeeksforGeeks;", "e": 33786, "s": 33032, "text": null }, { "code": null, "e": 33798, "s": 33788, "text": "Output: " }, { "code": null, "e": 33817, "s": 33800, "text": "punamsingh628700" }, { "code": null, "e": 33826, "s": 33817, "text": "react-js" }, { "code": null, "e": 33837, "s": 33826, "text": "JavaScript" }, { "code": null, "e": 33854, "s": 33837, "text": "Web Technologies" }, { "code": null, "e": 33952, "s": 33854, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 33992, "s": 33952, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 34037, "s": 33992, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 34098, "s": 34037, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 34167, "s": 34098, "text": "How to calculate the number of days between two dates in javascript?" }, { "code": null, "e": 34194, "s": 34167, "text": "File uploading in React.js" }, { "code": null, "e": 34234, "s": 34194, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 34267, "s": 34234, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 34312, "s": 34267, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 34355, "s": 34312, "text": "How to fetch data from an API in ReactJS ?" } ]
Animation in Android with Example - GeeksforGeeks
06 Sep, 2021 Animation is the process of adding a motion effect to any view, image, or text. With the help of an animation, you can add motion or can change the shape of a specific view. Animation in Android is generally used to give your UI a rich look and feel. The animations are basically of three types as follows: Property AnimationView AnimationDrawable Animation Property Animation View Animation Drawable Animation Property Animation is one of the robust frameworks which allows animating almost everything. This is one of the powerful and flexible animations which was introduced in Android 3.0. Property animation can be used to add any animation in the CheckBox, RadioButtons, and widgets other than any view. View Animation can be used to add animation to a specific view to perform tweened animation on views. Tweened animation calculates animation information such as size, rotation, start point, and endpoint. These animations are slower and less flexible. An example of View animation can be used if we want to expand a specific layout in that place we can use View Animation. The example of View Animation can be seen in Expandable RecyclerView. Drawable Animation is used if you want to animate one image over another. The simple way to understand is to animate drawable is to load the series of drawable one after another to create an animation. A simple example of drawable animation can be seen in many apps Splash screen on apps logo animation. Methods Description Now we will see the Simple Example to add animations to ImageView. Note that we are going to implement this project using the Java language. Step 1: Create a New Project To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Java as the programming language. Step 2: Working with the strings.xml file Strings.xml can be found from the app > res > values > strings.xml. Below is the snippet for the strings.xml file. XML <resources> <string name="app_name">GFG App</string> <string name="blink">BLINK</string> <string name="clockwise">ROTATE</string> <string name="fade">FADE</string> <string name="move">MOVE</string> <string name="slide">SLIDE</string> <string name="zoom">ZOOM</string> <string name="stop_animation">STOP ANIMATION</string> <string name="course_rating">Course Rating</string> <string name="course_name">Course Name</string></resources> Step 3: Add google repository in the build.gradle file of the application project if by default it is not there buildscript { repositories { google() mavenCentral() } All Jetpack components are available in the Google Maven repository, include them in the build.gradle file allprojects { repositories { google() mavenCentral() } } Step 4: Working with the activity_main.xml file Create ImageView in the activity_main.xml along with buttons that will add animation to the view. Navigate to the app > res > layout > activity_main.xml. Below is the code for the activity_main.xml file. XML <?xml version="1.0" encoding="utf-8"?><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity"> <ImageView android:id="@+id/imageview" android:layout_width="200dp" android:layout_height="200dp" android:layout_centerHorizontal="true" android:layout_marginTop="40dp" android:contentDescription="@string/app_name" android:src="@drawable/gfgimage" /> <LinearLayout android:id="@+id/linear1" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_below="@id/imageview" android:layout_marginTop="30dp" android:orientation="horizontal" android:weightSum="3"> <!--To start the blink animation of the image--> <Button android:id="@+id/BTNblink" style="@style/TextAppearance.AppCompat.Widget.Button" android:layout_width="0dp" android:layout_height="wrap_content" android:layout_margin="10dp" android:layout_weight="1" android:padding="3dp" android:text="@string/blink" android:textColor="@color/white" /> <!--To start the rotate animation of the image--> <Button android:id="@+id/BTNrotate" style="@style/TextAppearance.AppCompat.Widget.Button" android:layout_width="0dp" android:layout_height="wrap_content" android:layout_margin="10dp" android:layout_weight="1" android:padding="3dp" android:text="@string/clockwise" android:textColor="@color/white" /> <!--To start the fading animation of the image--> <Button android:id="@+id/BTNfade" style="@style/TextAppearance.AppCompat.Widget.Button" android:layout_width="0dp" android:layout_height="wrap_content" android:layout_margin="10dp" android:layout_weight="1" android:padding="3dp" android:text="@string/fade" android:textColor="@color/white" /> </LinearLayout> <LinearLayout android:id="@+id/linear2" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_below="@id/linear1" android:layout_marginTop="30dp" android:orientation="horizontal" android:weightSum="3"> <!--To start the move animation of the image--> <Button android:id="@+id/BTNmove" style="@style/TextAppearance.AppCompat.Widget.Button" android:layout_width="0dp" android:layout_height="wrap_content" android:layout_margin="10dp" android:layout_weight="1" android:padding="3dp" android:text="@string/move" android:textColor="@color/white" /> <!--To start the slide animation of the image--> <Button android:id="@+id/BTNslide" style="@style/TextAppearance.AppCompat.Widget.Button" android:layout_width="0dp" android:layout_height="wrap_content" android:layout_margin="10dp" android:layout_weight="1" android:padding="3dp" android:text="@string/slide" android:textColor="@color/white" /> <!--To start the zoom animation of the image--> <Button android:id="@+id/BTNzoom" style="@style/TextAppearance.AppCompat.Widget.Button" android:layout_width="0dp" android:layout_height="wrap_content" android:layout_margin="10dp" android:layout_weight="1" android:padding="3dp" android:text="@string/zoom" android:textColor="@color/white" /> </LinearLayout> <!--To stop the animation of the image--> <Button android:id="@+id/BTNstop" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_below="@id/linear2" android:layout_marginLeft="30dp" android:layout_marginTop="30dp" android:layout_marginRight="30dp" android:text="@string/stop_animation" /> </RelativeLayout> Step 5: Create 6 different types of animation for ImageView To create new animations we have to create a new directory for storing all our animations. Navigate to the app > res > Right-Click on res >> New >> Directory >> Name your directory as “anim”. Inside this directory, we will create our animations. For creating a new anim right click on the anim directory >> Animation Resource file and give the name to your file. Below is the code snippet for 6 different animations. 1) Blink Animation XML <?xml version="1.0" encoding="utf-8"?><set xmlns:android="http://schemas.android.com/apk/res/android"> <alpha android:fromAlpha="0.0" android:toAlpha="1.0" android:interpolator="@android:anim/accelerate_interpolator" android:duration="500" android:repeatMode="reverse" android:repeatCount="infinite"/></set> 2) Fade Animation XML <?xml version="1.0" encoding="utf-8"?><set xmlns:android="http://schemas.android.com/apk/res/android" android:interpolator="@android:anim/accelerate_interpolator"> <!-- duration is the time for which animation will work--> <alpha android:duration="1000" android:fromAlpha="0" android:toAlpha="1" /> <alpha android:duration="1000" android:fromAlpha="1" android:startOffset="2000" android:toAlpha="0" /> </set> 3) Move Animation XML <?xml version="1.0" encoding="utf-8"?><set xmlns:android="http://schemas.android.com/apk/res/android" android:interpolator="@android:anim/linear_interpolator" android:fillAfter="true"> <translate android:fromXDelta="0%p" android:toXDelta="75%p" android:duration="700" /></set> 4) Rotate Animation XML <?xml version="1.0" encoding="utf-8"?><set xmlns:android="http://schemas.android.com/apk/res/android"> <rotate android:duration="6000" android:fromDegrees="0" android:pivotX="50%" android:pivotY="50%" android:toDegrees="360" /> <rotate android:duration="6000" android:fromDegrees="360" android:pivotX="50%" android:pivotY="50%" android:startOffset="5000" android:toDegrees="0" /> </set> 5) Slide Animation XML <?xml version="1.0" encoding="utf-8"?><set xmlns:android="http://schemas.android.com/apk/res/android" android:fillAfter="true" > <scale android:duration="500" android:fromXScale="1.0" android:fromYScale="1.0" android:interpolator="@android:anim/linear_interpolator" android:toXScale="1.0" android:toYScale="0.0" /></set> 6) Zoom Animation XML <?xml version="1.0" encoding="utf-8"?><set xmlns:android="http://schemas.android.com/apk/res/android" android:fillAfter="true" > <scale android:duration="500" android:fromXScale="1.0" android:fromYScale="1.0" android:interpolator="@android:anim/linear_interpolator" android:toXScale="1.0" android:toYScale="0.0" /></set> Step 6: Working with the MainActivity.java file Add animation to the ImageView by clicking a specific Button. Navigate to the app > java > your apps package name >> MainActivity.java. Java import androidx.appcompat.app.AppCompatActivity;import android.os.Bundle;import android.view.View;import android.view.animation.Animation;import android.view.animation.AnimationUtils;import android.widget.Button;import android.widget.ImageView; public class MainActivity extends AppCompatActivity { ImageView imageView; Button blinkBTN, rotateBTN, fadeBTN, moveBTN, slideBTN, zoomBTN, stopBTN; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); imageView = findViewById(R.id.imageview); blinkBTN = findViewById(R.id.BTNblink); rotateBTN = findViewById(R.id.BTNrotate); fadeBTN = findViewById(R.id.BTNfade); moveBTN = findViewById(R.id.BTNmove); slideBTN = findViewById(R.id.BTNslide); zoomBTN = findViewById(R.id.BTNzoom); stopBTN = findViewById(R.id.BTNstop); blinkBTN.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // To add blink animation Animation animation = AnimationUtils.loadAnimation(getApplicationContext(), R.anim.blink_animation); imageView.startAnimation(animation); } }); rotateBTN.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // To add rotate animation Animation animation = AnimationUtils.loadAnimation(getApplicationContext(), R.anim.rotate_animation); imageView.startAnimation(animation); } }); fadeBTN.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // To add fade animation Animation animation = AnimationUtils.loadAnimation(getApplicationContext(), R.anim.fade_animation); imageView.startAnimation(animation); } }); moveBTN.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // To add move animation Animation animation = AnimationUtils.loadAnimation(getApplicationContext(), R.anim.move_animation); imageView.startAnimation(animation); } }); slideBTN.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // To add slide animation Animation animation = AnimationUtils.loadAnimation(getApplicationContext(), R.anim.slide_animation); imageView.startAnimation(animation); } }); zoomBTN.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // To add zoom animation Animation animation = AnimationUtils.loadAnimation(getApplicationContext(), R.anim.zoom_animation); imageView.startAnimation(animation); } }); stopBTN.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // To stop the animation going on imageview imageView.clearAnimation(); } }); }} Note: Drawables and strings can be found in the drawable folder and strings.xml file. Drawables can be found from the app > res > drawable. Output: hemantjain99 Android-Animation Picked Technical Scripter 2020 Android Java Technical Scripter Java Android Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments How to Create and Add Data to SQLite Database in Android? Services in Android with Example Broadcast Receiver in Android With Example Content Providers in Android with Example Android RecyclerView in Kotlin For-each loop in Java Arrays.sort() in Java with examples Initialize an ArrayList in Java Reverse a string in Java HashMap in Java with Examples
[ { "code": null, "e": 24974, "s": 24946, "text": "\n06 Sep, 2021" }, { "code": null, "e": 25282, "s": 24974, "text": "Animation is the process of adding a motion effect to any view, image, or text. With the help of an animation, you can add motion or can change the shape of a specific view. Animation in Android is generally used to give your UI a rich look and feel. The animations are basically of three types as follows: " }, { "code": null, "e": 25333, "s": 25282, "text": "Property AnimationView AnimationDrawable Animation" }, { "code": null, "e": 25352, "s": 25333, "text": "Property Animation" }, { "code": null, "e": 25367, "s": 25352, "text": "View Animation" }, { "code": null, "e": 25386, "s": 25367, "text": "Drawable Animation" }, { "code": null, "e": 25684, "s": 25386, "text": "Property Animation is one of the robust frameworks which allows animating almost everything. This is one of the powerful and flexible animations which was introduced in Android 3.0. Property animation can be used to add any animation in the CheckBox, RadioButtons, and widgets other than any view." }, { "code": null, "e": 26126, "s": 25684, "text": "View Animation can be used to add animation to a specific view to perform tweened animation on views. Tweened animation calculates animation information such as size, rotation, start point, and endpoint. These animations are slower and less flexible. An example of View animation can be used if we want to expand a specific layout in that place we can use View Animation. The example of View Animation can be seen in Expandable RecyclerView." }, { "code": null, "e": 26430, "s": 26126, "text": "Drawable Animation is used if you want to animate one image over another. The simple way to understand is to animate drawable is to load the series of drawable one after another to create an animation. A simple example of drawable animation can be seen in many apps Splash screen on apps logo animation." }, { "code": null, "e": 26438, "s": 26430, "text": "Methods" }, { "code": null, "e": 26450, "s": 26438, "text": "Description" }, { "code": null, "e": 26593, "s": 26450, "text": "Now we will see the Simple Example to add animations to ImageView. Note that we are going to implement this project using the Java language. " }, { "code": null, "e": 26622, "s": 26593, "text": "Step 1: Create a New Project" }, { "code": null, "e": 26784, "s": 26622, "text": "To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Java as the programming language." }, { "code": null, "e": 26826, "s": 26784, "text": "Step 2: Working with the strings.xml file" }, { "code": null, "e": 26941, "s": 26826, "text": "Strings.xml can be found from the app > res > values > strings.xml. Below is the snippet for the strings.xml file." }, { "code": null, "e": 26945, "s": 26941, "text": "XML" }, { "code": "<resources> <string name=\"app_name\">GFG App</string> <string name=\"blink\">BLINK</string> <string name=\"clockwise\">ROTATE</string> <string name=\"fade\">FADE</string> <string name=\"move\">MOVE</string> <string name=\"slide\">SLIDE</string> <string name=\"zoom\">ZOOM</string> <string name=\"stop_animation\">STOP ANIMATION</string> <string name=\"course_rating\">Course Rating</string> <string name=\"course_name\">Course Name</string></resources>", "e": 27409, "s": 26945, "text": null }, { "code": null, "e": 27521, "s": 27409, "text": "Step 3: Add google repository in the build.gradle file of the application project if by default it is not there" }, { "code": null, "e": 27535, "s": 27521, "text": "buildscript {" }, { "code": null, "e": 27551, "s": 27535, "text": " repositories {" }, { "code": null, "e": 27564, "s": 27551, "text": " google()" }, { "code": null, "e": 27583, "s": 27564, "text": " mavenCentral()" }, { "code": null, "e": 27585, "s": 27583, "text": "}" }, { "code": null, "e": 27692, "s": 27585, "text": "All Jetpack components are available in the Google Maven repository, include them in the build.gradle file" }, { "code": null, "e": 27706, "s": 27692, "text": "allprojects {" }, { "code": null, "e": 27722, "s": 27706, "text": " repositories {" }, { "code": null, "e": 27735, "s": 27722, "text": " google()" }, { "code": null, "e": 27753, "s": 27735, "text": " mavenCentral()" }, { "code": null, "e": 27756, "s": 27753, "text": " }" }, { "code": null, "e": 27758, "s": 27756, "text": "}" }, { "code": null, "e": 27806, "s": 27758, "text": "Step 4: Working with the activity_main.xml file" }, { "code": null, "e": 28011, "s": 27806, "text": "Create ImageView in the activity_main.xml along with buttons that will add animation to the view. Navigate to the app > res > layout > activity_main.xml. Below is the code for the activity_main.xml file. " }, { "code": null, "e": 28015, "s": 28011, "text": "XML" }, { "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\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" tools:context=\".MainActivity\"> <ImageView android:id=\"@+id/imageview\" android:layout_width=\"200dp\" android:layout_height=\"200dp\" android:layout_centerHorizontal=\"true\" android:layout_marginTop=\"40dp\" android:contentDescription=\"@string/app_name\" android:src=\"@drawable/gfgimage\" /> <LinearLayout android:id=\"@+id/linear1\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_below=\"@id/imageview\" android:layout_marginTop=\"30dp\" android:orientation=\"horizontal\" android:weightSum=\"3\"> <!--To start the blink animation of the image--> <Button android:id=\"@+id/BTNblink\" style=\"@style/TextAppearance.AppCompat.Widget.Button\" android:layout_width=\"0dp\" android:layout_height=\"wrap_content\" android:layout_margin=\"10dp\" android:layout_weight=\"1\" android:padding=\"3dp\" android:text=\"@string/blink\" android:textColor=\"@color/white\" /> <!--To start the rotate animation of the image--> <Button android:id=\"@+id/BTNrotate\" style=\"@style/TextAppearance.AppCompat.Widget.Button\" android:layout_width=\"0dp\" android:layout_height=\"wrap_content\" android:layout_margin=\"10dp\" android:layout_weight=\"1\" android:padding=\"3dp\" android:text=\"@string/clockwise\" android:textColor=\"@color/white\" /> <!--To start the fading animation of the image--> <Button android:id=\"@+id/BTNfade\" style=\"@style/TextAppearance.AppCompat.Widget.Button\" android:layout_width=\"0dp\" android:layout_height=\"wrap_content\" android:layout_margin=\"10dp\" android:layout_weight=\"1\" android:padding=\"3dp\" android:text=\"@string/fade\" android:textColor=\"@color/white\" /> </LinearLayout> <LinearLayout android:id=\"@+id/linear2\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_below=\"@id/linear1\" android:layout_marginTop=\"30dp\" android:orientation=\"horizontal\" android:weightSum=\"3\"> <!--To start the move animation of the image--> <Button android:id=\"@+id/BTNmove\" style=\"@style/TextAppearance.AppCompat.Widget.Button\" android:layout_width=\"0dp\" android:layout_height=\"wrap_content\" android:layout_margin=\"10dp\" android:layout_weight=\"1\" android:padding=\"3dp\" android:text=\"@string/move\" android:textColor=\"@color/white\" /> <!--To start the slide animation of the image--> <Button android:id=\"@+id/BTNslide\" style=\"@style/TextAppearance.AppCompat.Widget.Button\" android:layout_width=\"0dp\" android:layout_height=\"wrap_content\" android:layout_margin=\"10dp\" android:layout_weight=\"1\" android:padding=\"3dp\" android:text=\"@string/slide\" android:textColor=\"@color/white\" /> <!--To start the zoom animation of the image--> <Button android:id=\"@+id/BTNzoom\" style=\"@style/TextAppearance.AppCompat.Widget.Button\" android:layout_width=\"0dp\" android:layout_height=\"wrap_content\" android:layout_margin=\"10dp\" android:layout_weight=\"1\" android:padding=\"3dp\" android:text=\"@string/zoom\" android:textColor=\"@color/white\" /> </LinearLayout> <!--To stop the animation of the image--> <Button android:id=\"@+id/BTNstop\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_below=\"@id/linear2\" android:layout_marginLeft=\"30dp\" android:layout_marginTop=\"30dp\" android:layout_marginRight=\"30dp\" android:text=\"@string/stop_animation\" /> </RelativeLayout>", "e": 32383, "s": 28015, "text": null }, { "code": null, "e": 32443, "s": 32383, "text": "Step 5: Create 6 different types of animation for ImageView" }, { "code": null, "e": 32861, "s": 32443, "text": "To create new animations we have to create a new directory for storing all our animations. Navigate to the app > res > Right-Click on res >> New >> Directory >> Name your directory as “anim”. Inside this directory, we will create our animations. For creating a new anim right click on the anim directory >> Animation Resource file and give the name to your file. Below is the code snippet for 6 different animations. " }, { "code": null, "e": 32880, "s": 32861, "text": "1) Blink Animation" }, { "code": null, "e": 32884, "s": 32880, "text": "XML" }, { "code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><set xmlns:android=\"http://schemas.android.com/apk/res/android\"> <alpha android:fromAlpha=\"0.0\" android:toAlpha=\"1.0\" android:interpolator=\"@android:anim/accelerate_interpolator\" android:duration=\"500\" android:repeatMode=\"reverse\" android:repeatCount=\"infinite\"/></set>", "e": 33230, "s": 32884, "text": null }, { "code": null, "e": 33248, "s": 33230, "text": "2) Fade Animation" }, { "code": null, "e": 33252, "s": 33248, "text": "XML" }, { "code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><set xmlns:android=\"http://schemas.android.com/apk/res/android\" android:interpolator=\"@android:anim/accelerate_interpolator\"> <!-- duration is the time for which animation will work--> <alpha android:duration=\"1000\" android:fromAlpha=\"0\" android:toAlpha=\"1\" /> <alpha android:duration=\"1000\" android:fromAlpha=\"1\" android:startOffset=\"2000\" android:toAlpha=\"0\" /> </set>", "e": 33728, "s": 33252, "text": null }, { "code": null, "e": 33746, "s": 33728, "text": "3) Move Animation" }, { "code": null, "e": 33750, "s": 33746, "text": "XML" }, { "code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><set xmlns:android=\"http://schemas.android.com/apk/res/android\" android:interpolator=\"@android:anim/linear_interpolator\" android:fillAfter=\"true\"> <translate android:fromXDelta=\"0%p\" android:toXDelta=\"75%p\" android:duration=\"700\" /></set>", "e": 34061, "s": 33750, "text": null }, { "code": null, "e": 34081, "s": 34061, "text": "4) Rotate Animation" }, { "code": null, "e": 34085, "s": 34081, "text": "XML" }, { "code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><set xmlns:android=\"http://schemas.android.com/apk/res/android\"> <rotate android:duration=\"6000\" android:fromDegrees=\"0\" android:pivotX=\"50%\" android:pivotY=\"50%\" android:toDegrees=\"360\" /> <rotate android:duration=\"6000\" android:fromDegrees=\"360\" android:pivotX=\"50%\" android:pivotY=\"50%\" android:startOffset=\"5000\" android:toDegrees=\"0\" /> </set>", "e": 34560, "s": 34085, "text": null }, { "code": null, "e": 34579, "s": 34560, "text": "5) Slide Animation" }, { "code": null, "e": 34583, "s": 34579, "text": "XML" }, { "code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><set xmlns:android=\"http://schemas.android.com/apk/res/android\" android:fillAfter=\"true\" > <scale android:duration=\"500\" android:fromXScale=\"1.0\" android:fromYScale=\"1.0\" android:interpolator=\"@android:anim/linear_interpolator\" android:toXScale=\"1.0\" android:toYScale=\"0.0\" /></set>", "e": 34953, "s": 34583, "text": null }, { "code": null, "e": 34971, "s": 34953, "text": "6) Zoom Animation" }, { "code": null, "e": 34975, "s": 34971, "text": "XML" }, { "code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><set xmlns:android=\"http://schemas.android.com/apk/res/android\" android:fillAfter=\"true\" > <scale android:duration=\"500\" android:fromXScale=\"1.0\" android:fromYScale=\"1.0\" android:interpolator=\"@android:anim/linear_interpolator\" android:toXScale=\"1.0\" android:toYScale=\"0.0\" /></set>", "e": 35347, "s": 34975, "text": null }, { "code": null, "e": 35396, "s": 35347, "text": "Step 6: Working with the MainActivity.java file " }, { "code": null, "e": 35532, "s": 35396, "text": "Add animation to the ImageView by clicking a specific Button. Navigate to the app > java > your apps package name >> MainActivity.java." }, { "code": null, "e": 35537, "s": 35532, "text": "Java" }, { "code": "import androidx.appcompat.app.AppCompatActivity;import android.os.Bundle;import android.view.View;import android.view.animation.Animation;import android.view.animation.AnimationUtils;import android.widget.Button;import android.widget.ImageView; public class MainActivity extends AppCompatActivity { ImageView imageView; Button blinkBTN, rotateBTN, fadeBTN, moveBTN, slideBTN, zoomBTN, stopBTN; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); imageView = findViewById(R.id.imageview); blinkBTN = findViewById(R.id.BTNblink); rotateBTN = findViewById(R.id.BTNrotate); fadeBTN = findViewById(R.id.BTNfade); moveBTN = findViewById(R.id.BTNmove); slideBTN = findViewById(R.id.BTNslide); zoomBTN = findViewById(R.id.BTNzoom); stopBTN = findViewById(R.id.BTNstop); blinkBTN.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // To add blink animation Animation animation = AnimationUtils.loadAnimation(getApplicationContext(), R.anim.blink_animation); imageView.startAnimation(animation); } }); rotateBTN.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // To add rotate animation Animation animation = AnimationUtils.loadAnimation(getApplicationContext(), R.anim.rotate_animation); imageView.startAnimation(animation); } }); fadeBTN.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // To add fade animation Animation animation = AnimationUtils.loadAnimation(getApplicationContext(), R.anim.fade_animation); imageView.startAnimation(animation); } }); moveBTN.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // To add move animation Animation animation = AnimationUtils.loadAnimation(getApplicationContext(), R.anim.move_animation); imageView.startAnimation(animation); } }); slideBTN.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // To add slide animation Animation animation = AnimationUtils.loadAnimation(getApplicationContext(), R.anim.slide_animation); imageView.startAnimation(animation); } }); zoomBTN.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // To add zoom animation Animation animation = AnimationUtils.loadAnimation(getApplicationContext(), R.anim.zoom_animation); imageView.startAnimation(animation); } }); stopBTN.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // To stop the animation going on imageview imageView.clearAnimation(); } }); }}", "e": 38877, "s": 35537, "text": null }, { "code": null, "e": 39017, "s": 38877, "text": "Note: Drawables and strings can be found in the drawable folder and strings.xml file. Drawables can be found from the app > res > drawable." }, { "code": null, "e": 39025, "s": 39017, "text": "Output:" }, { "code": null, "e": 39038, "s": 39025, "text": "hemantjain99" }, { "code": null, "e": 39056, "s": 39038, "text": "Android-Animation" }, { "code": null, "e": 39063, "s": 39056, "text": "Picked" }, { "code": null, "e": 39087, "s": 39063, "text": "Technical Scripter 2020" }, { "code": null, "e": 39095, "s": 39087, "text": "Android" }, { "code": null, "e": 39100, "s": 39095, "text": "Java" }, { "code": null, "e": 39119, "s": 39100, "text": "Technical Scripter" }, { "code": null, "e": 39124, "s": 39119, "text": "Java" }, { "code": null, "e": 39132, "s": 39124, "text": "Android" }, { "code": null, "e": 39230, "s": 39132, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 39239, "s": 39230, "text": "Comments" }, { "code": null, "e": 39252, "s": 39239, "text": "Old Comments" }, { "code": null, "e": 39310, "s": 39252, "text": "How to Create and Add Data to SQLite Database in Android?" }, { "code": null, "e": 39343, "s": 39310, "text": "Services in Android with Example" }, { "code": null, "e": 39386, "s": 39343, "text": "Broadcast Receiver in Android With Example" }, { "code": null, "e": 39428, "s": 39386, "text": "Content Providers in Android with Example" }, { "code": null, "e": 39459, "s": 39428, "text": "Android RecyclerView in Kotlin" }, { "code": null, "e": 39481, "s": 39459, "text": "For-each loop in Java" }, { "code": null, "e": 39517, "s": 39481, "text": "Arrays.sort() in Java with examples" }, { "code": null, "e": 39549, "s": 39517, "text": "Initialize an ArrayList in Java" }, { "code": null, "e": 39574, "s": 39549, "text": "Reverse a string in Java" } ]
Add zero columns to Pandas Dataframe - GeeksforGeeks
11 Dec, 2020 Prerequisites: Pandas The task here is to generate a Python program using its Pandas module that can add a column with all entries as zero to an existing dataframe. A Dataframe is a two-dimensional, size-mutable, potentially heterogeneous tabular data.It is used to represent data in tabular form like an Excel file format. Below is the syntax for creating a dataframe in pandas. It can be imagines as a dictionary like container for series object. Syntax: DataFrame(data=None, index=None, columns=None, dtype=None, copy=False) Import required libraries Create or import data Add a new column with all zeroes. Example 1: Python3 # import pandas libraryimport pandas as pd # creating dictionary of listsdict = {'name': ["sohom", "rakesh", "rajshekhar", "sumit"], 'department': ["ECE", "CSE", "EE", "MCA"], 'CGPA': [9.2, 8.7, 8.6, 7.7]} # creating a dataframedf = pd.DataFrame(dict) print("data frame before adding the column:")display(df) # creating a new column# of zeroes to the# dataframedf['new'] = 0 # showing the dataframeprint("data frame after adding the column:")display(df) Output: Example 2: Python3 # import pandas libraryimport pandas as pd # create datadata = [["geeks", 1], ["for", 2], ["best", 3]] # creating a dataframedf = pd.DataFrame(data, columns=['col1', 'col2']) print("data frame before adding the column:")display(df) # creating a new column with all zero entriesdf['col3'] = 0 # showing the dataframeprint("data frame after adding the column:")display(df) Output: Python pandas-dataFrame Python-pandas Technical Scripter 2020 Python Technical Scripter Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Check if element exists in list in Python How To Convert Python Dictionary To JSON? 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": 25555, "s": 25527, "text": "\n11 Dec, 2020" }, { "code": null, "e": 25577, "s": 25555, "text": "Prerequisites: Pandas" }, { "code": null, "e": 25720, "s": 25577, "text": "The task here is to generate a Python program using its Pandas module that can add a column with all entries as zero to an existing dataframe." }, { "code": null, "e": 26004, "s": 25720, "text": "A Dataframe is a two-dimensional, size-mutable, potentially heterogeneous tabular data.It is used to represent data in tabular form like an Excel file format. Below is the syntax for creating a dataframe in pandas. It can be imagines as a dictionary like container for series object." }, { "code": null, "e": 26012, "s": 26004, "text": "Syntax:" }, { "code": null, "e": 26083, "s": 26012, "text": "DataFrame(data=None, index=None, columns=None, dtype=None, copy=False)" }, { "code": null, "e": 26109, "s": 26083, "text": "Import required libraries" }, { "code": null, "e": 26131, "s": 26109, "text": "Create or import data" }, { "code": null, "e": 26165, "s": 26131, "text": "Add a new column with all zeroes." }, { "code": null, "e": 26176, "s": 26165, "text": "Example 1:" }, { "code": null, "e": 26184, "s": 26176, "text": "Python3" }, { "code": "# import pandas libraryimport pandas as pd # creating dictionary of listsdict = {'name': [\"sohom\", \"rakesh\", \"rajshekhar\", \"sumit\"], 'department': [\"ECE\", \"CSE\", \"EE\", \"MCA\"], 'CGPA': [9.2, 8.7, 8.6, 7.7]} # creating a dataframedf = pd.DataFrame(dict) print(\"data frame before adding the column:\")display(df) # creating a new column# of zeroes to the# dataframedf['new'] = 0 # showing the dataframeprint(\"data frame after adding the column:\")display(df)", "e": 26657, "s": 26184, "text": null }, { "code": null, "e": 26665, "s": 26657, "text": "Output:" }, { "code": null, "e": 26676, "s": 26665, "text": "Example 2:" }, { "code": null, "e": 26684, "s": 26676, "text": "Python3" }, { "code": "# import pandas libraryimport pandas as pd # create datadata = [[\"geeks\", 1], [\"for\", 2], [\"best\", 3]] # creating a dataframedf = pd.DataFrame(data, columns=['col1', 'col2']) print(\"data frame before adding the column:\")display(df) # creating a new column with all zero entriesdf['col3'] = 0 # showing the dataframeprint(\"data frame after adding the column:\")display(df)", "e": 27060, "s": 26684, "text": null }, { "code": null, "e": 27068, "s": 27060, "text": "Output:" }, { "code": null, "e": 27092, "s": 27068, "text": "Python pandas-dataFrame" }, { "code": null, "e": 27106, "s": 27092, "text": "Python-pandas" }, { "code": null, "e": 27130, "s": 27106, "text": "Technical Scripter 2020" }, { "code": null, "e": 27137, "s": 27130, "text": "Python" }, { "code": null, "e": 27156, "s": 27137, "text": "Technical Scripter" }, { "code": null, "e": 27254, "s": 27156, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27286, "s": 27254, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 27328, "s": 27286, "text": "Check if element exists in list in Python" }, { "code": null, "e": 27370, "s": 27328, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 27426, "s": 27370, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 27453, "s": 27426, "text": "Python Classes and Objects" }, { "code": null, "e": 27484, "s": 27453, "text": "Python | os.path.join() method" }, { "code": null, "e": 27513, "s": 27484, "text": "Create a directory in Python" }, { "code": null, "e": 27535, "s": 27513, "text": "Defaultdict in Python" }, { "code": null, "e": 27574, "s": 27535, "text": "Python | Get unique values from a list" } ]
CSS | rotateY() Function - GeeksforGeeks
07 Aug, 2019 The rotateY() function is an inbuilt function which is used to rotate an element around the vertical axis. Syntax: rotateY( angle ) Parameters: This function accepts single parameter angle which represents the angle of rotations. The positive and negative angles rotate the elements in clockwise and counter-clockwise respectively. Below examples illustrate the rotateY() function in CSS:Example 1: <!DOCTYPE html> <html> <head> <title>CSS rotateY() function</title> <style> body { text-align:center; } h1 { color:green; } .rotateY_image { transform: rotateY(60deg); } </style> </head> <body> <h1>GeeksforGeeks</h1> <h2>CSS rotateY() function</h2> <img class="rotateY_image" src= "https://media.geeksforgeeks.org/wp-content/cdn-uploads/20190710102234/download3.png" alt="GeeksforGeeks logo"> </body> </html> Output: Example 2: <!DOCTYPE html> <html> <head> <title>CSS rotateY() function</title> <style> body { text-align:center; } h1 { color:green; } .GFG { font-size:35px; font-weight:bold; color:green; transform: rotateY(60deg); } </style> </head> <body> <h1>GeeksforGeeks</h1> <h2>CSS rotateY() function</h2> <div class="GFG">Welcome to GeeksforGeeks</div> </body> </html> Output: Supported Browsers: The browsers supported by rotateY() function are listed below: Google Chrome Internet Explorer Firefox Safari Opera CSS-Functions CSS Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to set space between the flexbox ? Design a web page using HTML and CSS Form validation using jQuery How to style a checkbox using CSS? Search Bar using HTML, CSS and JavaScript Remove elements from a JavaScript Array Installation of Node.js on Linux Convert a string to an integer in JavaScript How to fetch data from an API in ReactJS ? Difference between var, let and const keywords in JavaScript
[ { "code": null, "e": 26621, "s": 26593, "text": "\n07 Aug, 2019" }, { "code": null, "e": 26728, "s": 26621, "text": "The rotateY() function is an inbuilt function which is used to rotate an element around the vertical axis." }, { "code": null, "e": 26736, "s": 26728, "text": "Syntax:" }, { "code": null, "e": 26753, "s": 26736, "text": "rotateY( angle )" }, { "code": null, "e": 26953, "s": 26753, "text": "Parameters: This function accepts single parameter angle which represents the angle of rotations. The positive and negative angles rotate the elements in clockwise and counter-clockwise respectively." }, { "code": null, "e": 27020, "s": 26953, "text": "Below examples illustrate the rotateY() function in CSS:Example 1:" }, { "code": "<!DOCTYPE html> <html> <head> <title>CSS rotateY() function</title> <style> body { text-align:center; } h1 { color:green; } .rotateY_image { transform: rotateY(60deg); } </style> </head> <body> <h1>GeeksforGeeks</h1> <h2>CSS rotateY() function</h2> <img class=\"rotateY_image\" src= \"https://media.geeksforgeeks.org/wp-content/cdn-uploads/20190710102234/download3.png\" alt=\"GeeksforGeeks logo\"> </body> </html> ", "e": 27575, "s": 27020, "text": null }, { "code": null, "e": 27583, "s": 27575, "text": "Output:" }, { "code": null, "e": 27594, "s": 27583, "text": "Example 2:" }, { "code": "<!DOCTYPE html> <html> <head> <title>CSS rotateY() function</title> <style> body { text-align:center; } h1 { color:green; } .GFG { font-size:35px; font-weight:bold; color:green; transform: rotateY(60deg); } </style> </head> <body> <h1>GeeksforGeeks</h1> <h2>CSS rotateY() function</h2> <div class=\"GFG\">Welcome to GeeksforGeeks</div> </body> </html>", "e": 28082, "s": 27594, "text": null }, { "code": null, "e": 28090, "s": 28082, "text": "Output:" }, { "code": null, "e": 28173, "s": 28090, "text": "Supported Browsers: The browsers supported by rotateY() function are listed below:" }, { "code": null, "e": 28187, "s": 28173, "text": "Google Chrome" }, { "code": null, "e": 28205, "s": 28187, "text": "Internet Explorer" }, { "code": null, "e": 28213, "s": 28205, "text": "Firefox" }, { "code": null, "e": 28220, "s": 28213, "text": "Safari" }, { "code": null, "e": 28226, "s": 28220, "text": "Opera" }, { "code": null, "e": 28240, "s": 28226, "text": "CSS-Functions" }, { "code": null, "e": 28244, "s": 28240, "text": "CSS" }, { "code": null, "e": 28261, "s": 28244, "text": "Web Technologies" }, { "code": null, "e": 28359, "s": 28261, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28398, "s": 28359, "text": "How to set space between the flexbox ?" }, { "code": null, "e": 28435, "s": 28398, "text": "Design a web page using HTML and CSS" }, { "code": null, "e": 28464, "s": 28435, "text": "Form validation using jQuery" }, { "code": null, "e": 28499, "s": 28464, "text": "How to style a checkbox using CSS?" }, { "code": null, "e": 28541, "s": 28499, "text": "Search Bar using HTML, CSS and JavaScript" }, { "code": null, "e": 28581, "s": 28541, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 28614, "s": 28581, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 28659, "s": 28614, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 28702, "s": 28659, "text": "How to fetch data from an API in ReactJS ?" } ]
CSS - Bounce Up Effect
Bounce Animation effect is used to move the element quick up, back, or away from a surface after hitting it. @keyframes bounceInUp { 0% { opacity: 0; transform: translateY(2000px); } 60% { opacity: 1; transform: translateY(-30px); } 80% { transform: translateY(10px); } 100% { transform: translateY(0); } } Transform − Transform applies to 2d and 3d transformation to an element. Transform − Transform applies to 2d and 3d transformation to an element. Opacity − Opacity applies to an element to make translucence. Opacity − Opacity applies to an element to make translucence. <html> <head> <style> .animated { background-image: url(/css/images/logo.png); background-repeat: no-repeat; background-position: left top; padding-top:95px; margin-bottom:60px; -webkit-animation-duration: 10s; animation-duration: 10s; -webkit-animation-fill-mode: both; animation-fill-mode: both; } @-webkit-keyframes bounceInUp { 0% { opacity: 0; -webkit-transform: translateY(2000px); } 60% { opacity: 1; -webkit-transform: translateY(-30px); } 80% { -webkit-transform: translateY(10px); } 100% { -webkit-transform: translateY(0); } } @keyframes bounceInUp { 0% { opacity: 0; transform: translateY(2000px); } 60% { opacity: 1; transform: translateY(-30px); } 80% { transform: translateY(10px); } 100% { transform: translateY(0); } } .bounceInUp { -webkit-animation-name: bounceInUp; animation-name: bounceInUp; } </style> </head> <body> <div id = "animated-example" class = "animated bounceInUp"></div> <button onclick = "myFunction()">Reload page</button> <script> function myFunction() { location.reload(); } </script> </body> </html> It will produce the following result − Academic Tutorials Big Data & Analytics Computer Programming Computer Science Databases DevOps Digital Marketing Engineering Tutorials Exams Syllabus Famous Monuments GATE Exams Tutorials Latest Technologies Machine Learning Mainframe Development Management Tutorials Mathematics Tutorials Microsoft Technologies Misc tutorials Mobile Development Java Technologies Python Technologies SAP Tutorials Programming Scripts Selected Reading Software Quality Soft Skills Telecom Tutorials UPSC IAS Exams Web Development Sports Tutorials XML Technologies Multi-Language Interview Questions Academic Tutorials Big Data & Analytics Computer Programming Computer Science Databases DevOps Digital Marketing Engineering Tutorials Exams Syllabus Famous Monuments GATE Exams Tutorials Latest Technologies Machine Learning Mainframe Development Management Tutorials Mathematics Tutorials Microsoft Technologies Misc tutorials Mobile Development Java Technologies Python Technologies SAP Tutorials Programming Scripts Selected Reading Software Quality Soft Skills Telecom Tutorials UPSC IAS Exams Web Development Sports Tutorials XML Technologies Multi-Language Interview Questions Selected Reading UPSC IAS Exams Notes Developer's Best Practices Questions and Answers Effective Resume Writing HR Interview Questions Computer Glossary Who is Who Print Add Notes Bookmark this page
[ { "code": null, "e": 2735, "s": 2626, "text": "Bounce Animation effect is used to move the element quick up, back, or away from a surface after hitting it." }, { "code": null, "e": 2994, "s": 2735, "text": "@keyframes bounceInUp {\n 0% {\n opacity: 0;\n transform: translateY(2000px);\n }\n 60% {\n opacity: 1;\n transform: translateY(-30px);\n }\n 80% {\n transform: translateY(10px);\n }\n 100% {\n transform: translateY(0);\n }\n} " }, { "code": null, "e": 3067, "s": 2994, "text": "Transform − Transform applies to 2d and 3d transformation to an element." }, { "code": null, "e": 3140, "s": 3067, "text": "Transform − Transform applies to 2d and 3d transformation to an element." }, { "code": null, "e": 3202, "s": 3140, "text": "Opacity − Opacity applies to an element to make translucence." }, { "code": null, "e": 3264, "s": 3202, "text": "Opacity − Opacity applies to an element to make translucence." }, { "code": null, "e": 5007, "s": 3264, "text": "<html>\n <head>\n <style>\n .animated {\n background-image: url(/css/images/logo.png);\n background-repeat: no-repeat;\n background-position: left top;\n padding-top:95px;\n margin-bottom:60px;\n -webkit-animation-duration: 10s;\n animation-duration: 10s;\n -webkit-animation-fill-mode: both;\n animation-fill-mode: both;\n }\n \n @-webkit-keyframes bounceInUp {\n 0% {\n opacity: 0;\n -webkit-transform: translateY(2000px);\n }\n 60% {\n opacity: 1;\n -webkit-transform: translateY(-30px);\n }\n 80% {\n -webkit-transform: translateY(10px);\n }\n 100% {\n -webkit-transform: translateY(0);\n }\n }\n \n @keyframes bounceInUp {\n 0% {\n opacity: 0;\n transform: translateY(2000px);\n }\n 60% {\n opacity: 1;\n transform: translateY(-30px);\n }\n 80% {\n transform: translateY(10px);\n }\n 100% {\n transform: translateY(0);\n }\n }\n \n .bounceInUp {\n -webkit-animation-name: bounceInUp;\n animation-name: bounceInUp;\n }\n </style>\n </head>\n\n <body>\n \n <div id = \"animated-example\" class = \"animated bounceInUp\"></div>\n <button onclick = \"myFunction()\">Reload page</button>\n \n <script>\n function myFunction() {\n location.reload();\n }\n </script>\n \n </body>\n</html>" }, { "code": null, "e": 5046, "s": 5007, "text": "It will produce the following result −" }, { "code": null, "e": 5693, "s": 5046, "text": "\n\n Academic Tutorials\n Big Data & Analytics \n Computer Programming \n Computer Science \n Databases \n DevOps \n Digital Marketing \n Engineering Tutorials \n Exams Syllabus \n Famous Monuments \n GATE Exams Tutorials\n Latest Technologies \n Machine Learning \n Mainframe Development \n Management Tutorials \n Mathematics Tutorials\n Microsoft Technologies \n Misc tutorials \n Mobile Development \n Java Technologies \n Python Technologies \n SAP Tutorials \nProgramming Scripts \n Selected Reading \n Software Quality \n Soft Skills \n Telecom Tutorials \n UPSC IAS Exams \n Web Development \n Sports Tutorials \n XML Technologies \n Multi-Language\n Interview Questions\n\n" }, { "code": null, "e": 5713, "s": 5693, "text": " Academic Tutorials" }, { "code": null, "e": 5736, "s": 5713, "text": " Big Data & Analytics " }, { "code": null, "e": 5759, "s": 5736, "text": " Computer Programming " }, { "code": null, "e": 5778, "s": 5759, "text": " Computer Science " }, { "code": null, "e": 5790, "s": 5778, "text": " Databases " }, { "code": null, "e": 5799, "s": 5790, "text": " DevOps " }, { "code": null, "e": 5819, "s": 5799, "text": " Digital Marketing " }, { "code": null, "e": 5843, "s": 5819, "text": " Engineering Tutorials " }, { "code": null, "e": 5860, "s": 5843, "text": " Exams Syllabus " }, { "code": null, "e": 5879, "s": 5860, "text": " Famous Monuments " }, { "code": null, "e": 5901, "s": 5879, "text": " GATE Exams Tutorials" }, { "code": null, "e": 5923, "s": 5901, "text": " Latest Technologies " }, { "code": null, "e": 5942, "s": 5923, "text": " Machine Learning " }, { "code": null, "e": 5966, "s": 5942, "text": " Mainframe Development " }, { "code": null, "e": 5989, "s": 5966, "text": " Management Tutorials " }, { "code": null, "e": 6012, "s": 5989, "text": " Mathematics Tutorials" }, { "code": null, "e": 6037, "s": 6012, "text": " Microsoft Technologies " }, { "code": null, "e": 6054, "s": 6037, "text": " Misc tutorials " }, { "code": null, "e": 6075, "s": 6054, "text": " Mobile Development " }, { "code": null, "e": 6095, "s": 6075, "text": " Java Technologies " }, { "code": null, "e": 6117, "s": 6095, "text": " Python Technologies " }, { "code": null, "e": 6133, "s": 6117, "text": " SAP Tutorials " }, { "code": null, "e": 6154, "s": 6133, "text": "Programming Scripts " }, { "code": null, "e": 6173, "s": 6154, "text": " Selected Reading " }, { "code": null, "e": 6192, "s": 6173, "text": " Software Quality " }, { "code": null, "e": 6206, "s": 6192, "text": " Soft Skills " }, { "code": null, "e": 6226, "s": 6206, "text": " Telecom Tutorials " }, { "code": null, "e": 6243, "s": 6226, "text": " UPSC IAS Exams " }, { "code": null, "e": 6261, "s": 6243, "text": " Web Development " }, { "code": null, "e": 6280, "s": 6261, "text": " Sports Tutorials " }, { "code": null, "e": 6299, "s": 6280, "text": " XML Technologies " }, { "code": null, "e": 6315, "s": 6299, "text": " Multi-Language" }, { "code": null, "e": 6336, "s": 6315, "text": " Interview Questions" }, { "code": null, "e": 6353, "s": 6336, "text": "Selected Reading" }, { "code": null, "e": 6374, "s": 6353, "text": "UPSC IAS Exams Notes" }, { "code": null, "e": 6401, "s": 6374, "text": "Developer's Best Practices" }, { "code": null, "e": 6423, "s": 6401, "text": "Questions and Answers" }, { "code": null, "e": 6448, "s": 6423, "text": "Effective Resume Writing" }, { "code": null, "e": 6471, "s": 6448, "text": "HR Interview Questions" }, { "code": null, "e": 6489, "s": 6471, "text": "Computer Glossary" }, { "code": null, "e": 6500, "s": 6489, "text": "Who is Who" }, { "code": null, "e": 6507, "s": 6500, "text": " Print" }, { "code": null, "e": 6518, "s": 6507, "text": " Add Notes" } ]