title
stringlengths
3
221
text
stringlengths
17
477k
parsed
listlengths
0
3.17k
Happiness and Life Satisfaction. Exploratory Data Analysis on World... | by XuanKhanh Nguyen | Towards Data Science
What is the purpose of life? Is that to be happy? Why people go through all the pain and hardship? Is it to achieve happiness in some way? I’m not the only person who believed the purpose of life is happiness. If you look around, most people are pursuing happiness in their lives. On March 20th, the world celebrates the International Day of Happiness. The 2020 report ranked 156 countries by how happy their citizens perceive themselves based on their evaluations of their own lives. The rankings of national happiness are based on a Cantril ladder survey. Nationally representative samples of respondents are asked to think of a ladder, the best possible life for them being a 10, and the worst possible experience is a 0. They are then asked to rate their own current lives on that 0 to 10 scale. The report correlates the results with various life factors. In the reports, experts in economics, psychology, survey analysis, and national statistics describe how well-being measurements can be used effectively to assess nations’ progress and other topics. So, how happy are people today? Were people more comfortable in the past? How satisfied with their lives are people in different societies? How do our living conditions affect all of this? GDP: GDP per capita is a measure of a country’s economic output that accounts for its number of people. Support: Social support means having friends and other people, including family, turning to in times of need or crisis to give you a broader focus and positive self-image. Social support enhances the quality of life and provides a buffer against adverse life events. Health: Healthy Life Expectancy is the average number of years that a newborn can expect to live in “full health” — in other words, not hampered by disabling illnesses or injuries. Freedom: Freedom of choice describes an individual’s opportunity and autonomy to perform an action selected from at least two available options, unconstrained by external parties. Generosity: is defined as the residual of regressing the national average of responses to the question, “Have you donated money to a charity in past months?” on GDP capita. Corruption: The Corruption Perceptions Index (CPI) is an index published annually by Transparency International since 1995, which ranks countries “by their perceived levels of public sector corruption, as determined by expert assessments and opinion surveys.” Import Modules, Read the Dataset and Define an Evaluation TableDefine a Function to Calculate the Adjusted R2How Happiness Score is distributedThe relationship between different features with Happiness Score.Visualize and Examine DataMultiple Linear RegressionConclusion Import Modules, Read the Dataset and Define an Evaluation Table Define a Function to Calculate the Adjusted R2 How Happiness Score is distributed The relationship between different features with Happiness Score. Visualize and Examine Data Multiple Linear Regression Conclusion Grab yourself a coffee, and join me on this journey towards predicting happiness! To do some analysis, we need to set our environment up. First, we introduce some modules and read the data. The below output is the head of the data, but if you want to see more details, you might remove # signs in front of thedf_15.describe()and df_15.info() # FOR NUMERICAL ANALYTICSimport numpy as np# TO STORE AND PROCESS DATA IN DATAFRAMEimport pandas as pdimport os# BASIC VISUALIZATION PACKAGEimport matplotlib.pyplot as plt# ADVANCED PLOTINGimport seaborn as seabornInstance# TRAIN TEST SPLITfrom sklearn.model_selection import train_test_split# INTERACTIVE VISUALIZATIONimport chart_studio.plotly as py import plotly.graph_objs as goimport plotly.express as pxfrom plotly.offline import download_plotlyjs, init_notebook_mode, plot, iplotinit_notebook_mode(connected=True)import statsmodels.formula.api as statsfrom statsmodels.formula.api import olsfrom sklearn import datasetsfrom sklearn.linear_model import LinearRegressionfrom sklearn.metrics import mean_squared_errorfrom discover_feature_relationships import discover#2015 datadf_15 = pd.read_csv('2015.csv')#df_15.describe()#df_15.info()usecols = ['Rank','Country','Score','GDP','Support', 'Health','Freedom','Generosity','Corruption']df_15.drop(['Region','Standard Error', 'Dystopia Residual'],axis=1,inplace=True) df_15.columns = ['Country','Rank','Score','Support', 'GDP','Health', 'Freedom','Generosity','Corruption']df_15['Year'] = 2015 #add year columndf_15.head() I only present the 2015 data code as an example; you could do similar for other years.Parts starting with Happiness, Whisker, and Dystopia. Residual are different targets. Dystopia Residual compares each countries scores to the theoretical unhappiest country in the world. Since the data from the years have a bit of a different naming convention, we will abstract them to a common name. target = ['Top','Top-Mid', 'Low-Mid', 'Low' ]target_n = [4, 3, 2, 1]df_15["target"] = pd.qcut(df_15['Rank'], len(target), labels=target)df_15["target_n"] = pd.qcut(df_15['Rank'], len(target), labels=target_n) We then combine all data file to finaldf # APPENDING ALL TOGUETHERfinaldf = df_15.append([df_16,df_17,df_18,df_19])# finaldf.dropna(inplace = True)#CHECKING FOR MISSING DATAfinaldf.isnull().any()# FILLING MISSING VALUES OF CORRUPTION PERCEPTION WITH ITS MEANfinaldf.Corruption.fillna((finaldf.Corruption.mean()), inplace = True)finaldf.head(10) We can see the statistical detail of our dataset by using describe() function: Further, we define an empty dataframe. This dataframeincludes Root Mean Squared Error (RMSE), R-squared, Adjusted R-squared, and mean of the R-squared values obtained by the k-Fold Cross-Validation, which are the essential metrics to compare different models. Having an R-squared value closer to one and smaller RMSE means a better fit. In the following sections, we will fill this dataframe with the results. evaluation = pd.DataFrame({'Model':[], 'Details':[], 'Root Mean Squared Error (RMSE)': [], 'R-squared (training)': [], 'Adjusted R-squared (training)': [], 'R-squared (test)':[], 'Adjusted R-squared(test)':[], '5-Fold Cross Validation':[] }) R-squared increases when the number of features increases. Sometimes a more robust evaluator is preferred to compare the performance between different models. This evaluator is called adjusted R-squared, and it only increases, if the addition of the variable reduces the MSE. The definition of the adjusted R2 is: As we can see below, the Happiness Score has values above 2.85 and below 7.76. So there is no single country which has a Happiness Score above 8. We want to predict Happiness Score, so our dependent variable here is Score other features such as GPD Support Health, etc., are our independent variables. We first use scatter plots to observe relationships between variables. '''Happiness score vs gdp per capital'''px.scatter(finaldf, x="GDP", y="Score", animation_frame="Year", animation_group="Country", size="Rank", color="Country", hover_name="Country", trendline= "ols")train_data, test_data = train_test_split(finaldf, train_size = 0.8, random_state = 3)lr = LinearRegression()X_train = np.array(train_data['GDP'], dtype = pd.Series).reshape(-1,1)y_train = np.array(train_data['Score'], dtype = pd.Series)lr.fit(X_train, y_train)X_test = np.array(test_data['GDP'], dtype = pd.Series).reshape(-1,1)y_test = np.array(test_data['Score'], dtype = pd.Series)pred = lr.predict(X_test)#ROOT MEAN SQUARED ERRORrmsesm = float(format(np.sqrt(metrics.mean_squared_error(y_test,pred)),'.3f'))#R-SQUARED (TRAINING)rtrsm = float(format(lr.score(X_train, y_train),'.3f'))#R-SQUARED (TEST)rtesm = float(format(lr.score(X_test, y_test),'.3f'))cv = float(format(cross_val_score(lr,finaldf[['GDP']],finaldf['Score'],cv=5).mean(),'.3f'))print ("Average Score for Test Data: {:.3f}".format(y_test.mean()))print('Intercept: {}'.format(lr.intercept_))print('Coefficient: {}'.format(lr.coef_))r = evaluation.shape[0]evaluation.loc[r] = ['Simple Linear Regression','-',rmsesm,rtrsm,'-',rtesm,'-',cv]evaluation By using these values and the below definition, we can estimate the Happiness Score manually. The equation we use for our estimations is called hypothesis function and defined as We also printed the intercept and coefficient for the simple linear regression. Let’s show the result, shall we? Since we have just two dimensions at the simple regression, it is easy to draw it. The below chart determines the result of the simple regression. It does not look like a perfect fit, but when we work with real-world datasets, having an ideal fit is not easy. seabornInstance.set_style(style='whitegrid')plt.figure(figsize=(12,6))plt.scatter(X_test,y_test,color='blue',label="Data", s = 12)plt.plot(X_test,lr.predict(X_test),color="red",label="Predicted Regression Line")plt.xlabel("GDP per Captita", fontsize=15)plt.ylabel("Happiness Score", fontsize=15)plt.xticks(fontsize=13)plt.yticks(fontsize=13)plt.legend()plt.gca().spines['right'].set_visible(False)plt.gca().spines['top'].set_visible(False) The relationship between GDP per capita(Economy of the country) has a strong positive correlation with Happiness Score, that is, if the GDP per capita of a country is higher than the Happiness Score of that country, it is also more likely to be high. To keep the article short, I won’t include the code in this part. The code is similar to the GDP feature above. I recommend you try to implement yourself. I will include the link at the end of this article for reference. Social Support of countries also has a strong and positive relationship with Happiness Score. So, it makes sense that we need social support to be happy. People are also wired for emotions, and we experience those emotions within a social context. A healthy life expectancy has a strong and positive relationship with the Happiness Score, that is, if the country has a High Life Expectancy, it can also have a high Happiness Score. Being happy doesn’t just improve the quality of a person’s life. It may increase the quantity of our life as well. I will also be happy if I get a long healthy life. You? Freedom to make life choices has a positive relationship with Happiness Score. Choice and autonomy are more directly related to happiness than having lots of money. It gives us options to pursue meaning in our life, finding activities that stimulate and excite us. This is an essential aspect of feeling happy. Generosity Generosity has a fragile linear relationship with the Happiness Score. Why the charity has no direct relationship with happiness score? Generosity scores are calculated based on the countries which give the most to nonprofits around the world. Countries that are not generous that does not mean they are not happy. Perceptions of corruption Distribution of Perceptions of corruption rightly skewed that means very less number of the country has high perceptions of corruption. That means most of the country has corruption problems. How corruption feature impact on the Happiness Score? Perceptions of corruption data have highly skewed no wonder why the data has a weak linear relationship. Still, as we can see in the scatter plot, most of the data points are on the left side, and most of the countries with low perceptions of corruption have a Happiness Score between 4 to 6. Countries with high perception scores have a high Happiness Score above 7. We do not have big data with too many features. Thus, we have a chance to plot most of them and reach some useful analytical results. Drawing charts and examining the data before applying a model is a good practice because we may detect some possible outliers or decide to do normalization. This step is not a must but gets to know the data is always useful. We start with the histograms of dataframe. # DISTRIBUTION OF ALL NUMERIC DATAplt.rcParams['figure.figsize'] = (15, 15)df1 = finaldf[['GDP', 'Health', 'Freedom', 'Generosity','Corruption']]h = df1.hist(bins = 25, figsize = (16,16), xlabelsize = '10', ylabelsize = '10')seabornInstance.despine(left = True, bottom = True)[x.title.set_size(12) for x in h.ravel()];[x.yaxis.tick_left() for x in h.ravel()] Next, to give us a more appealing view of where each country is placed in the World ranking report, we use darker blue for countries that have the highest rating on the report (i.e., are the “happiest”), while the lighter blue represents countries with a lower ranking. We can see that countries in the European and Americas regions have a reasonably high ranking than ones in the Asian and African areas. '''World MapHappiness Rank Accross the World'''happiness_rank = dict(type = 'choropleth', locations = finaldf['Country'], locationmode = 'country names', z = finaldf['Rank'], text = finaldf['Country'], colorscale = 'Blues_', autocolorscale=False, reversescale=True, marker_line_color='darkgray', marker_line_width=0.5)layout = dict(title = 'Happiness Rank Across the World', geo = dict(showframe = False, projection = {'type': 'equirectangular'}))world_map_1 = go.Figure(data = [happiness_rank], layout=layout)iplot(world_map_1) Let’s check which countries are better positioned in each of the aspects being analyzed. fig, axes = plt.subplots(nrows=3, ncols=2,constrained_layout=True,figsize=(10,10))seabornInstance.barplot(x='GDP',y='Country', data=finaldf.nlargest(10,'GDP'), ax=axes[0,0],palette="Blues_r")seabornInstance.barplot(x='Health' ,y='Country', data=finaldf.nlargest(10,'Health'), ax=axes[0,1],palette='Blues_r')seabornInstance.barplot(x='Score' ,y='Country', data=finaldf.nlargest(10,'Score'), ax=axes[1,0],palette='Blues_r')seabornInstance.barplot(x='Generosity' ,y='Country', data=finaldf.nlargest(10,'Generosity'), ax=axes[1,1],palette='Blues_r')seabornInstance.barplot(x='Freedom' ,y='Country', data=finaldf.nlargest(10,'Freedom'), ax=axes[2,0],palette='Blues_r')seabornInstance.barplot(x='Corruption' ,y='Country', data=finaldf.nlargest(10,'Corruption'), ax=axes[2,1],palette='Blues_r') mask = np.zeros_like(finaldf[usecols].corr(), dtype=np.bool) mask[np.triu_indices_from(mask)] = Truef, ax = plt.subplots(figsize=(16, 12))plt.title('Pearson Correlation Matrix',fontsize=25)seabornInstance.heatmap(finaldf[usecols].corr(), linewidths=0.25,vmax=0.7,square=True,cmap="Blues", linecolor='w',annot=True,annot_kws={"size":8},mask=mask,cbar_kws={"shrink": .9}); It looks like GDP, Health, and Support are strongly correlated with the Happiness score. Freedom correlates quite well with the Happiness score; however, Freedom connects quite well with all data. Corruption still has a mediocre correlation with the Happiness score. In the scatterplots, we see that GDP, Health, and Support are quite linearly correlated with some noise. We find the auto-correlation of Corruption fascinating here, where everything is terrible, but if the corruption is high, the distribution is all over the place. It seems to be just a negative indicator of a threshold. I found an exciting package by Ian Ozsvald that uses. It trains random forests to predict features from each other, going a bit beyond simple correlation. # visualize hidden relationships in dataclassifier_overrides = set()df_results = discover.discover(finaldf.drop(['target', 'target_n'],axis=1).sample(frac=1), classifier_overrides) We use heat maps here to visualize how our features are clustered or vary over space. fig, ax = plt.subplots(ncols=2,figsize=(24, 8))seabornInstance.heatmap(df_results.pivot(index = 'target', columns = 'feature', values = 'score').fillna(1).loc[finaldf.drop( ['target', 'target_n'],axis = 1).columns,finaldf.drop( ['target', 'target_n'],axis = 1).columns], annot=True, center = 0, ax = ax[0], vmin = -1, vmax = 1, cmap = "Blues")seabornInstance.heatmap(df_results.pivot(index = 'target', columns = 'feature', values = 'score').fillna(1).loc[finaldf.drop( ['target', 'target_n'],axis=1).columns,finaldf.drop( ['target', 'target_n'],axis=1).columns], annot=True, center=0, ax=ax[1], vmin=-0.25, vmax=1, cmap="Blues_r")plt.plot() This gets more interesting. Corruption is a better predictor of the Happiness Score than Support. Possibly because of the ‘threshold’ we previously discovered? Moreover, although Social Support correlated quite well, it does not have substantial predictive value. I guess this is because all the distributions of the quartiles are quite close in the scatterplot. In the thirst section of this article, we used a simple linear regression to examine the relationships between the Happiness Score and other features. We found a poor fit. To improve this model, we want to add more features. Now, it is time to create some complex models. We determined features at first sight by looking at the previous sections and used them in our first multiple linear regression. As in the simple regression, we printed the coefficients which the model uses for the predictions. However, this time we must use the below definition for our predictions if we want to make calculations manually. We create a model with all features. # MULTIPLE LINEAR REGRESSION 1train_data_dm,test_data_dm = train_test_split(finaldf,train_size = 0.8,random_state=3)independent_var = ['GDP','Health','Freedom','Support','Generosity','Corruption']complex_model_1 = LinearRegression()complex_model_1.fit(train_data_dm[independent_var],train_data_dm['Score'])print('Intercept: {}'.format(complex_model_1.intercept_))print('Coefficients: {}'.format(complex_model_1.coef_))print('Happiness score = ',np.round(complex_model_1.intercept_,4), '+',np.round(complex_model_1.coef_[0],4),'∗ Support', '+',np.round(complex_model_1.coef_[1],4),'* GDP', '+',np.round(complex_model_1.coef_[2],4),'* Health', '+',np.round(complex_model_1.coef_[3],4),'* Freedom', '+',np.round(complex_model_1.coef_[4],4),'* Generosity', '+',np.round(complex_model_1.coef_[5],4),'* Corrption')pred = complex_model_1.predict(test_data_dm[independent_var])rmsecm = float(format(np.sqrt(metrics.mean_squared_error( test_data_dm['Score'],pred)),'.3f'))rtrcm = float(format(complex_model_1.score( train_data_dm[independent_var], train_data_dm['Score']),'.3f'))artrcm = float(format(adjustedR2(complex_model_1.score( train_data_dm[independent_var], train_data_dm['Score']), train_data_dm.shape[0], len(independent_var)),'.3f'))rtecm = float(format(complex_model_1.score( test_data_dm[independent_var], test_data_dm['Score']),'.3f'))artecm = float(format(adjustedR2(complex_model_1.score( test_data_dm[independent_var],test_data['Score']), test_data_dm.shape[0], len(independent_var)),'.3f'))cv = float(format(cross_val_score(complex_model_1, finaldf[independent_var], finaldf['Score'],cv=5).mean(),'.3f'))r = evaluation.shape[0]evaluation.loc[r] = ['Multiple Linear Regression-1','selected features',rmsecm,rtrcm,artrcm,rtecm,artecm,cv]evaluation.sort_values(by = '5-Fold Cross Validation', ascending=False) We knew that GDP, Support, and Health are quite linearly correlated. This time, we create a model with these three features. # MULTIPLE LINEAR REGRESSION 2train_data_dm,test_data_dm = train_test_split(finaldf,train_size = 0.8,random_state=3)independent_var = ['GDP','Health','Support']complex_model_2 = LinearRegression()complex_model_2.fit(train_data_dm[independent_var],train_data_dm['Score'])print('Intercept: {}'.format(complex_model_2.intercept_))print('Coefficients: {}'.format(complex_model_2.coef_))print('Happiness score = ',np.round(complex_model_2.intercept_,4), '+',np.round(complex_model_2.coef_[0],4),'∗ Support', '+',np.round(complex_model_2.coef_[1],4),'* GDP', '+',np.round(complex_model_2.coef_[2],4),'* Health')pred = complex_model_2.predict(test_data_dm[independent_var])rmsecm = float(format(np.sqrt(metrics.mean_squared_error( test_data_dm['Score'],pred)),'.3f'))rtrcm = float(format(complex_model_2.score( train_data_dm[independent_var], train_data_dm['Score']),'.3f'))artrcm = float(format(adjustedR2(complex_model_2.score( train_data_dm[independent_var], train_data_dm['Score']), train_data_dm.shape[0], len(independent_var)),'.3f'))rtecm = float(format(complex_model_2.score( test_data_dm[independent_var], test_data_dm['Score']),'.3f'))artecm = float(format(adjustedR2(complex_model_2.score( test_data_dm[independent_var],test_data['Score']), test_data_dm.shape[0], len(independent_var)),'.3f'))cv = float(format(cross_val_score(complex_model_2, finaldf[independent_var], finaldf['Score'],cv=5).mean(),'.3f'))r = evaluation.shape[0]evaluation.loc[r] = ['Multiple Linear Regression-2','selected features',rmsecm,rtrcm,artrcm,rtecm,artecm,cv]evaluation.sort_values(by = '5-Fold Cross Validation', ascending=False) When we look at the evaluation table, multiple linear regression -2 (selected features) is the best. However, I have doubts about its reliability, and I would prefer the multiple linear regression with all elements. X = finaldf[[ 'GDP', 'Health', 'Support','Freedom','Generosity','Corruption']]y = finaldf['Score']''' This function takes the features as input and returns the normalized values, the mean, as well as the standard deviation for each feature. '''def featureNormalize(X): mu = np.mean(X) ## Define the mean sigma = np.std(X) ## Define the standard deviation. X_norm = (X - mu)/sigma ## Scaling function. return X_norm, mu, sigmam = len(y) ## length of the training dataX = np.hstack((np.ones([m,1]), X)) ## Append the bias term (field containing all ones) to X.y = np.array(y).reshape(-1,1) ## reshape y to mx1 arraytheta = np.zeros([7,1]) ## Initialize theta (the coefficient) to a 3x1 zero vector.''' This function takes in the values for the training set as well as initial values of theta and returns the cost(J). '''def cost_function(X,y, theta): h = X.dot(theta) ## The hypothesis J = 1/(2*m)*(np.sum((h-y)**2)) ## Implementing the cost function return J''' This function takes in the values of the set, as well the intial theta values(coefficients), the learning rate, and the number of iterations. The output will be the a new set of coefficeients(theta), optimized for making predictions, as well as the array of the cost as it depreciates on each iteration. '''num_iters = 2000 ## Initialize the iteration parameter.alpha = 0.01 ## Initialize the learning rate.def gradientDescentMulti(X, y, theta, alpha, iterations): m = len(y) J_history = [] for _ in range(iterations): temp = np.dot(X, theta) - y temp = np.dot(X.T, temp) theta = theta - (alpha/m) * temp J_history.append(cost_function(X, y, theta)) ## Append the cost to the J_history array return theta, J_historyprint('Happiness score = ',np.round(theta[0],4), '+',np.round(theta[1],4),'∗ Support', '+',np.round(theta[2],4),'* GDP', '+',np.round(theta[3],4),'* Health', '+',np.round(theta[4],4),'* Freedom', '+',np.round(theta[5],4),'* Generosity', '+',np.round(theta[6],4),'* Corrption') Print out the J_history; it’s approximately 0.147. We can conclude that using gradient descent gives us a best-fit model to predict the Happiness Score. We can also use statsmodels to predict the Happiness Score. # MULTIPLE LRimport statsmodels.api as smX_sm = X = sm.add_constant(X)model = sm.OLS(y,X_sm)model.fit().summary() Our coefficient is very close to what we get here. The code in this note is available on Github. It seems like the common criticism for “The World Happiness Report” is quite valid. A high focus on GDP and strongly correlated features such as family and life expectancy. Do high GDP make you happy? In the end, we are who we are. I spend my July to analyze why people are not satisfied or don’t live fulfilling lives. I cared about the “why.” After finished analyzing the data, it raises a question: how can we chase happiness? Just a few months ago, since the lock-down, I did everything to chase happiness. I define myself as a minimalist. But I started to purchase many things, and I thought that makes me happy. I spent a lot of time on social media, I stayed connected with others, and I expected that makes me happy. I started writing on Medium; I got volunteer jobs that match my skills and interest, and I believed money and working make me happy. I tried to go vegan, and I hoped that makes me happy. At the end of the day, I am lying in my bed, alone, and thinking, “Is happiness achievable? What’s next in this endless pursuit of happiness?” Well, I realize I am chasing something random that I- myself believe makes me happy. While writing this article, I ran into a quote by Ralph Waldo Emerson: “The purpose of life is not to be happy. It is to be useful, to be honorable, to be compassionate, to have it make some difference that you have lived and lived well.” The dot is finally connected. Happiness can’t be a goal in itself. It is merely a byproduct of usefulness. What makes me happy is when I’m useful. Ok, but how? One day I woke up and thought to myself: “What am I doing for this world?” And the answer was nothing. And that same day, I started writing on Medium. I turned my school notes to articles with hope people will learn a thing or two after reading them. For you, it can be anything, like painting, creating a product, supporting your family and friends, anything you feel like doing. Please don’t take it too seriously. And the most important, don’t overthink it. Just do something useful. Anything. Stay safe and healthy! Resources: World Happiness Report 2020.Kaggle World Happiness Report.The happiness countries in the world of 2020.Engineering a happiness prediction model. World Happiness Report 2020. Kaggle World Happiness Report. The happiness countries in the world of 2020. Engineering a happiness prediction model.
[ { "code": null, "e": 310, "s": 171, "text": "What is the purpose of life? Is that to be happy? Why people go through all the pain and hardship? Is it to achieve happiness in some way?" }, { "code": null, "e": 452, "s": 310, "text": "I’m not the only person who believed the purpose of life is happiness. If you look around, most people are pursuing happiness in their lives." }, { "code": null, "e": 1230, "s": 452, "text": "On March 20th, the world celebrates the International Day of Happiness. The 2020 report ranked 156 countries by how happy their citizens perceive themselves based on their evaluations of their own lives. The rankings of national happiness are based on a Cantril ladder survey. Nationally representative samples of respondents are asked to think of a ladder, the best possible life for them being a 10, and the worst possible experience is a 0. They are then asked to rate their own current lives on that 0 to 10 scale. The report correlates the results with various life factors. In the reports, experts in economics, psychology, survey analysis, and national statistics describe how well-being measurements can be used effectively to assess nations’ progress and other topics." }, { "code": null, "e": 1419, "s": 1230, "text": "So, how happy are people today? Were people more comfortable in the past? How satisfied with their lives are people in different societies? How do our living conditions affect all of this?" }, { "code": null, "e": 1523, "s": 1419, "text": "GDP: GDP per capita is a measure of a country’s economic output that accounts for its number of people." }, { "code": null, "e": 1790, "s": 1523, "text": "Support: Social support means having friends and other people, including family, turning to in times of need or crisis to give you a broader focus and positive self-image. Social support enhances the quality of life and provides a buffer against adverse life events." }, { "code": null, "e": 1971, "s": 1790, "text": "Health: Healthy Life Expectancy is the average number of years that a newborn can expect to live in “full health” — in other words, not hampered by disabling illnesses or injuries." }, { "code": null, "e": 2151, "s": 1971, "text": "Freedom: Freedom of choice describes an individual’s opportunity and autonomy to perform an action selected from at least two available options, unconstrained by external parties." }, { "code": null, "e": 2324, "s": 2151, "text": "Generosity: is defined as the residual of regressing the national average of responses to the question, “Have you donated money to a charity in past months?” on GDP capita." }, { "code": null, "e": 2584, "s": 2324, "text": "Corruption: The Corruption Perceptions Index (CPI) is an index published annually by Transparency International since 1995, which ranks countries “by their perceived levels of public sector corruption, as determined by expert assessments and opinion surveys.”" }, { "code": null, "e": 2855, "s": 2584, "text": "Import Modules, Read the Dataset and Define an Evaluation TableDefine a Function to Calculate the Adjusted R2How Happiness Score is distributedThe relationship between different features with Happiness Score.Visualize and Examine DataMultiple Linear RegressionConclusion" }, { "code": null, "e": 2919, "s": 2855, "text": "Import Modules, Read the Dataset and Define an Evaluation Table" }, { "code": null, "e": 2966, "s": 2919, "text": "Define a Function to Calculate the Adjusted R2" }, { "code": null, "e": 3001, "s": 2966, "text": "How Happiness Score is distributed" }, { "code": null, "e": 3067, "s": 3001, "text": "The relationship between different features with Happiness Score." }, { "code": null, "e": 3094, "s": 3067, "text": "Visualize and Examine Data" }, { "code": null, "e": 3121, "s": 3094, "text": "Multiple Linear Regression" }, { "code": null, "e": 3132, "s": 3121, "text": "Conclusion" }, { "code": null, "e": 3214, "s": 3132, "text": "Grab yourself a coffee, and join me on this journey towards predicting happiness!" }, { "code": null, "e": 3474, "s": 3214, "text": "To do some analysis, we need to set our environment up. First, we introduce some modules and read the data. The below output is the head of the data, but if you want to see more details, you might remove # signs in front of thedf_15.describe()and df_15.info()" }, { "code": null, "e": 4696, "s": 3474, "text": "# FOR NUMERICAL ANALYTICSimport numpy as np# TO STORE AND PROCESS DATA IN DATAFRAMEimport pandas as pdimport os# BASIC VISUALIZATION PACKAGEimport matplotlib.pyplot as plt# ADVANCED PLOTINGimport seaborn as seabornInstance# TRAIN TEST SPLITfrom sklearn.model_selection import train_test_split# INTERACTIVE VISUALIZATIONimport chart_studio.plotly as py import plotly.graph_objs as goimport plotly.express as pxfrom plotly.offline import download_plotlyjs, init_notebook_mode, plot, iplotinit_notebook_mode(connected=True)import statsmodels.formula.api as statsfrom statsmodels.formula.api import olsfrom sklearn import datasetsfrom sklearn.linear_model import LinearRegressionfrom sklearn.metrics import mean_squared_errorfrom discover_feature_relationships import discover#2015 datadf_15 = pd.read_csv('2015.csv')#df_15.describe()#df_15.info()usecols = ['Rank','Country','Score','GDP','Support', 'Health','Freedom','Generosity','Corruption']df_15.drop(['Region','Standard Error', 'Dystopia Residual'],axis=1,inplace=True) df_15.columns = ['Country','Rank','Score','Support', 'GDP','Health', 'Freedom','Generosity','Corruption']df_15['Year'] = 2015 #add year columndf_15.head()" }, { "code": null, "e": 5084, "s": 4696, "text": "I only present the 2015 data code as an example; you could do similar for other years.Parts starting with Happiness, Whisker, and Dystopia. Residual are different targets. Dystopia Residual compares each countries scores to the theoretical unhappiest country in the world. Since the data from the years have a bit of a different naming convention, we will abstract them to a common name." }, { "code": null, "e": 5293, "s": 5084, "text": "target = ['Top','Top-Mid', 'Low-Mid', 'Low' ]target_n = [4, 3, 2, 1]df_15[\"target\"] = pd.qcut(df_15['Rank'], len(target), labels=target)df_15[\"target_n\"] = pd.qcut(df_15['Rank'], len(target), labels=target_n)" }, { "code": null, "e": 5334, "s": 5293, "text": "We then combine all data file to finaldf" }, { "code": null, "e": 5638, "s": 5334, "text": "# APPENDING ALL TOGUETHERfinaldf = df_15.append([df_16,df_17,df_18,df_19])# finaldf.dropna(inplace = True)#CHECKING FOR MISSING DATAfinaldf.isnull().any()# FILLING MISSING VALUES OF CORRUPTION PERCEPTION WITH ITS MEANfinaldf.Corruption.fillna((finaldf.Corruption.mean()), inplace = True)finaldf.head(10)" }, { "code": null, "e": 5717, "s": 5638, "text": "We can see the statistical detail of our dataset by using describe() function:" }, { "code": null, "e": 6127, "s": 5717, "text": "Further, we define an empty dataframe. This dataframeincludes Root Mean Squared Error (RMSE), R-squared, Adjusted R-squared, and mean of the R-squared values obtained by the k-Fold Cross-Validation, which are the essential metrics to compare different models. Having an R-squared value closer to one and smaller RMSE means a better fit. In the following sections, we will fill this dataframe with the results." }, { "code": null, "e": 6568, "s": 6127, "text": "evaluation = pd.DataFrame({'Model':[], 'Details':[], 'Root Mean Squared Error (RMSE)': [], 'R-squared (training)': [], 'Adjusted R-squared (training)': [], 'R-squared (test)':[], 'Adjusted R-squared(test)':[], '5-Fold Cross Validation':[] })" }, { "code": null, "e": 6882, "s": 6568, "text": "R-squared increases when the number of features increases. Sometimes a more robust evaluator is preferred to compare the performance between different models. This evaluator is called adjusted R-squared, and it only increases, if the addition of the variable reduces the MSE. The definition of the adjusted R2 is:" }, { "code": null, "e": 7028, "s": 6882, "text": "As we can see below, the Happiness Score has values above 2.85 and below 7.76. So there is no single country which has a Happiness Score above 8." }, { "code": null, "e": 7184, "s": 7028, "text": "We want to predict Happiness Score, so our dependent variable here is Score other features such as GPD Support Health, etc., are our independent variables." }, { "code": null, "e": 7255, "s": 7184, "text": "We first use scatter plots to observe relationships between variables." }, { "code": null, "e": 8539, "s": 7255, "text": "'''Happiness score vs gdp per capital'''px.scatter(finaldf, x=\"GDP\", y=\"Score\", animation_frame=\"Year\", animation_group=\"Country\", size=\"Rank\", color=\"Country\", hover_name=\"Country\", trendline= \"ols\")train_data, test_data = train_test_split(finaldf, train_size = 0.8, random_state = 3)lr = LinearRegression()X_train = np.array(train_data['GDP'], dtype = pd.Series).reshape(-1,1)y_train = np.array(train_data['Score'], dtype = pd.Series)lr.fit(X_train, y_train)X_test = np.array(test_data['GDP'], dtype = pd.Series).reshape(-1,1)y_test = np.array(test_data['Score'], dtype = pd.Series)pred = lr.predict(X_test)#ROOT MEAN SQUARED ERRORrmsesm = float(format(np.sqrt(metrics.mean_squared_error(y_test,pred)),'.3f'))#R-SQUARED (TRAINING)rtrsm = float(format(lr.score(X_train, y_train),'.3f'))#R-SQUARED (TEST)rtesm = float(format(lr.score(X_test, y_test),'.3f'))cv = float(format(cross_val_score(lr,finaldf[['GDP']],finaldf['Score'],cv=5).mean(),'.3f'))print (\"Average Score for Test Data: {:.3f}\".format(y_test.mean()))print('Intercept: {}'.format(lr.intercept_))print('Coefficient: {}'.format(lr.coef_))r = evaluation.shape[0]evaluation.loc[r] = ['Simple Linear Regression','-',rmsesm,rtrsm,'-',rtesm,'-',cv]evaluation" }, { "code": null, "e": 8718, "s": 8539, "text": "By using these values and the below definition, we can estimate the Happiness Score manually. The equation we use for our estimations is called hypothesis function and defined as" }, { "code": null, "e": 8798, "s": 8718, "text": "We also printed the intercept and coefficient for the simple linear regression." }, { "code": null, "e": 8831, "s": 8798, "text": "Let’s show the result, shall we?" }, { "code": null, "e": 9091, "s": 8831, "text": "Since we have just two dimensions at the simple regression, it is easy to draw it. The below chart determines the result of the simple regression. It does not look like a perfect fit, but when we work with real-world datasets, having an ideal fit is not easy." }, { "code": null, "e": 9531, "s": 9091, "text": "seabornInstance.set_style(style='whitegrid')plt.figure(figsize=(12,6))plt.scatter(X_test,y_test,color='blue',label=\"Data\", s = 12)plt.plot(X_test,lr.predict(X_test),color=\"red\",label=\"Predicted Regression Line\")plt.xlabel(\"GDP per Captita\", fontsize=15)plt.ylabel(\"Happiness Score\", fontsize=15)plt.xticks(fontsize=13)plt.yticks(fontsize=13)plt.legend()plt.gca().spines['right'].set_visible(False)plt.gca().spines['top'].set_visible(False)" }, { "code": null, "e": 9782, "s": 9531, "text": "The relationship between GDP per capita(Economy of the country) has a strong positive correlation with Happiness Score, that is, if the GDP per capita of a country is higher than the Happiness Score of that country, it is also more likely to be high." }, { "code": null, "e": 10003, "s": 9782, "text": "To keep the article short, I won’t include the code in this part. The code is similar to the GDP feature above. I recommend you try to implement yourself. I will include the link at the end of this article for reference." }, { "code": null, "e": 10251, "s": 10003, "text": "Social Support of countries also has a strong and positive relationship with Happiness Score. So, it makes sense that we need social support to be happy. People are also wired for emotions, and we experience those emotions within a social context." }, { "code": null, "e": 10606, "s": 10251, "text": "A healthy life expectancy has a strong and positive relationship with the Happiness Score, that is, if the country has a High Life Expectancy, it can also have a high Happiness Score. Being happy doesn’t just improve the quality of a person’s life. It may increase the quantity of our life as well. I will also be happy if I get a long healthy life. You?" }, { "code": null, "e": 10917, "s": 10606, "text": "Freedom to make life choices has a positive relationship with Happiness Score. Choice and autonomy are more directly related to happiness than having lots of money. It gives us options to pursue meaning in our life, finding activities that stimulate and excite us. This is an essential aspect of feeling happy." }, { "code": null, "e": 10928, "s": 10917, "text": "Generosity" }, { "code": null, "e": 11243, "s": 10928, "text": "Generosity has a fragile linear relationship with the Happiness Score. Why the charity has no direct relationship with happiness score? Generosity scores are calculated based on the countries which give the most to nonprofits around the world. Countries that are not generous that does not mean they are not happy." }, { "code": null, "e": 11269, "s": 11243, "text": "Perceptions of corruption" }, { "code": null, "e": 11461, "s": 11269, "text": "Distribution of Perceptions of corruption rightly skewed that means very less number of the country has high perceptions of corruption. That means most of the country has corruption problems." }, { "code": null, "e": 11515, "s": 11461, "text": "How corruption feature impact on the Happiness Score?" }, { "code": null, "e": 11883, "s": 11515, "text": "Perceptions of corruption data have highly skewed no wonder why the data has a weak linear relationship. Still, as we can see in the scatter plot, most of the data points are on the left side, and most of the countries with low perceptions of corruption have a Happiness Score between 4 to 6. Countries with high perception scores have a high Happiness Score above 7." }, { "code": null, "e": 12285, "s": 11883, "text": "We do not have big data with too many features. Thus, we have a chance to plot most of them and reach some useful analytical results. Drawing charts and examining the data before applying a model is a good practice because we may detect some possible outliers or decide to do normalization. This step is not a must but gets to know the data is always useful. We start with the histograms of dataframe." }, { "code": null, "e": 12669, "s": 12285, "text": "# DISTRIBUTION OF ALL NUMERIC DATAplt.rcParams['figure.figsize'] = (15, 15)df1 = finaldf[['GDP', 'Health', 'Freedom', 'Generosity','Corruption']]h = df1.hist(bins = 25, figsize = (16,16), xlabelsize = '10', ylabelsize = '10')seabornInstance.despine(left = True, bottom = True)[x.title.set_size(12) for x in h.ravel()];[x.yaxis.tick_left() for x in h.ravel()]" }, { "code": null, "e": 13075, "s": 12669, "text": "Next, to give us a more appealing view of where each country is placed in the World ranking report, we use darker blue for countries that have the highest rating on the report (i.e., are the “happiest”), while the lighter blue represents countries with a lower ranking. We can see that countries in the European and Americas regions have a reasonably high ranking than ones in the Asian and African areas." }, { "code": null, "e": 13732, "s": 13075, "text": "'''World MapHappiness Rank Accross the World'''happiness_rank = dict(type = 'choropleth', locations = finaldf['Country'], locationmode = 'country names', z = finaldf['Rank'], text = finaldf['Country'], colorscale = 'Blues_', autocolorscale=False, reversescale=True, marker_line_color='darkgray', marker_line_width=0.5)layout = dict(title = 'Happiness Rank Across the World', geo = dict(showframe = False, projection = {'type': 'equirectangular'}))world_map_1 = go.Figure(data = [happiness_rank], layout=layout)iplot(world_map_1)" }, { "code": null, "e": 13821, "s": 13732, "text": "Let’s check which countries are better positioned in each of the aspects being analyzed." }, { "code": null, "e": 14885, "s": 13821, "text": "fig, axes = plt.subplots(nrows=3, ncols=2,constrained_layout=True,figsize=(10,10))seabornInstance.barplot(x='GDP',y='Country', data=finaldf.nlargest(10,'GDP'), ax=axes[0,0],palette=\"Blues_r\")seabornInstance.barplot(x='Health' ,y='Country', data=finaldf.nlargest(10,'Health'), ax=axes[0,1],palette='Blues_r')seabornInstance.barplot(x='Score' ,y='Country', data=finaldf.nlargest(10,'Score'), ax=axes[1,0],palette='Blues_r')seabornInstance.barplot(x='Generosity' ,y='Country', data=finaldf.nlargest(10,'Generosity'), ax=axes[1,1],palette='Blues_r')seabornInstance.barplot(x='Freedom' ,y='Country', data=finaldf.nlargest(10,'Freedom'), ax=axes[2,0],palette='Blues_r')seabornInstance.barplot(x='Corruption' ,y='Country', data=finaldf.nlargest(10,'Corruption'), ax=axes[2,1],palette='Blues_r')" }, { "code": null, "e": 15291, "s": 14885, "text": "mask = np.zeros_like(finaldf[usecols].corr(), dtype=np.bool) mask[np.triu_indices_from(mask)] = Truef, ax = plt.subplots(figsize=(16, 12))plt.title('Pearson Correlation Matrix',fontsize=25)seabornInstance.heatmap(finaldf[usecols].corr(), linewidths=0.25,vmax=0.7,square=True,cmap=\"Blues\", linecolor='w',annot=True,annot_kws={\"size\":8},mask=mask,cbar_kws={\"shrink\": .9});" }, { "code": null, "e": 15558, "s": 15291, "text": "It looks like GDP, Health, and Support are strongly correlated with the Happiness score. Freedom correlates quite well with the Happiness score; however, Freedom connects quite well with all data. Corruption still has a mediocre correlation with the Happiness score." }, { "code": null, "e": 15882, "s": 15558, "text": "In the scatterplots, we see that GDP, Health, and Support are quite linearly correlated with some noise. We find the auto-correlation of Corruption fascinating here, where everything is terrible, but if the corruption is high, the distribution is all over the place. It seems to be just a negative indicator of a threshold." }, { "code": null, "e": 16037, "s": 15882, "text": "I found an exciting package by Ian Ozsvald that uses. It trains random forests to predict features from each other, going a bit beyond simple correlation." }, { "code": null, "e": 16248, "s": 16037, "text": "# visualize hidden relationships in dataclassifier_overrides = set()df_results = discover.discover(finaldf.drop(['target', 'target_n'],axis=1).sample(frac=1), classifier_overrides)" }, { "code": null, "e": 16334, "s": 16248, "text": "We use heat maps here to visualize how our features are clustered or vary over space." }, { "code": null, "e": 17256, "s": 16334, "text": "fig, ax = plt.subplots(ncols=2,figsize=(24, 8))seabornInstance.heatmap(df_results.pivot(index = 'target', columns = 'feature', values = 'score').fillna(1).loc[finaldf.drop( ['target', 'target_n'],axis = 1).columns,finaldf.drop( ['target', 'target_n'],axis = 1).columns], annot=True, center = 0, ax = ax[0], vmin = -1, vmax = 1, cmap = \"Blues\")seabornInstance.heatmap(df_results.pivot(index = 'target', columns = 'feature', values = 'score').fillna(1).loc[finaldf.drop( ['target', 'target_n'],axis=1).columns,finaldf.drop( ['target', 'target_n'],axis=1).columns], annot=True, center=0, ax=ax[1], vmin=-0.25, vmax=1, cmap=\"Blues_r\")plt.plot()" }, { "code": null, "e": 17416, "s": 17256, "text": "This gets more interesting. Corruption is a better predictor of the Happiness Score than Support. Possibly because of the ‘threshold’ we previously discovered?" }, { "code": null, "e": 17619, "s": 17416, "text": "Moreover, although Social Support correlated quite well, it does not have substantial predictive value. I guess this is because all the distributions of the quartiles are quite close in the scatterplot." }, { "code": null, "e": 17891, "s": 17619, "text": "In the thirst section of this article, we used a simple linear regression to examine the relationships between the Happiness Score and other features. We found a poor fit. To improve this model, we want to add more features. Now, it is time to create some complex models." }, { "code": null, "e": 18233, "s": 17891, "text": "We determined features at first sight by looking at the previous sections and used them in our first multiple linear regression. As in the simple regression, we printed the coefficients which the model uses for the predictions. However, this time we must use the below definition for our predictions if we want to make calculations manually." }, { "code": null, "e": 18270, "s": 18233, "text": "We create a model with all features." }, { "code": null, "e": 20448, "s": 18270, "text": "# MULTIPLE LINEAR REGRESSION 1train_data_dm,test_data_dm = train_test_split(finaldf,train_size = 0.8,random_state=3)independent_var = ['GDP','Health','Freedom','Support','Generosity','Corruption']complex_model_1 = LinearRegression()complex_model_1.fit(train_data_dm[independent_var],train_data_dm['Score'])print('Intercept: {}'.format(complex_model_1.intercept_))print('Coefficients: {}'.format(complex_model_1.coef_))print('Happiness score = ',np.round(complex_model_1.intercept_,4), '+',np.round(complex_model_1.coef_[0],4),'∗ Support', '+',np.round(complex_model_1.coef_[1],4),'* GDP', '+',np.round(complex_model_1.coef_[2],4),'* Health', '+',np.round(complex_model_1.coef_[3],4),'* Freedom', '+',np.round(complex_model_1.coef_[4],4),'* Generosity', '+',np.round(complex_model_1.coef_[5],4),'* Corrption')pred = complex_model_1.predict(test_data_dm[independent_var])rmsecm = float(format(np.sqrt(metrics.mean_squared_error( test_data_dm['Score'],pred)),'.3f'))rtrcm = float(format(complex_model_1.score( train_data_dm[independent_var], train_data_dm['Score']),'.3f'))artrcm = float(format(adjustedR2(complex_model_1.score( train_data_dm[independent_var], train_data_dm['Score']), train_data_dm.shape[0], len(independent_var)),'.3f'))rtecm = float(format(complex_model_1.score( test_data_dm[independent_var], test_data_dm['Score']),'.3f'))artecm = float(format(adjustedR2(complex_model_1.score( test_data_dm[independent_var],test_data['Score']), test_data_dm.shape[0], len(independent_var)),'.3f'))cv = float(format(cross_val_score(complex_model_1, finaldf[independent_var], finaldf['Score'],cv=5).mean(),'.3f'))r = evaluation.shape[0]evaluation.loc[r] = ['Multiple Linear Regression-1','selected features',rmsecm,rtrcm,artrcm,rtecm,artecm,cv]evaluation.sort_values(by = '5-Fold Cross Validation', ascending=False)" }, { "code": null, "e": 20573, "s": 20448, "text": "We knew that GDP, Support, and Health are quite linearly correlated. This time, we create a model with these three features." }, { "code": null, "e": 22532, "s": 20573, "text": "# MULTIPLE LINEAR REGRESSION 2train_data_dm,test_data_dm = train_test_split(finaldf,train_size = 0.8,random_state=3)independent_var = ['GDP','Health','Support']complex_model_2 = LinearRegression()complex_model_2.fit(train_data_dm[independent_var],train_data_dm['Score'])print('Intercept: {}'.format(complex_model_2.intercept_))print('Coefficients: {}'.format(complex_model_2.coef_))print('Happiness score = ',np.round(complex_model_2.intercept_,4), '+',np.round(complex_model_2.coef_[0],4),'∗ Support', '+',np.round(complex_model_2.coef_[1],4),'* GDP', '+',np.round(complex_model_2.coef_[2],4),'* Health')pred = complex_model_2.predict(test_data_dm[independent_var])rmsecm = float(format(np.sqrt(metrics.mean_squared_error( test_data_dm['Score'],pred)),'.3f'))rtrcm = float(format(complex_model_2.score( train_data_dm[independent_var], train_data_dm['Score']),'.3f'))artrcm = float(format(adjustedR2(complex_model_2.score( train_data_dm[independent_var], train_data_dm['Score']), train_data_dm.shape[0], len(independent_var)),'.3f'))rtecm = float(format(complex_model_2.score( test_data_dm[independent_var], test_data_dm['Score']),'.3f'))artecm = float(format(adjustedR2(complex_model_2.score( test_data_dm[independent_var],test_data['Score']), test_data_dm.shape[0], len(independent_var)),'.3f'))cv = float(format(cross_val_score(complex_model_2, finaldf[independent_var], finaldf['Score'],cv=5).mean(),'.3f'))r = evaluation.shape[0]evaluation.loc[r] = ['Multiple Linear Regression-2','selected features',rmsecm,rtrcm,artrcm,rtecm,artecm,cv]evaluation.sort_values(by = '5-Fold Cross Validation', ascending=False)" }, { "code": null, "e": 22748, "s": 22532, "text": "When we look at the evaluation table, multiple linear regression -2 (selected features) is the best. However, I have doubts about its reliability, and I would prefer the multiple linear regression with all elements." }, { "code": null, "e": 24827, "s": 22748, "text": "X = finaldf[[ 'GDP', 'Health', 'Support','Freedom','Generosity','Corruption']]y = finaldf['Score']''' This function takes the features as input and returns the normalized values, the mean, as well as the standard deviation for each feature. '''def featureNormalize(X): mu = np.mean(X) ## Define the mean sigma = np.std(X) ## Define the standard deviation. X_norm = (X - mu)/sigma ## Scaling function. return X_norm, mu, sigmam = len(y) ## length of the training dataX = np.hstack((np.ones([m,1]), X)) ## Append the bias term (field containing all ones) to X.y = np.array(y).reshape(-1,1) ## reshape y to mx1 arraytheta = np.zeros([7,1]) ## Initialize theta (the coefficient) to a 3x1 zero vector.''' This function takes in the values for the training set as well as initial values of theta and returns the cost(J). '''def cost_function(X,y, theta): h = X.dot(theta) ## The hypothesis J = 1/(2*m)*(np.sum((h-y)**2)) ## Implementing the cost function return J''' This function takes in the values of the set, as well the intial theta values(coefficients), the learning rate, and the number of iterations. The output will be the a new set of coefficeients(theta), optimized for making predictions, as well as the array of the cost as it depreciates on each iteration. '''num_iters = 2000 ## Initialize the iteration parameter.alpha = 0.01 ## Initialize the learning rate.def gradientDescentMulti(X, y, theta, alpha, iterations): m = len(y) J_history = [] for _ in range(iterations): temp = np.dot(X, theta) - y temp = np.dot(X.T, temp) theta = theta - (alpha/m) * temp J_history.append(cost_function(X, y, theta)) ## Append the cost to the J_history array return theta, J_historyprint('Happiness score = ',np.round(theta[0],4), '+',np.round(theta[1],4),'∗ Support', '+',np.round(theta[2],4),'* GDP', '+',np.round(theta[3],4),'* Health', '+',np.round(theta[4],4),'* Freedom', '+',np.round(theta[5],4),'* Generosity', '+',np.round(theta[6],4),'* Corrption')" }, { "code": null, "e": 24980, "s": 24827, "text": "Print out the J_history; it’s approximately 0.147. We can conclude that using gradient descent gives us a best-fit model to predict the Happiness Score." }, { "code": null, "e": 25040, "s": 24980, "text": "We can also use statsmodels to predict the Happiness Score." }, { "code": null, "e": 25154, "s": 25040, "text": "# MULTIPLE LRimport statsmodels.api as smX_sm = X = sm.add_constant(X)model = sm.OLS(y,X_sm)model.fit().summary()" }, { "code": null, "e": 25205, "s": 25154, "text": "Our coefficient is very close to what we get here." }, { "code": null, "e": 25251, "s": 25205, "text": "The code in this note is available on Github." }, { "code": null, "e": 25424, "s": 25251, "text": "It seems like the common criticism for “The World Happiness Report” is quite valid. A high focus on GDP and strongly correlated features such as family and life expectancy." }, { "code": null, "e": 25681, "s": 25424, "text": "Do high GDP make you happy? In the end, we are who we are. I spend my July to analyze why people are not satisfied or don’t live fulfilling lives. I cared about the “why.” After finished analyzing the data, it raises a question: how can we chase happiness?" }, { "code": null, "e": 25762, "s": 25681, "text": "Just a few months ago, since the lock-down, I did everything to chase happiness." }, { "code": null, "e": 25869, "s": 25762, "text": "I define myself as a minimalist. But I started to purchase many things, and I thought that makes me happy." }, { "code": null, "e": 25976, "s": 25869, "text": "I spent a lot of time on social media, I stayed connected with others, and I expected that makes me happy." }, { "code": null, "e": 26109, "s": 25976, "text": "I started writing on Medium; I got volunteer jobs that match my skills and interest, and I believed money and working make me happy." }, { "code": null, "e": 26163, "s": 26109, "text": "I tried to go vegan, and I hoped that makes me happy." }, { "code": null, "e": 26306, "s": 26163, "text": "At the end of the day, I am lying in my bed, alone, and thinking, “Is happiness achievable? What’s next in this endless pursuit of happiness?”" }, { "code": null, "e": 26391, "s": 26306, "text": "Well, I realize I am chasing something random that I- myself believe makes me happy." }, { "code": null, "e": 26462, "s": 26391, "text": "While writing this article, I ran into a quote by Ralph Waldo Emerson:" }, { "code": null, "e": 26630, "s": 26462, "text": "“The purpose of life is not to be happy. It is to be useful, to be honorable, to be compassionate, to have it make some difference that you have lived and lived well.”" }, { "code": null, "e": 26737, "s": 26630, "text": "The dot is finally connected. Happiness can’t be a goal in itself. It is merely a byproduct of usefulness." }, { "code": null, "e": 27287, "s": 26737, "text": "What makes me happy is when I’m useful. Ok, but how? One day I woke up and thought to myself: “What am I doing for this world?” And the answer was nothing. And that same day, I started writing on Medium. I turned my school notes to articles with hope people will learn a thing or two after reading them. For you, it can be anything, like painting, creating a product, supporting your family and friends, anything you feel like doing. Please don’t take it too seriously. And the most important, don’t overthink it. Just do something useful. Anything." }, { "code": null, "e": 27310, "s": 27287, "text": "Stay safe and healthy!" }, { "code": null, "e": 27321, "s": 27310, "text": "Resources:" }, { "code": null, "e": 27466, "s": 27321, "text": "World Happiness Report 2020.Kaggle World Happiness Report.The happiness countries in the world of 2020.Engineering a happiness prediction model." }, { "code": null, "e": 27495, "s": 27466, "text": "World Happiness Report 2020." }, { "code": null, "e": 27526, "s": 27495, "text": "Kaggle World Happiness Report." }, { "code": null, "e": 27572, "s": 27526, "text": "The happiness countries in the world of 2020." } ]
Cordova - First Application
We have understood how to install Cordova and set up the environment for it. Once everything is ready, we can create our first hybrid Cordova application. Open the directory where you want the app to be installed in command prompt. We will create it on desktop. C:\Users\username\Desktop>cordova create CordovaProject io.cordova.hellocordova CordovaApp CordovaProject is the directory name where the app is created. CordovaProject is the directory name where the app is created. io.cordova.hellocordova is the default reverse domain value. You should use your own domain value if possible. io.cordova.hellocordova is the default reverse domain value. You should use your own domain value if possible. CordovaApp is the title of your app. CordovaApp is the title of your app. You need to open your project directory in the command prompt. In our example, it is the CordovaProject. You should only choose platforms that you need. To be able to use the specified platform, you need to have installed the specific platform SDK. Since we are developing on windows, we can use the following platforms. We have already installed Android SDK, so we will only install android platform for this tutorial. C:\Users\username\Desktop\CordovaProject>cordova platform add android There are other platforms that can be used on Windows OS. C:\Users\username\Desktop\CordovaProject>cordova platform add wp8 C:\Users\username\Desktop\CordovaProject>cordova platform add amazon-fireos C:\Users\username\Desktop\CordovaProject>cordova platform add windows C:\Users\username\Desktop\CordovaProject>cordova platform add blackberry10 C:\Users\username\Desktop\CordovaProject>cordova platform add firefoxos If you are developing on Mac, you can use − $ cordova platform add IOS $ cordova platform add amazon-fireos $ cordova platform add android $ cordova platform add blackberry10 $ cordova platform add firefoxos You can also remove platform from your project by using − C:\Users\username\Desktop\CordovaProject>cordova platform rm android In this step we will build the app for a specified platform so we can run it on mobile device or emulator. C:\Users\username\Desktop\CordovaProject>cordova build android Now we can run our app. If you are using the default emulator you should use − C:\Users\username\Desktop\CordovaProject>cordova emulate android If you want to use the external emulator or real device you should use − C:\Users\username\Desktop\CordovaProject>cordova run android NOTE − We will use the Genymotion android emulator since it is faster and more responsive than the default one. You can find the emulator here. You can also use real device for testing by enabling USB debugging from the options and connecting it to your computer via USB cable. For some devices, you will also need to install the USB driver. Once we run the app, it will install it on the platform we specified. If everything is finished without errors, the output should show the default start screen of the app. In our next tutorial, we will show you how to configure the Cordova Application. 45 Lectures 2 hours Skillbakerystudios 16 Lectures 1 hours Nilay Mehta Print Add Notes Bookmark this page
[ { "code": null, "e": 2335, "s": 2180, "text": "We have understood how to install Cordova and set up the environment for it. Once everything is ready, we can create our first hybrid Cordova application." }, { "code": null, "e": 2442, "s": 2335, "text": "Open the directory where you want the app to be installed in command prompt. We will create it on desktop." }, { "code": null, "e": 2538, "s": 2442, "text": "C:\\Users\\username\\Desktop>cordova \n create CordovaProject io.cordova.hellocordova CordovaApp\n" }, { "code": null, "e": 2601, "s": 2538, "text": "CordovaProject is the directory name where the app is created." }, { "code": null, "e": 2664, "s": 2601, "text": "CordovaProject is the directory name where the app is created." }, { "code": null, "e": 2775, "s": 2664, "text": "io.cordova.hellocordova is the default reverse domain value. You should use your own domain value if possible." }, { "code": null, "e": 2886, "s": 2775, "text": "io.cordova.hellocordova is the default reverse domain value. You should use your own domain value if possible." }, { "code": null, "e": 2923, "s": 2886, "text": "CordovaApp is the title of your app." }, { "code": null, "e": 2960, "s": 2923, "text": "CordovaApp is the title of your app." }, { "code": null, "e": 3380, "s": 2960, "text": "You need to open your project directory in the command prompt. In our example, it is the CordovaProject. You should only choose platforms that you need. To be able to use the specified platform, you need to have installed the specific platform SDK. Since we are developing on windows, we can use the following platforms. We have already installed Android SDK, so we will only install android platform for this tutorial." }, { "code": null, "e": 3452, "s": 3380, "text": "C:\\Users\\username\\Desktop\\CordovaProject>cordova platform add android \n" }, { "code": null, "e": 3510, "s": 3452, "text": "There are other platforms that can be used on Windows OS." }, { "code": null, "e": 3578, "s": 3510, "text": "C:\\Users\\username\\Desktop\\CordovaProject>cordova platform add wp8 \n" }, { "code": null, "e": 3656, "s": 3578, "text": "C:\\Users\\username\\Desktop\\CordovaProject>cordova platform add amazon-fireos \n" }, { "code": null, "e": 3728, "s": 3656, "text": "C:\\Users\\username\\Desktop\\CordovaProject>cordova platform add windows \n" }, { "code": null, "e": 3804, "s": 3728, "text": "C:\\Users\\username\\Desktop\\CordovaProject>cordova platform add blackberry10\n" }, { "code": null, "e": 3878, "s": 3804, "text": "C:\\Users\\username\\Desktop\\CordovaProject>cordova platform add firefoxos \n" }, { "code": null, "e": 3922, "s": 3878, "text": "If you are developing on Mac, you can use −" }, { "code": null, "e": 3951, "s": 3922, "text": "$ cordova platform add IOS \n" }, { "code": null, "e": 3990, "s": 3951, "text": "$ cordova platform add amazon-fireos \n" }, { "code": null, "e": 4023, "s": 3990, "text": "$ cordova platform add android \n" }, { "code": null, "e": 4061, "s": 4023, "text": "$ cordova platform add blackberry10 \n" }, { "code": null, "e": 4096, "s": 4061, "text": "$ cordova platform add firefoxos \n" }, { "code": null, "e": 4154, "s": 4096, "text": "You can also remove platform from your project by using −" }, { "code": null, "e": 4225, "s": 4154, "text": "C:\\Users\\username\\Desktop\\CordovaProject>cordova platform rm android \n" }, { "code": null, "e": 4332, "s": 4225, "text": "In this step we will build the app for a specified platform so we can run it on mobile device or emulator." }, { "code": null, "e": 4397, "s": 4332, "text": "C:\\Users\\username\\Desktop\\CordovaProject>cordova build android \n" }, { "code": null, "e": 4476, "s": 4397, "text": "Now we can run our app. If you are using the default emulator you should use −" }, { "code": null, "e": 4543, "s": 4476, "text": "C:\\Users\\username\\Desktop\\CordovaProject>cordova emulate android \n" }, { "code": null, "e": 4616, "s": 4543, "text": "If you want to use the external emulator or real device you should use −" }, { "code": null, "e": 4679, "s": 4616, "text": "C:\\Users\\username\\Desktop\\CordovaProject>cordova run android \n" }, { "code": null, "e": 5021, "s": 4679, "text": "NOTE − We will use the Genymotion android emulator since it is faster and more responsive than the default one. You can find the emulator here. You can also use real device for testing by enabling USB debugging from the options and connecting it to your computer via USB cable. For some devices, you will also need to install the USB driver." }, { "code": null, "e": 5193, "s": 5021, "text": "Once we run the app, it will install it on the platform we specified. If everything is finished without errors, the output should show the default start screen of the app." }, { "code": null, "e": 5274, "s": 5193, "text": "In our next tutorial, we will show you how to configure the Cordova Application." }, { "code": null, "e": 5307, "s": 5274, "text": "\n 45 Lectures \n 2 hours \n" }, { "code": null, "e": 5327, "s": 5307, "text": " Skillbakerystudios" }, { "code": null, "e": 5360, "s": 5327, "text": "\n 16 Lectures \n 1 hours \n" }, { "code": null, "e": 5373, "s": 5360, "text": " Nilay Mehta" }, { "code": null, "e": 5380, "s": 5373, "text": " Print" }, { "code": null, "e": 5391, "s": 5380, "text": " Add Notes" } ]
Count numbers having 0 as a digit
19 Apr, 2021 Problem: Count how many integers from 1 to N contains 0 as a digit.Examples: Input: n = 9 Output: 0 Input: n = 107 Output: 17 The numbers having 0 are 10, 20,..90, 100, 101..107 Input: n = 155 Output: 24 The numbers having 0 are 10, 20,..90, 100, 101..110, 120, ..150. A naive solution is discussed in previous postIn this post an optimized solution is discussed. Let’s analyze the problem closely.Let the given number has d digits .The required answer can be computed by computing the following two values: Count of 0 digit integers having maximum of d-1 digits.Count of 0 digit integers having exactly d digits (less than/ equal to the given number of course!) Count of 0 digit integers having maximum of d-1 digits. Count of 0 digit integers having exactly d digits (less than/ equal to the given number of course!) Therefore, the solution would be the sum of above two.The first part has already been discussed here.How to find the second part? We can find the total number of integers having d digits (less than equal to given number), which don’t contain any zero.To find this we traverse the number, one digit at a time.We find count of non-negative integers as follows: If the number at that place is zero, decrement counter by 1 and break (because we can’t move any further, decrement to assure that the number itself contains a zero)else , multiply the (number-1), with power(9, number of digits to the right to it) If the number at that place is zero, decrement counter by 1 and break (because we can’t move any further, decrement to assure that the number itself contains a zero) else , multiply the (number-1), with power(9, number of digits to the right to it) Let’s illustrate with an example. Let the number be n = 123. non_zero = 0 We encounter 1 first, add (1-1)*92 to non_zero (= 0+0) We encounter 2, add (2-1)*91 to non_zero (= 0+9 = 9) We encounter 3, add (3-1)*90 to non_zero (=9+3 = 12) We can observe that non_zero denotes the number of integer consisting of 3 digits (not greater than 123) and don’t contain any zero. i.e., (111, 112, ....., 119, 121, 122, 123) (It is recommended to verify it once)Now, one may ask what’s the point of calculating the count of numbers which don’t have any zeroes?Correct! we’re interested to find the count of integers which have zero.However, we can now easily find that by subtracting non_zero from n after ignoring the most significant place.i.e., In our previous example zero = 23 – non_zero = 23-12 =11 and finally we add the two parts to arrive at the required result!!Below is implementation of above idea. C++ Java Python3 C# PHP Javascript //Modified C++ program to count number from 1 to n with// 0 as a digit.#include <bits/stdc++.h>using namespace std; // Returns count of integers having zero upto given digitsint zeroUpto(int digits){ // Refer below article for details // https://www.geeksforgeeks.org/count-positive-integers-0-digit/ int first = (pow(10,digits)-1)/9; int second = (pow(9,digits)-1)/8; return 9 * (first - second);} // utility function to convert character representation// to integerint toInt(char c){ return int(c)-48;} // counts numbers having zero as digits upto a given// number 'num'int countZero(string num){ // k denoted the number of digits in the number int k = num.length(); // Calculating the total number having zeros, // which upto k-1 digits int total = zeroUpto(k-1); // Now let us calculate the numbers which don't have // any zeros. In that k digits upto the given number int non_zero = 0; for (int i=0; i<num.length(); i++) { // If the number itself contains a zero then // decrement the counter if (num[i] == '0') { non_zero--; break; } // Adding the number of non zero numbers that // can be formed non_zero += (toInt(num[i])-1) * (pow(9,k-1-i)); } int no = 0, remaining = 0,calculatedUpto=0; // Calculate the number and the remaining after // ignoring the most significant digit for (int i=0; i<num.length(); i++) { no = no*10 + (toInt(num[i])); if (i != 0) calculatedUpto = calculatedUpto*10 + 9; } remaining = no-calculatedUpto; // Final answer is calculated // It is calculated by subtracting 9....9 (d-1) times // from no. int ans = zeroUpto(k-1) + (remaining-non_zero-1); return ans;} // Driver program to test the above functionsint main(){ string num = "107"; cout << "Count of numbers from 1" << " to " << num << " is " << countZero(num) << endl; num = "1264"; cout << "Count of numbers from 1" << " to " << num << " is " <<countZero(num) << endl; return 0;} //Modified Java program to count number from 1 to n with// 0 as a digit. public class GFG { // Returns count of integers having zero upto given digitsstatic int zeroUpto(int digits){ // Refer below article for details // https://www.geeksforgeeks.org/count-positive-integers-0-digit/ int first = (int) ((Math.pow(10,digits)-1)/9); int second = (int) ((Math.pow(9,digits)-1)/8); return 9 * (first - second);} // utility function to convert character representation// to integerstatic int toInt(char c){ return (int)(c)-48;} // counts numbers having zero as digits upto a given// number 'num'static int countZero(String num){ // k denoted the number of digits in the number int k = num.length(); // Calculating the total number having zeros, // which upto k-1 digits int total = zeroUpto(k-1); // Now let us calculate the numbers which don't have // any zeros. In that k digits upto the given number int non_zero = 0; for (int i=0; i<num.length(); i++) { // If the number itself contains a zero then // decrement the counter if (num.charAt(i) == '0') { non_zero--; break; } // Adding the number of non zero numbers that // can be formed non_zero += (toInt(num.charAt(i))-1) * (Math.pow(9,k-1-i)); } int no = 0, remaining = 0,calculatedUpto=0; // Calculate the number and the remaining after // ignoring the most significant digit for (int i=0; i<num.length(); i++) { no = no*10 + (toInt(num.charAt(i))); if (i != 0) calculatedUpto = calculatedUpto*10 + 9; } remaining = no-calculatedUpto; // Final answer is calculated // It is calculated by subtracting 9....9 (d-1) times // from no. int ans = zeroUpto(k-1) + (remaining-non_zero-1); return ans;} // Driver program to test the above functions static public void main(String[] args) { String num = "107"; System.out.println("Count of numbers from 1" + " to " + num + " is " + countZero(num)); num = "1264"; System.out.println("Count of numbers from 1" + " to " + num + " is " +countZero(num)); }} // This code is contributed by 29AjayKumar # Python3 program to count number from 1 to n# with 0 as a digit. # Returns count of integers having zero# upto given digitsdef zeroUpto(digits): first = int((pow(10, digits) - 1) / 9); second = int((pow(9, digits) - 1) / 8); return 9 * (first - second); # counts numbers having zero as digits# upto a given number 'num'def countZero(num): # k denoted the number of digits # in the number k = len(num); # Calculating the total number having # zeros, which upto k-1 digits total = zeroUpto(k - 1); # Now let us calculate the numbers which # don't have any zeros. In that k digits # upto the given number non_zero = 0; for i in range(len(num)): # If the number itself contains a zero # then decrement the counter if (num[i] == '0'): non_zero -= 1; break; # Adding the number of non zero numbers # that can be formed non_zero += (((ord(num[i]) - ord('0')) - 1) * (pow(9, k - 1 - i))); no = 0; remaining = 0; calculatedUpto = 0; # Calculate the number and the remaining # after ignoring the most significant digit for i in range(len(num)): no = no * 10 + (ord(num[i]) - ord('0')); if (i != 0): calculatedUpto = calculatedUpto * 10 + 9; remaining = no - calculatedUpto; # Final answer is calculated. It is calculated # by subtracting 9....9 (d-1) times from no. ans = zeroUpto(k - 1) + (remaining - non_zero - 1); return ans; # Driver Codenum = "107";print("Count of numbers from 1 to", num, "is", countZero(num)); num = "1264";print("Count of numbers from 1 to", num, "is", countZero(num)); # This code is contributed by mits // Modified C# program to count number from 1 to n with// 0 as a digit. using System;public class GFG{ // Returns count of integers having zero upto given digitsstatic int zeroUpto(int digits){ // Refer below article for details // https://www.geeksforgeeks.org/count-positive-integers-0-digit/ int first = (int) ((Math.Pow(10,digits)-1)/9); int second = (int) ((Math.Pow(9,digits)-1)/8); return 9 * (first - second);} // utility function to convert character representation// to integerstatic int toInt(char c){ return (int)(c)-48;} // counts numbers having zero as digits upto a given// number 'num'static int countZero(String num){ // k denoted the number of digits in the number int k = num.Length; // Calculating the total number having zeros, // which upto k-1 digits int total = zeroUpto(k-1); // Now let us calculate the numbers which don't have // any zeros. In that k digits upto the given number int non_zero = 0; for (int i=0; i<num.Length; i++) { // If the number itself contains a zero then // decrement the counter if (num[i] == '0') { non_zero--; break; } // Adding the number of non zero numbers that // can be formed non_zero += (toInt(num[i])-1) * (int)(Math.Pow(9,k-1-i)); } int no = 0, remaining = 0,calculatedUpto=0; // Calculate the number and the remaining after // ignoring the most significant digit for (int i=0; i<num.Length; i++) { no = no*10 + (toInt(num[i])); if (i != 0) calculatedUpto = calculatedUpto*10 + 9; } remaining = no-calculatedUpto; // Final answer is calculated // It is calculated by subtracting 9....9 (d-1) times // from no. int ans = zeroUpto(k-1) + (remaining-non_zero-1); return ans;} // Driver program to test the above functions static public void Main() { String num = "107"; Console.WriteLine("Count of numbers from 1" + " to " + num + " is " + countZero(num)); num = "1264"; Console.WriteLine("Count of numbers from 1" + " to " + num + " is " +countZero(num)); }} // This code is contributed by 29AjayKumar <?php// PHP program to count// number from 1 to n// with 0 as a digit. // Returns count of integers// having zero upto given digitsfunction zeroUpto($digits){ $first = (int)((pow(10, $digits) - 1) / 9); $second = (int)((pow(9, $digits) - 1) / 8); return 9 * ($first - $second);} // counts numbers having// zero as digits upto a// given number 'num'function countZero($num){ // k denoted the number // of digits in the number $k = strlen($num); // Calculating the total // number having zeros, // which upto k-1 digits $total = zeroUpto($k-1); // Now let us calculate // the numbers which don't // have any zeros. In that // k digits upto the given // number $non_zero = 0; for ($i = 0; $i < strlen($num); $i++) { // If the number itself // contains a zero then // decrement the counter if ($num[$i] == '0') { $non_zero--; break; } // Adding the number of // non zero numbers that // can be formed $non_zero += (($num[$i] - '0') - 1) * (pow(9, $k - 1 - $i)); } $no = 0; $remaining = 0; $calculatedUpto = 0; // Calculate the number // and the remaining after // ignoring the most // significant digit for ($i = 0; $i < strlen($num); $i++) { $no = $no * 10 + ($num[$i] - '0'); if ($i != 0) $calculatedUpto = $calculatedUpto * 10 + 9; } $remaining = $no - $calculatedUpto; // Final answer is calculated // It is calculated by subtracting // 9....9 (d-1) times from no. $ans = zeroUpto($k - 1) + ($remaining - $non_zero - 1); return $ans;} // Driver Code$num = "107";echo "Count of numbers from 1 to " . $num . " is " . countZero($num) . "\n"; $num = "1264";echo "Count of numbers from 1 to " . $num . " is " . countZero($num); // This code is contributed// by mits?> <script> // Modified javascript program to count number from 1 to n with// 0 as a digit. // Returns count of integers having zero upto given digitsfunction zeroUpto(digits){ // Refer below article for details // https://www.geeksforgeeks.org/count-positive-integers-0-digit/ var first = parseInt( ((Math.pow(10,digits)-1)/9)); var second = parseInt( ((Math.pow(9,digits)-1)/8)); return 9 * (first - second);} // utility function to convert character representation// to integerfunction toInt(c){ return parseInt((c.charCodeAt(0))-48);} // counts numbers having zero as digits upto a given// number 'num'function countZero(num){ // k denoted the number of digits in the number var k = num.length; // Calculating the total number having zeros, // which upto k-1 digits var total = zeroUpto(k-1); // Now let us calculate the numbers which don't have // any zeros. In that k digits upto the given number var non_zero = 0; for (i=0; i<num.length; i++) { // If the number itself contains a zero then // decrement the counter if (num.charAt(i) == '0') { non_zero--; break; } // Adding the number of non zero numbers that // can be formed non_zero += (toInt(num.charAt(i))-1) * (Math.pow(9,k-1-i)); } var no = 0, remaining = 0,calculatedUpto=0; // Calculate the number and the remaining after // ignoring the most significant digit for (i=0; i<num.length; i++) { no = no*10 + (toInt(num.charAt(i))); if (i != 0) calculatedUpto = calculatedUpto*10 + 9; } remaining = no-calculatedUpto; // Final answer is calculated // It is calculated by subtracting 9....9 (d-1) times // from no. var ans = zeroUpto(k-1) + (remaining-non_zero-1); return ans;} // Driver program to test the above functionsvar num = "107";document.write("Count of numbers from 1" + " to " + num + " is " + countZero(num)); var num = "1264";document.write("<br>Count of numbers from 1" + " to " + num + " is " +countZero(num)); // This code is contributed by shikhasingrajput</script> Output: Count of numbers from 1 to 107 is 17 Count of numbers from 1 to 1264 is 315 Complexity Analysis:Time Complexity : O(d), where d is no. of digits i.e., O(log(n) Auxiliary Space : O(1) This article is contributed by Ashutosh Kumar. If you like GeeksforGeeks and would like to contribute, you can also write an article and mail your article to contribute@geeksforgeeks.org. 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 Mithun Kumar 29AjayKumar shikhasingrajput C++ Mathematical Mathematical CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n19 Apr, 2021" }, { "code": null, "e": 133, "s": 54, "text": "Problem: Count how many integers from 1 to N contains 0 as a digit.Examples: " }, { "code": null, "e": 328, "s": 133, "text": "Input: n = 9\nOutput: 0\n\nInput: n = 107\nOutput: 17\nThe numbers having 0 are 10, 20,..90, 100, 101..107\n\nInput: n = 155\nOutput: 24\nThe numbers having 0 are 10, 20,..90, 100, 101..110,\n120, ..150." }, { "code": null, "e": 570, "s": 328, "text": "A naive solution is discussed in previous postIn this post an optimized solution is discussed. Let’s analyze the problem closely.Let the given number has d digits .The required answer can be computed by computing the following two values: " }, { "code": null, "e": 725, "s": 570, "text": "Count of 0 digit integers having maximum of d-1 digits.Count of 0 digit integers having exactly d digits (less than/ equal to the given number of course!)" }, { "code": null, "e": 781, "s": 725, "text": "Count of 0 digit integers having maximum of d-1 digits." }, { "code": null, "e": 881, "s": 781, "text": "Count of 0 digit integers having exactly d digits (less than/ equal to the given number of course!)" }, { "code": null, "e": 1242, "s": 881, "text": "Therefore, the solution would be the sum of above two.The first part has already been discussed here.How to find the second part? We can find the total number of integers having d digits (less than equal to given number), which don’t contain any zero.To find this we traverse the number, one digit at a time.We find count of non-negative integers as follows: " }, { "code": null, "e": 1490, "s": 1242, "text": "If the number at that place is zero, decrement counter by 1 and break (because we can’t move any further, decrement to assure that the number itself contains a zero)else , multiply the (number-1), with power(9, number of digits to the right to it)" }, { "code": null, "e": 1656, "s": 1490, "text": "If the number at that place is zero, decrement counter by 1 and break (because we can’t move any further, decrement to assure that the number itself contains a zero)" }, { "code": null, "e": 1739, "s": 1656, "text": "else , multiply the (number-1), with power(9, number of digits to the right to it)" }, { "code": null, "e": 1775, "s": 1739, "text": "Let’s illustrate with an example. " }, { "code": null, "e": 1985, "s": 1775, "text": "Let the number be n = 123. non_zero = 0\nWe encounter 1 first, \n add (1-1)*92 to non_zero (= 0+0)\n\nWe encounter 2, \n add (2-1)*91 to non_zero (= 0+9 = 9)\n\nWe encounter 3, \n add (3-1)*90 to non_zero (=9+3 = 12)" }, { "code": null, "e": 2650, "s": 1985, "text": "We can observe that non_zero denotes the number of integer consisting of 3 digits (not greater than 123) and don’t contain any zero. i.e., (111, 112, ....., 119, 121, 122, 123) (It is recommended to verify it once)Now, one may ask what’s the point of calculating the count of numbers which don’t have any zeroes?Correct! we’re interested to find the count of integers which have zero.However, we can now easily find that by subtracting non_zero from n after ignoring the most significant place.i.e., In our previous example zero = 23 – non_zero = 23-12 =11 and finally we add the two parts to arrive at the required result!!Below is implementation of above idea. " }, { "code": null, "e": 2654, "s": 2650, "text": "C++" }, { "code": null, "e": 2659, "s": 2654, "text": "Java" }, { "code": null, "e": 2667, "s": 2659, "text": "Python3" }, { "code": null, "e": 2670, "s": 2667, "text": "C#" }, { "code": null, "e": 2674, "s": 2670, "text": "PHP" }, { "code": null, "e": 2685, "s": 2674, "text": "Javascript" }, { "code": "//Modified C++ program to count number from 1 to n with// 0 as a digit.#include <bits/stdc++.h>using namespace std; // Returns count of integers having zero upto given digitsint zeroUpto(int digits){ // Refer below article for details // https://www.geeksforgeeks.org/count-positive-integers-0-digit/ int first = (pow(10,digits)-1)/9; int second = (pow(9,digits)-1)/8; return 9 * (first - second);} // utility function to convert character representation// to integerint toInt(char c){ return int(c)-48;} // counts numbers having zero as digits upto a given// number 'num'int countZero(string num){ // k denoted the number of digits in the number int k = num.length(); // Calculating the total number having zeros, // which upto k-1 digits int total = zeroUpto(k-1); // Now let us calculate the numbers which don't have // any zeros. In that k digits upto the given number int non_zero = 0; for (int i=0; i<num.length(); i++) { // If the number itself contains a zero then // decrement the counter if (num[i] == '0') { non_zero--; break; } // Adding the number of non zero numbers that // can be formed non_zero += (toInt(num[i])-1) * (pow(9,k-1-i)); } int no = 0, remaining = 0,calculatedUpto=0; // Calculate the number and the remaining after // ignoring the most significant digit for (int i=0; i<num.length(); i++) { no = no*10 + (toInt(num[i])); if (i != 0) calculatedUpto = calculatedUpto*10 + 9; } remaining = no-calculatedUpto; // Final answer is calculated // It is calculated by subtracting 9....9 (d-1) times // from no. int ans = zeroUpto(k-1) + (remaining-non_zero-1); return ans;} // Driver program to test the above functionsint main(){ string num = \"107\"; cout << \"Count of numbers from 1\" << \" to \" << num << \" is \" << countZero(num) << endl; num = \"1264\"; cout << \"Count of numbers from 1\" << \" to \" << num << \" is \" <<countZero(num) << endl; return 0;}", "e": 4786, "s": 2685, "text": null }, { "code": "//Modified Java program to count number from 1 to n with// 0 as a digit. public class GFG { // Returns count of integers having zero upto given digitsstatic int zeroUpto(int digits){ // Refer below article for details // https://www.geeksforgeeks.org/count-positive-integers-0-digit/ int first = (int) ((Math.pow(10,digits)-1)/9); int second = (int) ((Math.pow(9,digits)-1)/8); return 9 * (first - second);} // utility function to convert character representation// to integerstatic int toInt(char c){ return (int)(c)-48;} // counts numbers having zero as digits upto a given// number 'num'static int countZero(String num){ // k denoted the number of digits in the number int k = num.length(); // Calculating the total number having zeros, // which upto k-1 digits int total = zeroUpto(k-1); // Now let us calculate the numbers which don't have // any zeros. In that k digits upto the given number int non_zero = 0; for (int i=0; i<num.length(); i++) { // If the number itself contains a zero then // decrement the counter if (num.charAt(i) == '0') { non_zero--; break; } // Adding the number of non zero numbers that // can be formed non_zero += (toInt(num.charAt(i))-1) * (Math.pow(9,k-1-i)); } int no = 0, remaining = 0,calculatedUpto=0; // Calculate the number and the remaining after // ignoring the most significant digit for (int i=0; i<num.length(); i++) { no = no*10 + (toInt(num.charAt(i))); if (i != 0) calculatedUpto = calculatedUpto*10 + 9; } remaining = no-calculatedUpto; // Final answer is calculated // It is calculated by subtracting 9....9 (d-1) times // from no. int ans = zeroUpto(k-1) + (remaining-non_zero-1); return ans;} // Driver program to test the above functions static public void main(String[] args) { String num = \"107\"; System.out.println(\"Count of numbers from 1\" + \" to \" + num + \" is \" + countZero(num)); num = \"1264\"; System.out.println(\"Count of numbers from 1\" + \" to \" + num + \" is \" +countZero(num)); }} // This code is contributed by 29AjayKumar", "e": 7021, "s": 4786, "text": null }, { "code": "# Python3 program to count number from 1 to n# with 0 as a digit. # Returns count of integers having zero# upto given digitsdef zeroUpto(digits): first = int((pow(10, digits) - 1) / 9); second = int((pow(9, digits) - 1) / 8); return 9 * (first - second); # counts numbers having zero as digits# upto a given number 'num'def countZero(num): # k denoted the number of digits # in the number k = len(num); # Calculating the total number having # zeros, which upto k-1 digits total = zeroUpto(k - 1); # Now let us calculate the numbers which # don't have any zeros. In that k digits # upto the given number non_zero = 0; for i in range(len(num)): # If the number itself contains a zero # then decrement the counter if (num[i] == '0'): non_zero -= 1; break; # Adding the number of non zero numbers # that can be formed non_zero += (((ord(num[i]) - ord('0')) - 1) * (pow(9, k - 1 - i))); no = 0; remaining = 0; calculatedUpto = 0; # Calculate the number and the remaining # after ignoring the most significant digit for i in range(len(num)): no = no * 10 + (ord(num[i]) - ord('0')); if (i != 0): calculatedUpto = calculatedUpto * 10 + 9; remaining = no - calculatedUpto; # Final answer is calculated. It is calculated # by subtracting 9....9 (d-1) times from no. ans = zeroUpto(k - 1) + (remaining - non_zero - 1); return ans; # Driver Codenum = \"107\";print(\"Count of numbers from 1 to\", num, \"is\", countZero(num)); num = \"1264\";print(\"Count of numbers from 1 to\", num, \"is\", countZero(num)); # This code is contributed by mits", "e": 8785, "s": 7021, "text": null }, { "code": "// Modified C# program to count number from 1 to n with// 0 as a digit. using System;public class GFG{ // Returns count of integers having zero upto given digitsstatic int zeroUpto(int digits){ // Refer below article for details // https://www.geeksforgeeks.org/count-positive-integers-0-digit/ int first = (int) ((Math.Pow(10,digits)-1)/9); int second = (int) ((Math.Pow(9,digits)-1)/8); return 9 * (first - second);} // utility function to convert character representation// to integerstatic int toInt(char c){ return (int)(c)-48;} // counts numbers having zero as digits upto a given// number 'num'static int countZero(String num){ // k denoted the number of digits in the number int k = num.Length; // Calculating the total number having zeros, // which upto k-1 digits int total = zeroUpto(k-1); // Now let us calculate the numbers which don't have // any zeros. In that k digits upto the given number int non_zero = 0; for (int i=0; i<num.Length; i++) { // If the number itself contains a zero then // decrement the counter if (num[i] == '0') { non_zero--; break; } // Adding the number of non zero numbers that // can be formed non_zero += (toInt(num[i])-1) * (int)(Math.Pow(9,k-1-i)); } int no = 0, remaining = 0,calculatedUpto=0; // Calculate the number and the remaining after // ignoring the most significant digit for (int i=0; i<num.Length; i++) { no = no*10 + (toInt(num[i])); if (i != 0) calculatedUpto = calculatedUpto*10 + 9; } remaining = no-calculatedUpto; // Final answer is calculated // It is calculated by subtracting 9....9 (d-1) times // from no. int ans = zeroUpto(k-1) + (remaining-non_zero-1); return ans;} // Driver program to test the above functions static public void Main() { String num = \"107\"; Console.WriteLine(\"Count of numbers from 1\" + \" to \" + num + \" is \" + countZero(num)); num = \"1264\"; Console.WriteLine(\"Count of numbers from 1\" + \" to \" + num + \" is \" +countZero(num)); }} // This code is contributed by 29AjayKumar", "e": 10982, "s": 8785, "text": null }, { "code": "<?php// PHP program to count// number from 1 to n// with 0 as a digit. // Returns count of integers// having zero upto given digitsfunction zeroUpto($digits){ $first = (int)((pow(10, $digits) - 1) / 9); $second = (int)((pow(9, $digits) - 1) / 8); return 9 * ($first - $second);} // counts numbers having// zero as digits upto a// given number 'num'function countZero($num){ // k denoted the number // of digits in the number $k = strlen($num); // Calculating the total // number having zeros, // which upto k-1 digits $total = zeroUpto($k-1); // Now let us calculate // the numbers which don't // have any zeros. In that // k digits upto the given // number $non_zero = 0; for ($i = 0; $i < strlen($num); $i++) { // If the number itself // contains a zero then // decrement the counter if ($num[$i] == '0') { $non_zero--; break; } // Adding the number of // non zero numbers that // can be formed $non_zero += (($num[$i] - '0') - 1) * (pow(9, $k - 1 - $i)); } $no = 0; $remaining = 0; $calculatedUpto = 0; // Calculate the number // and the remaining after // ignoring the most // significant digit for ($i = 0; $i < strlen($num); $i++) { $no = $no * 10 + ($num[$i] - '0'); if ($i != 0) $calculatedUpto = $calculatedUpto * 10 + 9; } $remaining = $no - $calculatedUpto; // Final answer is calculated // It is calculated by subtracting // 9....9 (d-1) times from no. $ans = zeroUpto($k - 1) + ($remaining - $non_zero - 1); return $ans;} // Driver Code$num = \"107\";echo \"Count of numbers from 1 to \" . $num . \" is \" . countZero($num) . \"\\n\"; $num = \"1264\";echo \"Count of numbers from 1 to \" . $num . \" is \" . countZero($num); // This code is contributed// by mits?>", "e": 13106, "s": 10982, "text": null }, { "code": "<script> // Modified javascript program to count number from 1 to n with// 0 as a digit. // Returns count of integers having zero upto given digitsfunction zeroUpto(digits){ // Refer below article for details // https://www.geeksforgeeks.org/count-positive-integers-0-digit/ var first = parseInt( ((Math.pow(10,digits)-1)/9)); var second = parseInt( ((Math.pow(9,digits)-1)/8)); return 9 * (first - second);} // utility function to convert character representation// to integerfunction toInt(c){ return parseInt((c.charCodeAt(0))-48);} // counts numbers having zero as digits upto a given// number 'num'function countZero(num){ // k denoted the number of digits in the number var k = num.length; // Calculating the total number having zeros, // which upto k-1 digits var total = zeroUpto(k-1); // Now let us calculate the numbers which don't have // any zeros. In that k digits upto the given number var non_zero = 0; for (i=0; i<num.length; i++) { // If the number itself contains a zero then // decrement the counter if (num.charAt(i) == '0') { non_zero--; break; } // Adding the number of non zero numbers that // can be formed non_zero += (toInt(num.charAt(i))-1) * (Math.pow(9,k-1-i)); } var no = 0, remaining = 0,calculatedUpto=0; // Calculate the number and the remaining after // ignoring the most significant digit for (i=0; i<num.length; i++) { no = no*10 + (toInt(num.charAt(i))); if (i != 0) calculatedUpto = calculatedUpto*10 + 9; } remaining = no-calculatedUpto; // Final answer is calculated // It is calculated by subtracting 9....9 (d-1) times // from no. var ans = zeroUpto(k-1) + (remaining-non_zero-1); return ans;} // Driver program to test the above functionsvar num = \"107\";document.write(\"Count of numbers from 1\" + \" to \" + num + \" is \" + countZero(num)); var num = \"1264\";document.write(\"<br>Count of numbers from 1\" + \" to \" + num + \" is \" +countZero(num)); // This code is contributed by shikhasingrajput</script>", "e": 15262, "s": 13106, "text": null }, { "code": null, "e": 15272, "s": 15262, "text": "Output: " }, { "code": null, "e": 15349, "s": 15272, "text": "Count of numbers from 1 to 107 is 17 \nCount of numbers from 1 to 1264 is 315" }, { "code": null, "e": 15457, "s": 15349, "text": "Complexity Analysis:Time Complexity : O(d), where d is no. of digits i.e., O(log(n) Auxiliary Space : O(1) " }, { "code": null, "e": 15725, "s": 15457, "text": "This article is contributed by Ashutosh Kumar. If you like GeeksforGeeks and would like to contribute, you can also write an article and mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks." }, { "code": null, "e": 15851, "s": 15727, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above" }, { "code": null, "e": 15866, "s": 15853, "text": "Mithun Kumar" }, { "code": null, "e": 15878, "s": 15866, "text": "29AjayKumar" }, { "code": null, "e": 15895, "s": 15878, "text": "shikhasingrajput" }, { "code": null, "e": 15899, "s": 15895, "text": "C++" }, { "code": null, "e": 15912, "s": 15899, "text": "Mathematical" }, { "code": null, "e": 15925, "s": 15912, "text": "Mathematical" }, { "code": null, "e": 15929, "s": 15925, "text": "CPP" } ]
Commonly asked DBMS interview questions
06 Jun, 2022 1. What are the advantages of DBMS over traditional file-based systems? Database management systems were developed to handle the following difficulties of typical File-processing systems supported by conventional operating systems. 1. Data redundancy and inconsistency 2. Difficulty in accessing data 3. Data isolation – multiple files and formats 4. Integrity problems 5. Atomicity of updates 6. Concurrent access by multiple users 7. Security problems 2. What are super, primary, candidate, and foreign keys? A super key is a set of attributes of a relation schema upon which all attributes of the schema are functionally dependent. No two rows can have the same value of super key attributes. A Candidate key is a minimal superkey, i.e., no proper subset of Candidate key attributes can be a superkey. A Primary Key is one of the candidate keys. One of the candidate keys is selected as most important and becomes the primary key. There cannot be more than one primary key in a table..A Foreign key is a field (or collection of fields) in one table that uniquely identifies a row of another table. 3. What is the difference between primary key and unique constraints? The primary key cannot have NULL value, the unique constraints can have NULL values. There is only one primary key in a table, but there can be multiple unique constrains. 4.What is database normalization? It is a process of analyzing the given relation schemas based on their functional dependencies and primary keys to achieve the following desirable properties: 1. Minimizing Redundancy 2. Minimizing the Insertion, Deletion, And Update Anomalies Relation schemas that do not meet the properties are decomposed into smaller relation schemas that could meet desirable properties. 5. Why is the use of DBMS recommended? Explain by listing some of its major advantages? Some of the major advantages of DBMS are as follows: Controlled Redundancy: DBMS supports a mechanism to control the redundancy of data inside the database by integrating all the data into a single database and as data is stored in only one place, the duplicity of data does not happen. Data Sharing: Sharing of data among multiple users simultaneously can also be done in DBMS as the same database will be shared among all the users and by different application programs. Backup and Recovery Facility: DBMS minimizes the pain of creating the backup of data again and again by providing a feature of ‘backup and recovery’ which automatically creates the data backup and restores the data whenever required. Enforcement of Integrity Constraints: Integrity Constraints are very important to be enforced on the data so that the refined data after putting some constraints are stored in the database and this is followed by DBMS. Independence of Data: It simply means that you can change the structure of the data without affecting the structure of any of the application programs. 6. What are the differences between DDL, DML, and DCL in SQL? Following are some details of three :DDL stands for Data Definition Language. SQL queries like CREATE, ALTER, DROP, TRUNCATE and RENAME come under this. DML stands for Data Manipulation Language. SQL queries like SELECT, INSERT, DELETE and UPDATE come under this. DCL stands for Data Control Language. SQL queries like GRANT and REVOKE come under this. 7. What is the difference between having and where clause? HAVING is used to specify a condition for a group or an aggregate function used in a select statement. The WHERE clause selects before grouping. The HAVING clause selects rows after grouping. Unlike the HAVING clause, the WHERE clause cannot contain aggregate functions. (See this for examples). See Having vs Where Clause? for more details 8.How to print duplicate rows in a table? See https://www.geeksforgeeks.org/how-to-print-duplicate-rows-in-a-table/ 9. What is Join? An SQL Join is used to combine data from two or more tables, based on a common field between them. For example, consider the following two tables. Table – Student Table Table – StudentCourse Table Following is a join query that shows the names of students enrolled in different courseIDs. SELECT StudentCourse.CourseID, Student.StudentName FROM StudentCourse INNER JOIN Student ON StudentCourse.EnrollNo = Student.EnrollNo ORDER BY StudentCourse.CourseID; The above query would produce the following result. 9. What is Identity? Identity (or AutoNumber) is a column that automatically generates numeric values. A start and increment value can be set, but most DBA leave these at 1. A GUID column also generates numbers; the value of this cannot be controlled. Identity/GUID columns do not need to be indexed. 10.What is a view in SQL? How to create a view? A view is a virtual table based on the result-set of an SQL statement. We can create it using create view syntax. CREATE VIEW view_name AS SELECT column_name(s) FROM table_name WHERE condition 11.What are the uses of view? 1. Views can represent a subset of the data contained in a table; consequently, a view can limit the degree of exposure of the underlying tables to the outer world: a given user may have permission to query the view, while denied access to the rest of the base table. 2. Views can join and simplify multiple tables into a single virtual table.3. Views can act as aggregated tables, where the database engine aggregates data (sum, average, etc.) and presents the calculated results as part of the data.4. Views can hide the complexity of data.5. Views take very little space to store; the database contains only the definition of a view, not a copy of all the data which it presents. 6. Depending on the SQL engine used, views can provide extra security. 12. What is a Trigger? A Trigger is a code associated with insert, update or delete operations. The code is executed automatically whenever the associated query is executed on a table. Triggers can be useful to maintain integrity in the database. 13. What is a stored procedure? A stored procedure is like a function that contains a set of operations compiled together. It contains a set of operations that are commonly used in an application to do some common database tasks. 14. What is the difference between Trigger and Stored Procedure? Unlike Stored Procedures, Triggers cannot be called directly. They can only be associated with queries. 15. What is a transaction? What are ACID properties? A Database Transaction is a set of database operations that must be treated as a whole, which means either all operations are executed or none of them. An example can be a bank transaction from one account to another account. Either both debit and credit operations must be executed or none of them. ACID (Atomicity, Consistency, Isolation, Durability) is a set of properties that guarantee that database transactions are processed reliably. 16. What are indexes? A database index is a data structure that improves the speed of data retrieval operations on a database table at the cost of additional writes and the use of more storage space to maintain the extra copy of data. Data can be stored only in one order on a disk. To support faster access according to different values, faster search like binary search for different values is desired, For this purpose, indexes are created on tables. These indexes need extra space on the disk, but they allow faster search according to different frequently searched values. 17. What are clustered and non-clustered Indexes? Clustered indexes are the index according to which data is physically stored on a disk. Therefore, only one clustered index can be created on a given database table. Non-clustered indexes don’t define the physical ordering of data, but logical ordering. Typically, a tree is created whose leaf point to disk records. B-Tree or B+ tree are used for this purpose. 18. What is Denormalization? Denormalization is a database optimization technique in which we add redundant data to one or more tables. 19. What is CLAUSE in SQL? A clause in SQL is a part of a query that lets you filter or customize how you want your data to be queried to you. 20. What is a Live Lock? Livelock situation can be defined as when two or more processes continually repeat the same interaction in response to changes in the other processes without doing any useful work These processes are not in the waiting state, and they are running concurrently. This is different from a deadlock because in a deadlock all processes are in the waiting state. 21. What is QBE? Query-by-example represents a visual/graphical approach for accessing information in a database through the use of query templates called skeleton tables. It is used by entering example values directly into a query template to represent what is to be achieved. QBE is used by many database systems for personal computers. QBE is a very powerful facility that gives the user the capability to access the information a user wants without the knowledge of any programming language. Queries in QBE are expressed by skeleton tables. QBE has two distinct features: QBE has the two-dimensional syntax: Queries look like tables. 22. Why are cursors necessary in embedded SQL? A cursor is an object used to store the output of a query for row-by-row processing by the application programs. SQL statements operate on a set of data and return a set of data. On other hand, host language programs operate on a row at a time. The cursors are used to navigate through a set of rows returned by an embedded SQL SELECT statement. A cursor can be compared to a pointer. 23. What is the purpose of normalization in DBMS? Database normalization is the process of organizing the attributes of the database to reduce or eliminate data redundancy (having the same data but at different places). Purpose of normalization: It is used to remove duplicate data and database anomalies from the relational table. Normalization helps to reduce redundancy and complexity by examining new data types used in the table. It is helpful to divide the large database table into smaller tables and link them using relationships. It avoids duplicate data or no repeating groups into a table. It reduces the chances for anomalies to occur in a database. 24. What is the difference between a database schema and a database state? The collection of information stored in a database at a particular moment in time is called database state while the overall design of the database is called the database schema. 25. What is the purpose of SQL? SQL stands for Structured Query Language whose main purpose is to interact with the relational databases in the form of inserting, deleting and updating/modifying the data in the database. 26. Explain the concepts of a Primary key and Foreign Key. Primary Key is used to uniquely identify the records in a database table while Foreign Key is mainly used to link two or more tables together, as this is a particular field(s) in one of the database tables which are the primary key of some other table. Example: There are 2 tables – Employee and Department. Both have one common field/column as ‘ID’ where ID is the primary key of the Employee table while this is the foreign key for the Department table. 27.What are the main differences between Primary key and Unique Key? Given below are few differences: The main difference between the Primary key and the Unique key is that the Primary key can never have a null value while the Unique key may consist of a null value. In each table, there can be only one primary key while there can be more than one unique key in a table. 28. What is the concept of sub-query in terms of SQL? Sub-query is basically the query that is included inside some other query and can also be called an inner query which is found inside the outer query. 29. What is the use of the DROP command and what are the differences between DROP, TRUNCATE and DELETE commands? DROP command is a DDL command which is used to drop/delete the existing table, database, index, or view from the database. The major difference between DROP, TRUNCATE and DELETE commands are: DROP and TRUNCATE commands are the DDL commands which are used to delete tables from the database and once the table gets deleted, all the privileges and indexes that are related to the table also get deleted. These 2 operations cannot be rolled back and so should be used only when necessary. DELETE command, on the other hand, is a DML Command which is used to delete rows from the table and this can be rolled back. 30. What is the main difference between UNION and UNION ALL? UNION and UNION ALL are used to join the data from 2 or more tables but UNION removes duplicate rows and picks the rows which are distinct after combining the data from the tables whereas UNION ALL does not remove the duplicate rows, it just picks all the data from the tables. 31. What is Correlated Subquery in DBMS? A Subquery is also known as a nested query i.e. a query written inside some query. When a Subquery is executed for each of the rows of the outer query then it is termed as a Correlated Subquery. An example of Non-Correlated Subquery is: Here, the inner query is not executed for each of the rows of the outer query. 32. Explain Entity, Entity Type, and Entity Set in DBMS? The entity is an object, place, or thing which has its independent existence in the real world and about which data can be stored in a database. For Example, any person, book, etc. Entity Type is a collection of entities that have the same attributes. For Example, the STUDENT table contains rows in which each row is an entity holding the attributes like name, age, and id of the students, hence STUDENT is an Entity Type that holds the entities having the same attributes. Entity Set is a collection of entities of the same type. For Example, A collection of the employees of a firm. 33. What are the different levels of abstraction in the DBMS? There are 3 levels of data abstraction in the DBMS. They include: Physical Level: This is the lowest level of the data abstraction which states how the data is stored in the database. Logical Level: This is the next level of the data abstraction which states the type of the data and the relationship among the data that is stored in the database. View Level: This is the highest level in the data abstraction which shows/states only a part of the database. 34 . What integrity rules exist in the DBMS? There are two major integrity rules that exist in the DBMS. Entity Integrity: This states a very important rule that the value of a Primary key can never have a NULL value. Referential Integrity: This rule is related to the Foreign key which states that either the value of a Foreign key is a NULL value or it should be the primary key of any other relation. 35. What is E-R model in the DBMS? E-R model is known as an Entity-Relationship model in the DBMS which is based on the concept of the Entities and the relationship that exists among these entities. 36. What is a functional dependency in the DBMS? This is basically a constraint that is useful in describing the relationship among the different attributes in a relation. Example: If there is some relation ‘R1’ which has 2 attributes as Y and Z then the functional dependency among these 2 attributes can be shown as Y->Z which states that Z is functionally dependent on Y. 37. What is 1NF in the DBMS? 1NF is known as the First Normal Form. This is the easiest form of the normalization process which states that the domain of an attribute should have only atomic values. The objective of this is to remove the duplicate columns that are present in the table. 38. What is 2NF in the DBMS? 2NF is the Second Normal Form. Any table is said to have in the 2NF if it satisfies the following 2 conditions: A table is in the 1NF. Each non-prime attribute of a table is said to be functionally dependent in totality on the primary key. 39. What is 3NF in the DBMS? 3NF is the Third Normal Form. Any table is said to have in the 3NF if it satisfies the following 2 conditions: A table is in the 2NF. Each non-prime attribute of a table is said to be non-transitively dependent on every key of the table. 40. What is BCNF in the DBMS? BCNF is the Boyce Codd Normal Form which is stricter than the 3NF. Any table is said to have in the BCNF if it satisfies the following 2 conditions: A table is in the 3NF. For each of the functional dependencies X->Y that exists, X is the super key of a table. 41. What is a CLAUSE in terms of SQL? This is used with the SQL queries to fetch specific data as per the requirements on the basis of the conditions that are put in the SQL. This is very helpful in picking the selective records from the complete set of records. For Example, There is a query that has a WHERE condition or the query with the HAVING clause. 42.How can you get the alternate records from the table in the SQL? If you want to fetch the odd numbers then the following query can be used: If you want to fetch the even numbers, then the following query can be used: 43. How is the pattern matching done in the SQL? Answer: With the help of the LIKE operator, pattern matching is possible in the SQL.’%’ is used with the LIKE operator when it matches with the 0 or more characters, and ‘_’ is used to match the one particular character. Example: 44. What is a join in the SQL? A Join is one of the SQL statements which is used to join the data or the rows from 2 or more tables on the basis of a common field/column among them. 45. What are the different types of joins in SQL? There are 4 types of SQL Joins: Inner Join: This type of join is used to fetch the data among the tables which are common in both tables. Left Join: This returns all the rows from the table which is on the left side of the join but only the matching rows from the table which is on the right side of the join. Right Join: This returns all the rows from the table which is on the right side of the join but only the matching rows from the table which is on the left side of the join. Full Join: This returns the rows from all the tables on which the join condition has been put and the rows which do not match hold null values. 46. Explain the Stored Procedure. A Stored Procedure is a group of SQL statements in the form of a function that has some unique name and is stored in relational database management systems(RDBMS) and can be accessed whenever required. 47. What is RDBMS? RDBMS is the Relational Database Management System which contains data in the form of the tables and data is accessed on the basis of the common fields among the tables. 48. What are the different types of relationships in the DBMS? A Relationship in DBMS depicts an association between the tables. Different types of relationships are: One-to-One: This basically states that there should be a one-to-one relationship between the tables i.e. there should be one record in both the tables. One-to-Many: This states that there can be many relationships for one i.e. a primary key table hold only one record which can have many, one, or none records in the related table. Many-to-Many: This states that both the tables can be related to many other tables. 49. What do you mean by Entity type extension? Compilation of similar entity types into one particular type which is grouped together as an entity set is known as entity type extension. 50. What is conceptual design in dbms? Conceptual design is the first stage in the database design process. The goal at this stage is to design a database that is independent of database software and physical details. The output of this process is a conceptual data model that describes the main data entities, attributes, relationships, and constraints of a given problem domain. 51. Differentiate between logical database design and physical database design. Show how this separation leads to data independence. Maps or transforms the conceptual schema (or an ER schema) from the high-level data model into a relational database schema. The specifications for the stored database in terms of physical storage structures, record placement, and indexes are designed. The mapping can proceed in two stages: System-independent mapping but data model-dependent Tailoring the schemas to a specific DBMS The following criteria are often used to guide the choice of physical database design options: Response Time Space Utilization Transaction Throughput DDL statements in the language of the chosen DBMS that specify the conceptual and external level schemas of the database system. But if the DDL statements include some physical design parameters, a complete DDL specification must wait until after the physical database design phase is completed. An initial determination of storage structures and the access paths for the database files. This corresponds to defining the internal schema in terms of Data Storage Definition Language. The database design is divided into several phases. The logical database design and physical database design are two of them. This separation is generally based on the concept of the three-level architecture of DBMS, which provides data independence. Therefore, we can say that this separation leads to data independence because the output of the logical database design is the conceptual and external level schemas of the database system which is independent of the output of the physical database design that is an internal schema. 52. What are temporary tables? When are they useful? Temporary tables exist solely for a particular session, or whose data persists for the duration of the transaction. The temporary tables are generally used to support specialized rollups or specific application processing requirements. Unlike a permanent table, space is not allocated to a temporary table when it is created. Space will be dynamically allocated for the table as rows are inserted. The CREATE GLOBAL TEMPORARY TABLE command is used to create a temporary table in Oracle. 53. Explain different types of failures that occur in the Oracle database.Types of Failures – In the Oracle database following types of failures can occur: Statement Failure· Bad data typeInsufficient space Insufficient space Insufficient Privileges (e.g., object privileges to a role) User Process FailureThe user performed an abnormal disconnectThe user’s session was abnormally terminatedThe user’s program raised an address exception The user performed an abnormal disconnect The user’s session was abnormally terminated The user’s program raised an address exception User ErrorThe user drops a tableUser damages data by modification The user drops a table User damages data by modification Instance Failure Media FailureThe user drops a tableUser damages data by modification The user drops a table User damages data by modification Alert LogsRecords informational and error messagesAll Instance startups and shutdowns are recorded in the log Records informational and error messages All Instance startups and shutdowns are recorded in the log 54. What is the main goal of RAID technology? RAID stands for Redundant Array of Inexpensive (or sometimes “Independent”)Disks. RAID is a method of combining several hard disk drives into one logical unit (two or more disks grouped together to appear as a single device to the host system). RAID technology was developed to address the fault-tolerance and performance limitations of conventional disk storage. It can offer fault tolerance and higher throughput levels than a single hard drive or group of independent hard drives. While arrays were once considered complex and relatively specialized storage solutions, today they are easy to use and essential for a broad spectrum of client/server applications. AnupamJain piyushav94 surajv varshachoudhary user_18tl DBMS DBMS Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. CTE in SQL Difference between Clustered and Non-clustered index Data Preprocessing in Data Mining Difference between DELETE, DROP and TRUNCATE Difference between SQL and NoSQL Indexing in Databases | Set 1 Structured Query Language (SQL) Difference between DDL and DML in DBMS Types of Functional dependencies in DBMS Difference between DELETE and TRUNCATE
[ { "code": null, "e": 52, "s": 24, "text": "\n06 Jun, 2022" }, { "code": null, "e": 125, "s": 52, "text": "1. What are the advantages of DBMS over traditional file-based systems? " }, { "code": null, "e": 509, "s": 125, "text": "Database management systems were developed to handle the following difficulties of typical File-processing systems supported by conventional operating systems. 1. Data redundancy and inconsistency 2. Difficulty in accessing data 3. Data isolation – multiple files and formats 4. Integrity problems 5. Atomicity of updates 6. Concurrent access by multiple users 7. Security problems " }, { "code": null, "e": 1157, "s": 509, "text": "2. What are super, primary, candidate, and foreign keys? A super key is a set of attributes of a relation schema upon which all attributes of the schema are functionally dependent. No two rows can have the same value of super key attributes. A Candidate key is a minimal superkey, i.e., no proper subset of Candidate key attributes can be a superkey. A Primary Key is one of the candidate keys. One of the candidate keys is selected as most important and becomes the primary key. There cannot be more than one primary key in a table..A Foreign key is a field (or collection of fields) in one table that uniquely identifies a row of another table. " }, { "code": null, "e": 1400, "s": 1157, "text": "3. What is the difference between primary key and unique constraints? The primary key cannot have NULL value, the unique constraints can have NULL values. There is only one primary key in a table, but there can be multiple unique constrains. " }, { "code": null, "e": 1811, "s": 1400, "text": "4.What is database normalization? It is a process of analyzing the given relation schemas based on their functional dependencies and primary keys to achieve the following desirable properties: 1. Minimizing Redundancy 2. Minimizing the Insertion, Deletion, And Update Anomalies Relation schemas that do not meet the properties are decomposed into smaller relation schemas that could meet desirable properties. " }, { "code": null, "e": 1899, "s": 1811, "text": "5. Why is the use of DBMS recommended? Explain by listing some of its major advantages?" }, { "code": null, "e": 1952, "s": 1899, "text": "Some of the major advantages of DBMS are as follows:" }, { "code": null, "e": 2186, "s": 1952, "text": "Controlled Redundancy: DBMS supports a mechanism to control the redundancy of data inside the database by integrating all the data into a single database and as data is stored in only one place, the duplicity of data does not happen." }, { "code": null, "e": 2372, "s": 2186, "text": "Data Sharing: Sharing of data among multiple users simultaneously can also be done in DBMS as the same database will be shared among all the users and by different application programs." }, { "code": null, "e": 2606, "s": 2372, "text": "Backup and Recovery Facility: DBMS minimizes the pain of creating the backup of data again and again by providing a feature of ‘backup and recovery’ which automatically creates the data backup and restores the data whenever required." }, { "code": null, "e": 2825, "s": 2606, "text": "Enforcement of Integrity Constraints: Integrity Constraints are very important to be enforced on the data so that the refined data after putting some constraints are stored in the database and this is followed by DBMS." }, { "code": null, "e": 2978, "s": 2825, "text": "Independence of Data: It simply means that you can change the structure of the data without affecting the structure of any of the application programs. " }, { "code": null, "e": 3394, "s": 2978, "text": "6. What are the differences between DDL, DML, and DCL in SQL? Following are some details of three :DDL stands for Data Definition Language. SQL queries like CREATE, ALTER, DROP, TRUNCATE and RENAME come under this. DML stands for Data Manipulation Language. SQL queries like SELECT, INSERT, DELETE and UPDATE come under this. DCL stands for Data Control Language. SQL queries like GRANT and REVOKE come under this. " }, { "code": null, "e": 3795, "s": 3394, "text": "7. What is the difference between having and where clause? HAVING is used to specify a condition for a group or an aggregate function used in a select statement. The WHERE clause selects before grouping. The HAVING clause selects rows after grouping. Unlike the HAVING clause, the WHERE clause cannot contain aggregate functions. (See this for examples). See Having vs Where Clause? for more details " }, { "code": null, "e": 3912, "s": 3795, "text": "8.How to print duplicate rows in a table? See https://www.geeksforgeeks.org/how-to-print-duplicate-rows-in-a-table/ " }, { "code": null, "e": 4077, "s": 3912, "text": "9. What is Join? An SQL Join is used to combine data from two or more tables, based on a common field between them. For example, consider the following two tables. " }, { "code": null, "e": 4101, "s": 4077, "text": "Table – Student Table " }, { "code": null, "e": 4131, "s": 4101, "text": "Table – StudentCourse Table " }, { "code": null, "e": 4225, "s": 4131, "text": "Following is a join query that shows the names of students enrolled in different courseIDs. " }, { "code": null, "e": 4421, "s": 4225, "text": "SELECT StudentCourse.CourseID, Student.StudentName\n FROM StudentCourse\n INNER JOIN Student \n ON StudentCourse.EnrollNo = Student.EnrollNo\n ORDER BY StudentCourse.CourseID;" }, { "code": null, "e": 4475, "s": 4421, "text": "The above query would produce the following result. " }, { "code": null, "e": 4777, "s": 4475, "text": "9. What is Identity? Identity (or AutoNumber) is a column that automatically generates numeric values. A start and increment value can be set, but most DBA leave these at 1. A GUID column also generates numbers; the value of this cannot be controlled. Identity/GUID columns do not need to be indexed. " }, { "code": null, "e": 4941, "s": 4777, "text": "10.What is a view in SQL? How to create a view? A view is a virtual table based on the result-set of an SQL statement. We can create it using create view syntax. " }, { "code": null, "e": 5020, "s": 4941, "text": "CREATE VIEW view_name AS\nSELECT column_name(s)\nFROM table_name\nWHERE condition" }, { "code": null, "e": 5804, "s": 5020, "text": "11.What are the uses of view? 1. Views can represent a subset of the data contained in a table; consequently, a view can limit the degree of exposure of the underlying tables to the outer world: a given user may have permission to query the view, while denied access to the rest of the base table. 2. Views can join and simplify multiple tables into a single virtual table.3. Views can act as aggregated tables, where the database engine aggregates data (sum, average, etc.) and presents the calculated results as part of the data.4. Views can hide the complexity of data.5. Views take very little space to store; the database contains only the definition of a view, not a copy of all the data which it presents. 6. Depending on the SQL engine used, views can provide extra security." }, { "code": null, "e": 6052, "s": 5804, "text": "12. What is a Trigger? A Trigger is a code associated with insert, update or delete operations. The code is executed automatically whenever the associated query is executed on a table. Triggers can be useful to maintain integrity in the database. " }, { "code": null, "e": 6283, "s": 6052, "text": "13. What is a stored procedure? A stored procedure is like a function that contains a set of operations compiled together. It contains a set of operations that are commonly used in an application to do some common database tasks. " }, { "code": null, "e": 6454, "s": 6283, "text": "14. What is the difference between Trigger and Stored Procedure? Unlike Stored Procedures, Triggers cannot be called directly. They can only be associated with queries. " }, { "code": null, "e": 6950, "s": 6454, "text": "15. What is a transaction? What are ACID properties? A Database Transaction is a set of database operations that must be treated as a whole, which means either all operations are executed or none of them. An example can be a bank transaction from one account to another account. Either both debit and credit operations must be executed or none of them. ACID (Atomicity, Consistency, Isolation, Durability) is a set of properties that guarantee that database transactions are processed reliably. " }, { "code": null, "e": 7529, "s": 6950, "text": "16. What are indexes? A database index is a data structure that improves the speed of data retrieval operations on a database table at the cost of additional writes and the use of more storage space to maintain the extra copy of data. Data can be stored only in one order on a disk. To support faster access according to different values, faster search like binary search for different values is desired, For this purpose, indexes are created on tables. These indexes need extra space on the disk, but they allow faster search according to different frequently searched values. " }, { "code": null, "e": 7942, "s": 7529, "text": "17. What are clustered and non-clustered Indexes? Clustered indexes are the index according to which data is physically stored on a disk. Therefore, only one clustered index can be created on a given database table. Non-clustered indexes don’t define the physical ordering of data, but logical ordering. Typically, a tree is created whose leaf point to disk records. B-Tree or B+ tree are used for this purpose. " }, { "code": null, "e": 7971, "s": 7942, "text": "18. What is Denormalization?" }, { "code": null, "e": 8078, "s": 7971, "text": "Denormalization is a database optimization technique in which we add redundant data to one or more tables." }, { "code": null, "e": 8105, "s": 8078, "text": "19. What is CLAUSE in SQL?" }, { "code": null, "e": 8221, "s": 8105, "text": "A clause in SQL is a part of a query that lets you filter or customize how you want your data to be queried to you." }, { "code": null, "e": 8246, "s": 8221, "text": "20. What is a Live Lock?" }, { "code": null, "e": 8603, "s": 8246, "text": "Livelock situation can be defined as when two or more processes continually repeat the same interaction in response to changes in the other processes without doing any useful work These processes are not in the waiting state, and they are running concurrently. This is different from a deadlock because in a deadlock all processes are in the waiting state." }, { "code": null, "e": 8621, "s": 8603, "text": "21. What is QBE? " }, { "code": null, "e": 9180, "s": 8621, "text": "Query-by-example represents a visual/graphical approach for accessing information in a database through the use of query templates called skeleton tables. It is used by entering example values directly into a query template to represent what is to be achieved. QBE is used by many database systems for personal computers. QBE is a very powerful facility that gives the user the capability to access the information a user wants without the knowledge of any programming language. Queries in QBE are expressed by skeleton tables. QBE has two distinct features:" }, { "code": null, "e": 9242, "s": 9180, "text": "QBE has the two-dimensional syntax: Queries look like tables." }, { "code": null, "e": 9290, "s": 9242, "text": "22. Why are cursors necessary in embedded SQL? " }, { "code": null, "e": 9675, "s": 9290, "text": "A cursor is an object used to store the output of a query for row-by-row processing by the application programs. SQL statements operate on a set of data and return a set of data. On other hand, host language programs operate on a row at a time. The cursors are used to navigate through a set of rows returned by an embedded SQL SELECT statement. A cursor can be compared to a pointer." }, { "code": null, "e": 9725, "s": 9675, "text": "23. What is the purpose of normalization in DBMS?" }, { "code": null, "e": 9895, "s": 9725, "text": "Database normalization is the process of organizing the attributes of the database to reduce or eliminate data redundancy (having the same data but at different places)." }, { "code": null, "e": 9921, "s": 9895, "text": "Purpose of normalization:" }, { "code": null, "e": 10007, "s": 9921, "text": "It is used to remove duplicate data and database anomalies from the relational table." }, { "code": null, "e": 10110, "s": 10007, "text": "Normalization helps to reduce redundancy and complexity by examining new data types used in the table." }, { "code": null, "e": 10214, "s": 10110, "text": "It is helpful to divide the large database table into smaller tables and link them using relationships." }, { "code": null, "e": 10276, "s": 10214, "text": "It avoids duplicate data or no repeating groups into a table." }, { "code": null, "e": 10337, "s": 10276, "text": "It reduces the chances for anomalies to occur in a database." }, { "code": null, "e": 10412, "s": 10337, "text": "24. What is the difference between a database schema and a database state?" }, { "code": null, "e": 10591, "s": 10412, "text": "The collection of information stored in a database at a particular moment in time is called database state while the overall design of the database is called the database schema." }, { "code": null, "e": 10623, "s": 10591, "text": "25. What is the purpose of SQL?" }, { "code": null, "e": 10812, "s": 10623, "text": "SQL stands for Structured Query Language whose main purpose is to interact with the relational databases in the form of inserting, deleting and updating/modifying the data in the database." }, { "code": null, "e": 10871, "s": 10812, "text": "26. Explain the concepts of a Primary key and Foreign Key." }, { "code": null, "e": 11124, "s": 10871, "text": "Primary Key is used to uniquely identify the records in a database table while Foreign Key is mainly used to link two or more tables together, as this is a particular field(s) in one of the database tables which are the primary key of some other table." }, { "code": null, "e": 11327, "s": 11124, "text": "Example: There are 2 tables – Employee and Department. Both have one common field/column as ‘ID’ where ID is the primary key of the Employee table while this is the foreign key for the Department table." }, { "code": null, "e": 11396, "s": 11327, "text": "27.What are the main differences between Primary key and Unique Key?" }, { "code": null, "e": 11429, "s": 11396, "text": "Given below are few differences:" }, { "code": null, "e": 11594, "s": 11429, "text": "The main difference between the Primary key and the Unique key is that the Primary key can never have a null value while the Unique key may consist of a null value." }, { "code": null, "e": 11700, "s": 11594, "text": " In each table, there can be only one primary key while there can be more than one unique key in a table." }, { "code": null, "e": 11754, "s": 11700, "text": "28. What is the concept of sub-query in terms of SQL?" }, { "code": null, "e": 11905, "s": 11754, "text": "Sub-query is basically the query that is included inside some other query and can also be called an inner query which is found inside the outer query." }, { "code": null, "e": 12018, "s": 11905, "text": "29. What is the use of the DROP command and what are the differences between DROP, TRUNCATE and DELETE commands?" }, { "code": null, "e": 12141, "s": 12018, "text": "DROP command is a DDL command which is used to drop/delete the existing table, database, index, or view from the database." }, { "code": null, "e": 12210, "s": 12141, "text": "The major difference between DROP, TRUNCATE and DELETE commands are:" }, { "code": null, "e": 12504, "s": 12210, "text": "DROP and TRUNCATE commands are the DDL commands which are used to delete tables from the database and once the table gets deleted, all the privileges and indexes that are related to the table also get deleted. These 2 operations cannot be rolled back and so should be used only when necessary." }, { "code": null, "e": 12629, "s": 12504, "text": "DELETE command, on the other hand, is a DML Command which is used to delete rows from the table and this can be rolled back." }, { "code": null, "e": 12690, "s": 12629, "text": "30. What is the main difference between UNION and UNION ALL?" }, { "code": null, "e": 12968, "s": 12690, "text": "UNION and UNION ALL are used to join the data from 2 or more tables but UNION removes duplicate rows and picks the rows which are distinct after combining the data from the tables whereas UNION ALL does not remove the duplicate rows, it just picks all the data from the tables." }, { "code": null, "e": 13009, "s": 12968, "text": "31. What is Correlated Subquery in DBMS?" }, { "code": null, "e": 13204, "s": 13009, "text": "A Subquery is also known as a nested query i.e. a query written inside some query. When a Subquery is executed for each of the rows of the outer query then it is termed as a Correlated Subquery." }, { "code": null, "e": 13246, "s": 13204, "text": "An example of Non-Correlated Subquery is:" }, { "code": null, "e": 13325, "s": 13246, "text": "Here, the inner query is not executed for each of the rows of the outer query." }, { "code": null, "e": 13383, "s": 13325, "text": "32. Explain Entity, Entity Type, and Entity Set in DBMS?" }, { "code": null, "e": 13564, "s": 13383, "text": "The entity is an object, place, or thing which has its independent existence in the real world and about which data can be stored in a database. For Example, any person, book, etc." }, { "code": null, "e": 13858, "s": 13564, "text": "Entity Type is a collection of entities that have the same attributes. For Example, the STUDENT table contains rows in which each row is an entity holding the attributes like name, age, and id of the students, hence STUDENT is an Entity Type that holds the entities having the same attributes." }, { "code": null, "e": 13969, "s": 13858, "text": "Entity Set is a collection of entities of the same type. For Example, A collection of the employees of a firm." }, { "code": null, "e": 14031, "s": 13969, "text": "33. What are the different levels of abstraction in the DBMS?" }, { "code": null, "e": 14083, "s": 14031, "text": "There are 3 levels of data abstraction in the DBMS." }, { "code": null, "e": 14097, "s": 14083, "text": "They include:" }, { "code": null, "e": 14215, "s": 14097, "text": "Physical Level: This is the lowest level of the data abstraction which states how the data is stored in the database." }, { "code": null, "e": 14379, "s": 14215, "text": "Logical Level: This is the next level of the data abstraction which states the type of the data and the relationship among the data that is stored in the database." }, { "code": null, "e": 14489, "s": 14379, "text": "View Level: This is the highest level in the data abstraction which shows/states only a part of the database." }, { "code": null, "e": 14534, "s": 14489, "text": "34 . What integrity rules exist in the DBMS?" }, { "code": null, "e": 14594, "s": 14534, "text": "There are two major integrity rules that exist in the DBMS." }, { "code": null, "e": 14707, "s": 14594, "text": "Entity Integrity: This states a very important rule that the value of a Primary key can never have a NULL value." }, { "code": null, "e": 14893, "s": 14707, "text": "Referential Integrity: This rule is related to the Foreign key which states that either the value of a Foreign key is a NULL value or it should be the primary key of any other relation." }, { "code": null, "e": 14928, "s": 14893, "text": "35. What is E-R model in the DBMS?" }, { "code": null, "e": 15093, "s": 14928, "text": " E-R model is known as an Entity-Relationship model in the DBMS which is based on the concept of the Entities and the relationship that exists among these entities." }, { "code": null, "e": 15142, "s": 15093, "text": "36. What is a functional dependency in the DBMS?" }, { "code": null, "e": 15266, "s": 15142, "text": " This is basically a constraint that is useful in describing the relationship among the different attributes in a relation." }, { "code": null, "e": 15469, "s": 15266, "text": "Example: If there is some relation ‘R1’ which has 2 attributes as Y and Z then the functional dependency among these 2 attributes can be shown as Y->Z which states that Z is functionally dependent on Y." }, { "code": null, "e": 15498, "s": 15469, "text": "37. What is 1NF in the DBMS?" }, { "code": null, "e": 15538, "s": 15498, "text": " 1NF is known as the First Normal Form." }, { "code": null, "e": 15757, "s": 15538, "text": "This is the easiest form of the normalization process which states that the domain of an attribute should have only atomic values. The objective of this is to remove the duplicate columns that are present in the table." }, { "code": null, "e": 15787, "s": 15757, "text": "38. What is 2NF in the DBMS?" }, { "code": null, "e": 15819, "s": 15787, "text": " 2NF is the Second Normal Form." }, { "code": null, "e": 15900, "s": 15819, "text": "Any table is said to have in the 2NF if it satisfies the following 2 conditions:" }, { "code": null, "e": 15923, "s": 15900, "text": "A table is in the 1NF." }, { "code": null, "e": 16029, "s": 15923, "text": " Each non-prime attribute of a table is said to be functionally dependent in totality on the primary key." }, { "code": null, "e": 16059, "s": 16029, "text": "39. What is 3NF in the DBMS?" }, { "code": null, "e": 16090, "s": 16059, "text": " 3NF is the Third Normal Form." }, { "code": null, "e": 16171, "s": 16090, "text": "Any table is said to have in the 3NF if it satisfies the following 2 conditions:" }, { "code": null, "e": 16195, "s": 16171, "text": " A table is in the 2NF." }, { "code": null, "e": 16299, "s": 16195, "text": "Each non-prime attribute of a table is said to be non-transitively dependent on every key of the table." }, { "code": null, "e": 16330, "s": 16299, "text": "40. What is BCNF in the DBMS?" }, { "code": null, "e": 16398, "s": 16330, "text": " BCNF is the Boyce Codd Normal Form which is stricter than the 3NF." }, { "code": null, "e": 16480, "s": 16398, "text": "Any table is said to have in the BCNF if it satisfies the following 2 conditions:" }, { "code": null, "e": 16503, "s": 16480, "text": "A table is in the 3NF." }, { "code": null, "e": 16592, "s": 16503, "text": "For each of the functional dependencies X->Y that exists, X is the super key of a table." }, { "code": null, "e": 16630, "s": 16592, "text": "41. What is a CLAUSE in terms of SQL?" }, { "code": null, "e": 16856, "s": 16630, "text": " This is used with the SQL queries to fetch specific data as per the requirements on the basis of the conditions that are put in the SQL. This is very helpful in picking the selective records from the complete set of records." }, { "code": null, "e": 16950, "s": 16856, "text": "For Example, There is a query that has a WHERE condition or the query with the HAVING clause." }, { "code": null, "e": 17018, "s": 16950, "text": "42.How can you get the alternate records from the table in the SQL?" }, { "code": null, "e": 17094, "s": 17018, "text": " If you want to fetch the odd numbers then the following query can be used:" }, { "code": null, "e": 17171, "s": 17094, "text": "If you want to fetch the even numbers, then the following query can be used:" }, { "code": null, "e": 17221, "s": 17171, "text": "43. How is the pattern matching done in the SQL?" }, { "code": null, "e": 17442, "s": 17221, "text": "Answer: With the help of the LIKE operator, pattern matching is possible in the SQL.’%’ is used with the LIKE operator when it matches with the 0 or more characters, and ‘_’ is used to match the one particular character." }, { "code": null, "e": 17451, "s": 17442, "text": "Example:" }, { "code": null, "e": 17484, "s": 17453, "text": "44. What is a join in the SQL?" }, { "code": null, "e": 17635, "s": 17484, "text": "A Join is one of the SQL statements which is used to join the data or the rows from 2 or more tables on the basis of a common field/column among them." }, { "code": null, "e": 17685, "s": 17635, "text": "45. What are the different types of joins in SQL?" }, { "code": null, "e": 17717, "s": 17685, "text": "There are 4 types of SQL Joins:" }, { "code": null, "e": 17824, "s": 17717, "text": " Inner Join: This type of join is used to fetch the data among the tables which are common in both tables." }, { "code": null, "e": 17997, "s": 17824, "text": " Left Join: This returns all the rows from the table which is on the left side of the join but only the matching rows from the table which is on the right side of the join." }, { "code": null, "e": 18171, "s": 17997, "text": " Right Join: This returns all the rows from the table which is on the right side of the join but only the matching rows from the table which is on the left side of the join." }, { "code": null, "e": 18316, "s": 18171, "text": " Full Join: This returns the rows from all the tables on which the join condition has been put and the rows which do not match hold null values." }, { "code": null, "e": 18350, "s": 18316, "text": "46. Explain the Stored Procedure." }, { "code": null, "e": 18552, "s": 18350, "text": "A Stored Procedure is a group of SQL statements in the form of a function that has some unique name and is stored in relational database management systems(RDBMS) and can be accessed whenever required." }, { "code": null, "e": 18571, "s": 18552, "text": "47. What is RDBMS?" }, { "code": null, "e": 18741, "s": 18571, "text": "RDBMS is the Relational Database Management System which contains data in the form of the tables and data is accessed on the basis of the common fields among the tables." }, { "code": null, "e": 18804, "s": 18741, "text": "48. What are the different types of relationships in the DBMS?" }, { "code": null, "e": 18870, "s": 18804, "text": "A Relationship in DBMS depicts an association between the tables." }, { "code": null, "e": 18908, "s": 18870, "text": "Different types of relationships are:" }, { "code": null, "e": 19061, "s": 18908, "text": "One-to-One: This basically states that there should be a one-to-one relationship between the tables i.e. there should be one record in both the tables. " }, { "code": null, "e": 19242, "s": 19061, "text": "One-to-Many: This states that there can be many relationships for one i.e. a primary key table hold only one record which can have many, one, or none records in the related table. " }, { "code": null, "e": 19327, "s": 19242, "text": "Many-to-Many: This states that both the tables can be related to many other tables. " }, { "code": null, "e": 19374, "s": 19327, "text": "49. What do you mean by Entity type extension?" }, { "code": null, "e": 19513, "s": 19374, "text": "Compilation of similar entity types into one particular type which is grouped together as an entity set is known as entity type extension." }, { "code": null, "e": 19552, "s": 19513, "text": "50. What is conceptual design in dbms?" }, { "code": null, "e": 19894, "s": 19552, "text": "Conceptual design is the first stage in the database design process. The goal at this stage is to design a database that is independent of database software and physical details. The output of this process is a conceptual data model that describes the main data entities, attributes, relationships, and constraints of a given problem domain." }, { "code": null, "e": 20028, "s": 19894, "text": "51. Differentiate between logical database design and physical database design. Show how this separation leads to data independence. " }, { "code": null, "e": 20153, "s": 20028, "text": "Maps or transforms the conceptual schema (or an ER schema) from the high-level data model into a relational database schema." }, { "code": null, "e": 20281, "s": 20153, "text": "The specifications for the stored database in terms of physical storage structures, record placement, and indexes are designed." }, { "code": null, "e": 20320, "s": 20281, "text": "The mapping can proceed in two stages:" }, { "code": null, "e": 20372, "s": 20320, "text": "System-independent mapping but data model-dependent" }, { "code": null, "e": 20413, "s": 20372, "text": "Tailoring the schemas to a specific DBMS" }, { "code": null, "e": 20508, "s": 20413, "text": "The following criteria are often used to guide the choice of physical database design options:" }, { "code": null, "e": 20522, "s": 20508, "text": "Response Time" }, { "code": null, "e": 20540, "s": 20522, "text": "Space Utilization" }, { "code": null, "e": 20563, "s": 20540, "text": "Transaction Throughput" }, { "code": null, "e": 20860, "s": 20563, "text": "DDL statements in the language of the chosen DBMS that specify the conceptual and external level schemas of the database system. But if the DDL statements include some physical design parameters, a complete DDL specification must wait until after the physical database design phase is completed." }, { "code": null, "e": 21047, "s": 20860, "text": "An initial determination of storage structures and the access paths for the database files. This corresponds to defining the internal schema in terms of Data Storage Definition Language." }, { "code": null, "e": 21581, "s": 21047, "text": "The database design is divided into several phases. The logical database design and physical database design are two of them. This separation is generally based on the concept of the three-level architecture of DBMS, which provides data independence. Therefore, we can say that this separation leads to data independence because the output of the logical database design is the conceptual and external level schemas of the database system which is independent of the output of the physical database design that is an internal schema." }, { "code": null, "e": 22121, "s": 21581, "text": "52. What are temporary tables? When are they useful? Temporary tables exist solely for a particular session, or whose data persists for the duration of the transaction. The temporary tables are generally used to support specialized rollups or specific application processing requirements. Unlike a permanent table, space is not allocated to a temporary table when it is created. Space will be dynamically allocated for the table as rows are inserted. The CREATE GLOBAL TEMPORARY TABLE command is used to create a temporary table in Oracle." }, { "code": null, "e": 22277, "s": 22121, "text": "53. Explain different types of failures that occur in the Oracle database.Types of Failures – In the Oracle database following types of failures can occur:" }, { "code": null, "e": 22297, "s": 22277, "text": "Statement Failure· " }, { "code": null, "e": 22329, "s": 22297, "text": "Bad data typeInsufficient space" }, { "code": null, "e": 22348, "s": 22329, "text": "Insufficient space" }, { "code": null, "e": 22408, "s": 22348, "text": "Insufficient Privileges (e.g., object privileges to a role)" }, { "code": null, "e": 22560, "s": 22408, "text": "User Process FailureThe user performed an abnormal disconnectThe user’s session was abnormally terminatedThe user’s program raised an address exception" }, { "code": null, "e": 22602, "s": 22560, "text": "The user performed an abnormal disconnect" }, { "code": null, "e": 22647, "s": 22602, "text": "The user’s session was abnormally terminated" }, { "code": null, "e": 22694, "s": 22647, "text": "The user’s program raised an address exception" }, { "code": null, "e": 22760, "s": 22694, "text": "User ErrorThe user drops a tableUser damages data by modification" }, { "code": null, "e": 22783, "s": 22760, "text": "The user drops a table" }, { "code": null, "e": 22817, "s": 22783, "text": "User damages data by modification" }, { "code": null, "e": 22834, "s": 22817, "text": "Instance Failure" }, { "code": null, "e": 22903, "s": 22834, "text": "Media FailureThe user drops a tableUser damages data by modification" }, { "code": null, "e": 22926, "s": 22903, "text": "The user drops a table" }, { "code": null, "e": 22960, "s": 22926, "text": "User damages data by modification" }, { "code": null, "e": 23070, "s": 22960, "text": "Alert LogsRecords informational and error messagesAll Instance startups and shutdowns are recorded in the log" }, { "code": null, "e": 23111, "s": 23070, "text": "Records informational and error messages" }, { "code": null, "e": 23171, "s": 23111, "text": "All Instance startups and shutdowns are recorded in the log" }, { "code": null, "e": 23217, "s": 23171, "text": "54. What is the main goal of RAID technology?" }, { "code": null, "e": 23299, "s": 23217, "text": "RAID stands for Redundant Array of Inexpensive (or sometimes “Independent”)Disks." }, { "code": null, "e": 23883, "s": 23299, "text": "RAID is a method of combining several hard disk drives into one logical unit (two or more disks grouped together to appear as a single device to the host system). RAID technology was developed to address the fault-tolerance and performance limitations of conventional disk storage. It can offer fault tolerance and higher throughput levels than a single hard drive or group of independent hard drives. While arrays were once considered complex and relatively specialized storage solutions, today they are easy to use and essential for a broad spectrum of client/server applications. " }, { "code": null, "e": 23894, "s": 23883, "text": "AnupamJain" }, { "code": null, "e": 23905, "s": 23894, "text": "piyushav94" }, { "code": null, "e": 23912, "s": 23905, "text": "surajv" }, { "code": null, "e": 23928, "s": 23912, "text": "varshachoudhary" }, { "code": null, "e": 23938, "s": 23928, "text": "user_18tl" }, { "code": null, "e": 23943, "s": 23938, "text": "DBMS" }, { "code": null, "e": 23948, "s": 23943, "text": "DBMS" }, { "code": null, "e": 24046, "s": 23948, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 24057, "s": 24046, "text": "CTE in SQL" }, { "code": null, "e": 24110, "s": 24057, "text": "Difference between Clustered and Non-clustered index" }, { "code": null, "e": 24144, "s": 24110, "text": "Data Preprocessing in Data Mining" }, { "code": null, "e": 24189, "s": 24144, "text": "Difference between DELETE, DROP and TRUNCATE" }, { "code": null, "e": 24222, "s": 24189, "text": "Difference between SQL and NoSQL" }, { "code": null, "e": 24252, "s": 24222, "text": "Indexing in Databases | Set 1" }, { "code": null, "e": 24284, "s": 24252, "text": "Structured Query Language (SQL)" }, { "code": null, "e": 24323, "s": 24284, "text": "Difference between DDL and DML in DBMS" }, { "code": null, "e": 24364, "s": 24323, "text": "Types of Functional dependencies in DBMS" } ]
Get n-smallest values from a particular column in Pandas DataFrame
18 Dec, 2018 Pandas DataFrame is two-dimensional size-mutable, potentially heterogeneous tabular data structure with labeled axes (rows and columns). Let’s see how can we can get n-smallest values from a particular column in Pandas DataFrame. Observe this dataset first. We’ll use ‘Age’, ‘Weight’ and ‘Salary’ columns of this data in order to get n-smallest values from a particular column in Pandas DataFrame. # importing pandas module import pandas as pd # making data frame df = pd.read_csv("https://media.geeksforgeeks.org/wp-content/uploads/nba.csv") df.head(10) Code #1: Getting 5 smallest Age # importing pandas module import pandas as pd # making data frame df = pd.read_csv("nba.csv") df.nsmallest(5, ['Age']) Output: Code #2: Getting 10 minimum weights # importing pandas module import pandas as pd # making data frame df = pd.read_csv("nba.csv") df.nsmallest(10, ['Weight']) Output: Code #3: Getting 10 minimum salary # importing pandas module import pandas as pd # making data frame df = pd.read_csv("nba.csv") df.nsmallest(5, ['Salary']) Output: pandas-dataframe-program Python pandas-dataFrame Python-pandas Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Python Classes and Objects Python | os.path.join() method Python OOPs Concepts How to drop one or multiple columns in Pandas Dataframe Introduction To PYTHON How To Convert Python Dictionary To JSON? Check if element exists in list in Python Python | datetime.timedelta() function Python | Get unique values from a list
[ { "code": null, "e": 28, "s": 0, "text": "\n18 Dec, 2018" }, { "code": null, "e": 165, "s": 28, "text": "Pandas DataFrame is two-dimensional size-mutable, potentially heterogeneous tabular data structure with labeled axes (rows and columns)." }, { "code": null, "e": 258, "s": 165, "text": "Let’s see how can we can get n-smallest values from a particular column in Pandas DataFrame." }, { "code": null, "e": 426, "s": 258, "text": "Observe this dataset first. We’ll use ‘Age’, ‘Weight’ and ‘Salary’ columns of this data in order to get n-smallest values from a particular column in Pandas DataFrame." }, { "code": "# importing pandas module import pandas as pd # making data frame df = pd.read_csv(\"https://media.geeksforgeeks.org/wp-content/uploads/nba.csv\") df.head(10)", "e": 589, "s": 426, "text": null }, { "code": null, "e": 621, "s": 589, "text": "Code #1: Getting 5 smallest Age" }, { "code": "# importing pandas module import pandas as pd # making data frame df = pd.read_csv(\"nba.csv\") df.nsmallest(5, ['Age'])", "e": 748, "s": 621, "text": null }, { "code": null, "e": 757, "s": 748, "text": "Output: " }, { "code": null, "e": 793, "s": 757, "text": "Code #2: Getting 10 minimum weights" }, { "code": "# importing pandas module import pandas as pd # making data frame df = pd.read_csv(\"nba.csv\") df.nsmallest(10, ['Weight'])", "e": 924, "s": 793, "text": null }, { "code": null, "e": 933, "s": 924, "text": "Output: " }, { "code": null, "e": 968, "s": 933, "text": "Code #3: Getting 10 minimum salary" }, { "code": "# importing pandas module import pandas as pd # making data frame df = pd.read_csv(\"nba.csv\") df.nsmallest(5, ['Salary'])", "e": 1098, "s": 968, "text": null }, { "code": null, "e": 1106, "s": 1098, "text": "Output:" }, { "code": null, "e": 1131, "s": 1106, "text": "pandas-dataframe-program" }, { "code": null, "e": 1155, "s": 1131, "text": "Python pandas-dataFrame" }, { "code": null, "e": 1169, "s": 1155, "text": "Python-pandas" }, { "code": null, "e": 1176, "s": 1169, "text": "Python" }, { "code": null, "e": 1274, "s": 1176, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1306, "s": 1274, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 1333, "s": 1306, "text": "Python Classes and Objects" }, { "code": null, "e": 1364, "s": 1333, "text": "Python | os.path.join() method" }, { "code": null, "e": 1385, "s": 1364, "text": "Python OOPs Concepts" }, { "code": null, "e": 1441, "s": 1385, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 1464, "s": 1441, "text": "Introduction To PYTHON" }, { "code": null, "e": 1506, "s": 1464, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 1548, "s": 1506, "text": "Check if element exists in list in Python" }, { "code": null, "e": 1587, "s": 1548, "text": "Python | datetime.timedelta() function" } ]
Find common elements in two ArrayLists in Java
11 Dec, 2018 Prerequisite: ArrayList in Java Given two ArrayLists, the task is to print all common elements in both the ArrayLists in Java . Examples: Input: List1 = ["Hii", "Geeks", "for", "Geeks"], List2 = ["Hii", "Geeks", "Gaurav"] Output: [Hii, Geeks, Geeks] Input: List1 = ["a", "b", "c", "d", "e", "f"], List2 = ["b", "d", "e", "h", "g", "c"] Output:[b, c, d, e] Using Collections.retainAll() methodSyntax:Collections1.retainAll(Collections2) This method keeps only the common elements of both Collection in Collection1. Approach:Get the two ArrayLists.Find the common elements in both the Lists using Collection.retainAll() method. This method keeps only the common elements of both Collection in Collection1.The List 1 now contains the common elements only.Below is the implementation of the above approach:Program: By modifying the contents of List1.// Java Program to find common elements// in two ArrayLists// Using retainAll() method // import ArrayList packageimport java.util.ArrayList; public class GFG { // main method public static void main(String[] args) { // create ArrayList list1 ArrayList<String> list1 = new ArrayList<String>(); // Add values in ArrayList list1.add("Hii"); list1.add("Geeks"); list1.add("for"); list1.add("Geeks"); // print list 1 System.out.println("List1: " + list1); // Create ArrayList list2 ArrayList<String> list2 = new ArrayList<String>(); // Add values in ArrayList list2.add("Hii"); list2.add("Geeks"); list2.add("Gaurav"); // print list 2 System.out.println("List2: " + list2); // Find the common elements list1.retainAll(list2); // print list 1 System.out.println("Common elements: " + list1); }}Output:List1: [Hii, Geeks, for, Geeks] List2: [Hii, Geeks, Gaurav] Common elements: [Hii, Geeks, Geeks] Program 2: By retaining the contents of List1.// Java Program to find common elements// in two ArrayLists// Using retainAll() method // import ArrayList packageimport java.util.ArrayList; public class GFG { // main method public static void main(String[] args) { // create ArrayList list1 ArrayList<String> list1 = new ArrayList<String>(); // Add values in ArrayList list1.add("Hii"); list1.add("Geeks"); list1.add("for"); list1.add("Geeks"); // print list 1 System.out.println("List1: " + list1); // Create ArrayList list2 ArrayList<String> list2 = new ArrayList<String>(); // Add values in ArrayList list2.add("Hii"); list2.add("Geeks"); list2.add("Gaurav"); // print list 2 System.out.println("List2: " + list2); // Create ArrayList list3 ArrayList<String> list3 = new ArrayList<String>(list1); // Store the comparison output // in ArrayList list3 list3.retainAll(list2); // print list 3 System.out.println("Common elements: " + list3); }}Output:List1: [Hii, Geeks, for, Geeks] List2: [Hii, Geeks, Gaurav] Common elements: [Hii, Geeks, Geeks] Using Stream filterSyntax:list1.stream() .filter(list2::contains) .collect(Collectors .toList())); This method returns element if found in second list. Approach:First create two ArrayList and add values of list.Convert the ArrayList to Stream using stream() method.Set the filter condition to be distinct using contains() method.Collect the filtered values as List using collect() method. This list will be return common element in both list.Print list3Below is the implementation of the above approach:Program:// Java Program to find common elements// in two ArrayLists// Using Stream filter method // import ArrayList packageimport java.util.*;import java.util.stream.*; public class GFG { // main method public static void main(String[] args) { // create ArrayList list1 ArrayList<String> list1 = new ArrayList<String>(); // Add values in ArrayList list1.add("Hii"); list1.add("Geeks"); list1.add("for"); list1.add("Geeks"); // print list 1 System.out.println("List1: " + list1); // Create ArrayList list2 ArrayList<String> list2 = new ArrayList<String>(); // Add values in ArrayList list2.add("Hii"); list2.add("Geeks"); list2.add("Gaurav"); // print list 2 System.out.println("List2: " + list2); // Find common elements System.out.print("Common elements: "); System.out.println(list1.stream() .filter(list2::contains) .collect(Collectors .toList())); }}Output:List1: [Hii, Geeks, for, Geeks] List2: [Hii, Geeks, Gaurav] Common elements: [Hii, Geeks, Geeks] Naive approach:First create two ArrayList and add values of list.Create a temporary ArrayList to contain common elements.Iterate through the list1 and check if that element is present in the list2 using ArrayList.contains() method.If found, add it to the list3Print the common elements from list3Below is the implementation of the above approach:// Java Program to find common elements// in two ArrayLists// Using Stream filter method // import ArrayList packageimport java.util.ArrayList; public class GFG { // main method public static void main(String[] args) { // create ArrayList list1 ArrayList<String> list1 = new ArrayList<String>(); // Add values in ArrayList list1.add("Hii"); list1.add("Geeks"); list1.add("for"); list1.add("Geeks"); // print list 1 System.out.println("List1: " + list1); // Create ArrayList list2 ArrayList<String> list2 = new ArrayList<String>(); // Add values in ArrayList list2.add("Hii"); list2.add("Geeks"); list2.add("Gaurav"); // print list 2 System.out.println("List2: " + list2); // Create ArrayList list3 ArrayList<String> list3 = new ArrayList<String>(); // Find common elements // while iterating through list1 for (String temp : list1) { // Check if theis element is // present in list2 or not if (list2.contains(temp)) { // Since present, add it to list3 list3.add(temp); } } // print common elements from list 3 System.out.println("Common elements: " + list3); }}Output:List1: [Hii, Geeks, for, Geeks] List2: [Hii, Geeks, Gaurav] Common elements: [Hii, Geeks, Geeks] My Personal Notes arrow_drop_upSave Using Collections.retainAll() methodSyntax:Collections1.retainAll(Collections2) This method keeps only the common elements of both Collection in Collection1. Approach:Get the two ArrayLists.Find the common elements in both the Lists using Collection.retainAll() method. This method keeps only the common elements of both Collection in Collection1.The List 1 now contains the common elements only.Below is the implementation of the above approach:Program: By modifying the contents of List1.// Java Program to find common elements// in two ArrayLists// Using retainAll() method // import ArrayList packageimport java.util.ArrayList; public class GFG { // main method public static void main(String[] args) { // create ArrayList list1 ArrayList<String> list1 = new ArrayList<String>(); // Add values in ArrayList list1.add("Hii"); list1.add("Geeks"); list1.add("for"); list1.add("Geeks"); // print list 1 System.out.println("List1: " + list1); // Create ArrayList list2 ArrayList<String> list2 = new ArrayList<String>(); // Add values in ArrayList list2.add("Hii"); list2.add("Geeks"); list2.add("Gaurav"); // print list 2 System.out.println("List2: " + list2); // Find the common elements list1.retainAll(list2); // print list 1 System.out.println("Common elements: " + list1); }}Output:List1: [Hii, Geeks, for, Geeks] List2: [Hii, Geeks, Gaurav] Common elements: [Hii, Geeks, Geeks] Program 2: By retaining the contents of List1.// Java Program to find common elements// in two ArrayLists// Using retainAll() method // import ArrayList packageimport java.util.ArrayList; public class GFG { // main method public static void main(String[] args) { // create ArrayList list1 ArrayList<String> list1 = new ArrayList<String>(); // Add values in ArrayList list1.add("Hii"); list1.add("Geeks"); list1.add("for"); list1.add("Geeks"); // print list 1 System.out.println("List1: " + list1); // Create ArrayList list2 ArrayList<String> list2 = new ArrayList<String>(); // Add values in ArrayList list2.add("Hii"); list2.add("Geeks"); list2.add("Gaurav"); // print list 2 System.out.println("List2: " + list2); // Create ArrayList list3 ArrayList<String> list3 = new ArrayList<String>(list1); // Store the comparison output // in ArrayList list3 list3.retainAll(list2); // print list 3 System.out.println("Common elements: " + list3); }}Output:List1: [Hii, Geeks, for, Geeks] List2: [Hii, Geeks, Gaurav] Common elements: [Hii, Geeks, Geeks] Syntax: Collections1.retainAll(Collections2) This method keeps only the common elements of both Collection in Collection1. Approach: Get the two ArrayLists.Find the common elements in both the Lists using Collection.retainAll() method. This method keeps only the common elements of both Collection in Collection1.The List 1 now contains the common elements only. Get the two ArrayLists. Find the common elements in both the Lists using Collection.retainAll() method. This method keeps only the common elements of both Collection in Collection1. The List 1 now contains the common elements only. Below is the implementation of the above approach:Program: By modifying the contents of List1. // Java Program to find common elements// in two ArrayLists// Using retainAll() method // import ArrayList packageimport java.util.ArrayList; public class GFG { // main method public static void main(String[] args) { // create ArrayList list1 ArrayList<String> list1 = new ArrayList<String>(); // Add values in ArrayList list1.add("Hii"); list1.add("Geeks"); list1.add("for"); list1.add("Geeks"); // print list 1 System.out.println("List1: " + list1); // Create ArrayList list2 ArrayList<String> list2 = new ArrayList<String>(); // Add values in ArrayList list2.add("Hii"); list2.add("Geeks"); list2.add("Gaurav"); // print list 2 System.out.println("List2: " + list2); // Find the common elements list1.retainAll(list2); // print list 1 System.out.println("Common elements: " + list1); }} List1: [Hii, Geeks, for, Geeks] List2: [Hii, Geeks, Gaurav] Common elements: [Hii, Geeks, Geeks] Program 2: By retaining the contents of List1. // Java Program to find common elements// in two ArrayLists// Using retainAll() method // import ArrayList packageimport java.util.ArrayList; public class GFG { // main method public static void main(String[] args) { // create ArrayList list1 ArrayList<String> list1 = new ArrayList<String>(); // Add values in ArrayList list1.add("Hii"); list1.add("Geeks"); list1.add("for"); list1.add("Geeks"); // print list 1 System.out.println("List1: " + list1); // Create ArrayList list2 ArrayList<String> list2 = new ArrayList<String>(); // Add values in ArrayList list2.add("Hii"); list2.add("Geeks"); list2.add("Gaurav"); // print list 2 System.out.println("List2: " + list2); // Create ArrayList list3 ArrayList<String> list3 = new ArrayList<String>(list1); // Store the comparison output // in ArrayList list3 list3.retainAll(list2); // print list 3 System.out.println("Common elements: " + list3); }} List1: [Hii, Geeks, for, Geeks] List2: [Hii, Geeks, Gaurav] Common elements: [Hii, Geeks, Geeks] Using Stream filterSyntax:list1.stream() .filter(list2::contains) .collect(Collectors .toList())); This method returns element if found in second list. Approach:First create two ArrayList and add values of list.Convert the ArrayList to Stream using stream() method.Set the filter condition to be distinct using contains() method.Collect the filtered values as List using collect() method. This list will be return common element in both list.Print list3Below is the implementation of the above approach:Program:// Java Program to find common elements// in two ArrayLists// Using Stream filter method // import ArrayList packageimport java.util.*;import java.util.stream.*; public class GFG { // main method public static void main(String[] args) { // create ArrayList list1 ArrayList<String> list1 = new ArrayList<String>(); // Add values in ArrayList list1.add("Hii"); list1.add("Geeks"); list1.add("for"); list1.add("Geeks"); // print list 1 System.out.println("List1: " + list1); // Create ArrayList list2 ArrayList<String> list2 = new ArrayList<String>(); // Add values in ArrayList list2.add("Hii"); list2.add("Geeks"); list2.add("Gaurav"); // print list 2 System.out.println("List2: " + list2); // Find common elements System.out.print("Common elements: "); System.out.println(list1.stream() .filter(list2::contains) .collect(Collectors .toList())); }}Output:List1: [Hii, Geeks, for, Geeks] List2: [Hii, Geeks, Gaurav] Common elements: [Hii, Geeks, Geeks] Syntax: list1.stream() .filter(list2::contains) .collect(Collectors .toList())); This method returns element if found in second list. Approach: First create two ArrayList and add values of list.Convert the ArrayList to Stream using stream() method.Set the filter condition to be distinct using contains() method.Collect the filtered values as List using collect() method. This list will be return common element in both list.Print list3 First create two ArrayList and add values of list. Convert the ArrayList to Stream using stream() method. Set the filter condition to be distinct using contains() method. Collect the filtered values as List using collect() method. This list will be return common element in both list. Print list3 Below is the implementation of the above approach: Program: // Java Program to find common elements// in two ArrayLists// Using Stream filter method // import ArrayList packageimport java.util.*;import java.util.stream.*; public class GFG { // main method public static void main(String[] args) { // create ArrayList list1 ArrayList<String> list1 = new ArrayList<String>(); // Add values in ArrayList list1.add("Hii"); list1.add("Geeks"); list1.add("for"); list1.add("Geeks"); // print list 1 System.out.println("List1: " + list1); // Create ArrayList list2 ArrayList<String> list2 = new ArrayList<String>(); // Add values in ArrayList list2.add("Hii"); list2.add("Geeks"); list2.add("Gaurav"); // print list 2 System.out.println("List2: " + list2); // Find common elements System.out.print("Common elements: "); System.out.println(list1.stream() .filter(list2::contains) .collect(Collectors .toList())); }} List1: [Hii, Geeks, for, Geeks] List2: [Hii, Geeks, Gaurav] Common elements: [Hii, Geeks, Geeks] Naive approach:First create two ArrayList and add values of list.Create a temporary ArrayList to contain common elements.Iterate through the list1 and check if that element is present in the list2 using ArrayList.contains() method.If found, add it to the list3Print the common elements from list3Below is the implementation of the above approach:// Java Program to find common elements// in two ArrayLists// Using Stream filter method // import ArrayList packageimport java.util.ArrayList; public class GFG { // main method public static void main(String[] args) { // create ArrayList list1 ArrayList<String> list1 = new ArrayList<String>(); // Add values in ArrayList list1.add("Hii"); list1.add("Geeks"); list1.add("for"); list1.add("Geeks"); // print list 1 System.out.println("List1: " + list1); // Create ArrayList list2 ArrayList<String> list2 = new ArrayList<String>(); // Add values in ArrayList list2.add("Hii"); list2.add("Geeks"); list2.add("Gaurav"); // print list 2 System.out.println("List2: " + list2); // Create ArrayList list3 ArrayList<String> list3 = new ArrayList<String>(); // Find common elements // while iterating through list1 for (String temp : list1) { // Check if theis element is // present in list2 or not if (list2.contains(temp)) { // Since present, add it to list3 list3.add(temp); } } // print common elements from list 3 System.out.println("Common elements: " + list3); }}Output:List1: [Hii, Geeks, for, Geeks] List2: [Hii, Geeks, Gaurav] Common elements: [Hii, Geeks, Geeks] First create two ArrayList and add values of list.Create a temporary ArrayList to contain common elements.Iterate through the list1 and check if that element is present in the list2 using ArrayList.contains() method.If found, add it to the list3Print the common elements from list3 First create two ArrayList and add values of list. Create a temporary ArrayList to contain common elements. Iterate through the list1 and check if that element is present in the list2 using ArrayList.contains() method. If found, add it to the list3 Print the common elements from list3 Below is the implementation of the above approach: // Java Program to find common elements// in two ArrayLists// Using Stream filter method // import ArrayList packageimport java.util.ArrayList; public class GFG { // main method public static void main(String[] args) { // create ArrayList list1 ArrayList<String> list1 = new ArrayList<String>(); // Add values in ArrayList list1.add("Hii"); list1.add("Geeks"); list1.add("for"); list1.add("Geeks"); // print list 1 System.out.println("List1: " + list1); // Create ArrayList list2 ArrayList<String> list2 = new ArrayList<String>(); // Add values in ArrayList list2.add("Hii"); list2.add("Geeks"); list2.add("Gaurav"); // print list 2 System.out.println("List2: " + list2); // Create ArrayList list3 ArrayList<String> list3 = new ArrayList<String>(); // Find common elements // while iterating through list1 for (String temp : list1) { // Check if theis element is // present in list2 or not if (list2.contains(temp)) { // Since present, add it to list3 list3.add(temp); } } // print common elements from list 3 System.out.println("Common elements: " + list3); }} List1: [Hii, Geeks, for, Geeks] List2: [Hii, Geeks, Gaurav] Common elements: [Hii, Geeks, Geeks] Java - util package Java-Collections Java-List-Programs Technical Scripter 2018 Java Technical Scripter Java Java-Collections Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n11 Dec, 2018" }, { "code": null, "e": 60, "s": 28, "text": "Prerequisite: ArrayList in Java" }, { "code": null, "e": 156, "s": 60, "text": "Given two ArrayLists, the task is to print all common elements in both the ArrayLists in Java ." }, { "code": null, "e": 166, "s": 156, "text": "Examples:" }, { "code": null, "e": 402, "s": 166, "text": "Input: List1 = [\"Hii\", \"Geeks\", \"for\", \"Geeks\"], \n List2 = [\"Hii\", \"Geeks\", \"Gaurav\"]\nOutput: [Hii, Geeks, Geeks]\n\nInput: List1 = [\"a\", \"b\", \"c\", \"d\", \"e\", \"f\"], \n List2 = [\"b\", \"d\", \"e\", \"h\", \"g\", \"c\"]\nOutput:[b, c, d, e]\n" }, { "code": null, "e": 7193, "s": 402, "text": "Using Collections.retainAll() methodSyntax:Collections1.retainAll(Collections2)\n\nThis method keeps only the common elements\nof both Collection in Collection1.\nApproach:Get the two ArrayLists.Find the common elements in both the Lists using Collection.retainAll() method. This method keeps only the common elements of both Collection in Collection1.The List 1 now contains the common elements only.Below is the implementation of the above approach:Program: By modifying the contents of List1.// Java Program to find common elements// in two ArrayLists// Using retainAll() method // import ArrayList packageimport java.util.ArrayList; public class GFG { // main method public static void main(String[] args) { // create ArrayList list1 ArrayList<String> list1 = new ArrayList<String>(); // Add values in ArrayList list1.add(\"Hii\"); list1.add(\"Geeks\"); list1.add(\"for\"); list1.add(\"Geeks\"); // print list 1 System.out.println(\"List1: \" + list1); // Create ArrayList list2 ArrayList<String> list2 = new ArrayList<String>(); // Add values in ArrayList list2.add(\"Hii\"); list2.add(\"Geeks\"); list2.add(\"Gaurav\"); // print list 2 System.out.println(\"List2: \" + list2); // Find the common elements list1.retainAll(list2); // print list 1 System.out.println(\"Common elements: \" + list1); }}Output:List1: [Hii, Geeks, for, Geeks]\nList2: [Hii, Geeks, Gaurav]\nCommon elements: [Hii, Geeks, Geeks]\nProgram 2: By retaining the contents of List1.// Java Program to find common elements// in two ArrayLists// Using retainAll() method // import ArrayList packageimport java.util.ArrayList; public class GFG { // main method public static void main(String[] args) { // create ArrayList list1 ArrayList<String> list1 = new ArrayList<String>(); // Add values in ArrayList list1.add(\"Hii\"); list1.add(\"Geeks\"); list1.add(\"for\"); list1.add(\"Geeks\"); // print list 1 System.out.println(\"List1: \" + list1); // Create ArrayList list2 ArrayList<String> list2 = new ArrayList<String>(); // Add values in ArrayList list2.add(\"Hii\"); list2.add(\"Geeks\"); list2.add(\"Gaurav\"); // print list 2 System.out.println(\"List2: \" + list2); // Create ArrayList list3 ArrayList<String> list3 = new ArrayList<String>(list1); // Store the comparison output // in ArrayList list3 list3.retainAll(list2); // print list 3 System.out.println(\"Common elements: \" + list3); }}Output:List1: [Hii, Geeks, for, Geeks]\nList2: [Hii, Geeks, Gaurav]\nCommon elements: [Hii, Geeks, Geeks]\nUsing Stream filterSyntax:list1.stream()\n .filter(list2::contains)\n .collect(Collectors\n .toList()));\n\nThis method returns element if found in second list.\nApproach:First create two ArrayList and add values of list.Convert the ArrayList to Stream using stream() method.Set the filter condition to be distinct using contains() method.Collect the filtered values as List using collect() method. This list will be return common element in both list.Print list3Below is the implementation of the above approach:Program:// Java Program to find common elements// in two ArrayLists// Using Stream filter method // import ArrayList packageimport java.util.*;import java.util.stream.*; public class GFG { // main method public static void main(String[] args) { // create ArrayList list1 ArrayList<String> list1 = new ArrayList<String>(); // Add values in ArrayList list1.add(\"Hii\"); list1.add(\"Geeks\"); list1.add(\"for\"); list1.add(\"Geeks\"); // print list 1 System.out.println(\"List1: \" + list1); // Create ArrayList list2 ArrayList<String> list2 = new ArrayList<String>(); // Add values in ArrayList list2.add(\"Hii\"); list2.add(\"Geeks\"); list2.add(\"Gaurav\"); // print list 2 System.out.println(\"List2: \" + list2); // Find common elements System.out.print(\"Common elements: \"); System.out.println(list1.stream() .filter(list2::contains) .collect(Collectors .toList())); }}Output:List1: [Hii, Geeks, for, Geeks]\nList2: [Hii, Geeks, Gaurav]\nCommon elements: [Hii, Geeks, Geeks]\nNaive approach:First create two ArrayList and add values of list.Create a temporary ArrayList to contain common elements.Iterate through the list1 and check if that element is present in the list2 using ArrayList.contains() method.If found, add it to the list3Print the common elements from list3Below is the implementation of the above approach:// Java Program to find common elements// in two ArrayLists// Using Stream filter method // import ArrayList packageimport java.util.ArrayList; public class GFG { // main method public static void main(String[] args) { // create ArrayList list1 ArrayList<String> list1 = new ArrayList<String>(); // Add values in ArrayList list1.add(\"Hii\"); list1.add(\"Geeks\"); list1.add(\"for\"); list1.add(\"Geeks\"); // print list 1 System.out.println(\"List1: \" + list1); // Create ArrayList list2 ArrayList<String> list2 = new ArrayList<String>(); // Add values in ArrayList list2.add(\"Hii\"); list2.add(\"Geeks\"); list2.add(\"Gaurav\"); // print list 2 System.out.println(\"List2: \" + list2); // Create ArrayList list3 ArrayList<String> list3 = new ArrayList<String>(); // Find common elements // while iterating through list1 for (String temp : list1) { // Check if theis element is // present in list2 or not if (list2.contains(temp)) { // Since present, add it to list3 list3.add(temp); } } // print common elements from list 3 System.out.println(\"Common elements: \" + list3); }}Output:List1: [Hii, Geeks, for, Geeks]\nList2: [Hii, Geeks, Gaurav]\nCommon elements: [Hii, Geeks, Geeks]\nMy Personal Notes\narrow_drop_upSave" }, { "code": null, "e": 10216, "s": 7193, "text": "Using Collections.retainAll() methodSyntax:Collections1.retainAll(Collections2)\n\nThis method keeps only the common elements\nof both Collection in Collection1.\nApproach:Get the two ArrayLists.Find the common elements in both the Lists using Collection.retainAll() method. This method keeps only the common elements of both Collection in Collection1.The List 1 now contains the common elements only.Below is the implementation of the above approach:Program: By modifying the contents of List1.// Java Program to find common elements// in two ArrayLists// Using retainAll() method // import ArrayList packageimport java.util.ArrayList; public class GFG { // main method public static void main(String[] args) { // create ArrayList list1 ArrayList<String> list1 = new ArrayList<String>(); // Add values in ArrayList list1.add(\"Hii\"); list1.add(\"Geeks\"); list1.add(\"for\"); list1.add(\"Geeks\"); // print list 1 System.out.println(\"List1: \" + list1); // Create ArrayList list2 ArrayList<String> list2 = new ArrayList<String>(); // Add values in ArrayList list2.add(\"Hii\"); list2.add(\"Geeks\"); list2.add(\"Gaurav\"); // print list 2 System.out.println(\"List2: \" + list2); // Find the common elements list1.retainAll(list2); // print list 1 System.out.println(\"Common elements: \" + list1); }}Output:List1: [Hii, Geeks, for, Geeks]\nList2: [Hii, Geeks, Gaurav]\nCommon elements: [Hii, Geeks, Geeks]\nProgram 2: By retaining the contents of List1.// Java Program to find common elements// in two ArrayLists// Using retainAll() method // import ArrayList packageimport java.util.ArrayList; public class GFG { // main method public static void main(String[] args) { // create ArrayList list1 ArrayList<String> list1 = new ArrayList<String>(); // Add values in ArrayList list1.add(\"Hii\"); list1.add(\"Geeks\"); list1.add(\"for\"); list1.add(\"Geeks\"); // print list 1 System.out.println(\"List1: \" + list1); // Create ArrayList list2 ArrayList<String> list2 = new ArrayList<String>(); // Add values in ArrayList list2.add(\"Hii\"); list2.add(\"Geeks\"); list2.add(\"Gaurav\"); // print list 2 System.out.println(\"List2: \" + list2); // Create ArrayList list3 ArrayList<String> list3 = new ArrayList<String>(list1); // Store the comparison output // in ArrayList list3 list3.retainAll(list2); // print list 3 System.out.println(\"Common elements: \" + list3); }}Output:List1: [Hii, Geeks, for, Geeks]\nList2: [Hii, Geeks, Gaurav]\nCommon elements: [Hii, Geeks, Geeks]\n" }, { "code": null, "e": 10224, "s": 10216, "text": "Syntax:" }, { "code": null, "e": 10341, "s": 10224, "text": "Collections1.retainAll(Collections2)\n\nThis method keeps only the common elements\nof both Collection in Collection1.\n" }, { "code": null, "e": 10351, "s": 10341, "text": "Approach:" }, { "code": null, "e": 10581, "s": 10351, "text": "Get the two ArrayLists.Find the common elements in both the Lists using Collection.retainAll() method. This method keeps only the common elements of both Collection in Collection1.The List 1 now contains the common elements only." }, { "code": null, "e": 10605, "s": 10581, "text": "Get the two ArrayLists." }, { "code": null, "e": 10763, "s": 10605, "text": "Find the common elements in both the Lists using Collection.retainAll() method. This method keeps only the common elements of both Collection in Collection1." }, { "code": null, "e": 10813, "s": 10763, "text": "The List 1 now contains the common elements only." }, { "code": null, "e": 10908, "s": 10813, "text": "Below is the implementation of the above approach:Program: By modifying the contents of List1." }, { "code": "// Java Program to find common elements// in two ArrayLists// Using retainAll() method // import ArrayList packageimport java.util.ArrayList; public class GFG { // main method public static void main(String[] args) { // create ArrayList list1 ArrayList<String> list1 = new ArrayList<String>(); // Add values in ArrayList list1.add(\"Hii\"); list1.add(\"Geeks\"); list1.add(\"for\"); list1.add(\"Geeks\"); // print list 1 System.out.println(\"List1: \" + list1); // Create ArrayList list2 ArrayList<String> list2 = new ArrayList<String>(); // Add values in ArrayList list2.add(\"Hii\"); list2.add(\"Geeks\"); list2.add(\"Gaurav\"); // print list 2 System.out.println(\"List2: \" + list2); // Find the common elements list1.retainAll(list2); // print list 1 System.out.println(\"Common elements: \" + list1); }}", "e": 11977, "s": 10908, "text": null }, { "code": null, "e": 12075, "s": 11977, "text": "List1: [Hii, Geeks, for, Geeks]\nList2: [Hii, Geeks, Gaurav]\nCommon elements: [Hii, Geeks, Geeks]\n" }, { "code": null, "e": 12122, "s": 12075, "text": "Program 2: By retaining the contents of List1." }, { "code": "// Java Program to find common elements// in two ArrayLists// Using retainAll() method // import ArrayList packageimport java.util.ArrayList; public class GFG { // main method public static void main(String[] args) { // create ArrayList list1 ArrayList<String> list1 = new ArrayList<String>(); // Add values in ArrayList list1.add(\"Hii\"); list1.add(\"Geeks\"); list1.add(\"for\"); list1.add(\"Geeks\"); // print list 1 System.out.println(\"List1: \" + list1); // Create ArrayList list2 ArrayList<String> list2 = new ArrayList<String>(); // Add values in ArrayList list2.add(\"Hii\"); list2.add(\"Geeks\"); list2.add(\"Gaurav\"); // print list 2 System.out.println(\"List2: \" + list2); // Create ArrayList list3 ArrayList<String> list3 = new ArrayList<String>(list1); // Store the comparison output // in ArrayList list3 list3.retainAll(list2); // print list 3 System.out.println(\"Common elements: \" + list3); }}", "e": 13332, "s": 12122, "text": null }, { "code": null, "e": 13430, "s": 13332, "text": "List1: [Hii, Geeks, for, Geeks]\nList2: [Hii, Geeks, Gaurav]\nCommon elements: [Hii, Geeks, Geeks]\n" }, { "code": null, "e": 15254, "s": 13430, "text": "Using Stream filterSyntax:list1.stream()\n .filter(list2::contains)\n .collect(Collectors\n .toList()));\n\nThis method returns element if found in second list.\nApproach:First create two ArrayList and add values of list.Convert the ArrayList to Stream using stream() method.Set the filter condition to be distinct using contains() method.Collect the filtered values as List using collect() method. This list will be return common element in both list.Print list3Below is the implementation of the above approach:Program:// Java Program to find common elements// in two ArrayLists// Using Stream filter method // import ArrayList packageimport java.util.*;import java.util.stream.*; public class GFG { // main method public static void main(String[] args) { // create ArrayList list1 ArrayList<String> list1 = new ArrayList<String>(); // Add values in ArrayList list1.add(\"Hii\"); list1.add(\"Geeks\"); list1.add(\"for\"); list1.add(\"Geeks\"); // print list 1 System.out.println(\"List1: \" + list1); // Create ArrayList list2 ArrayList<String> list2 = new ArrayList<String>(); // Add values in ArrayList list2.add(\"Hii\"); list2.add(\"Geeks\"); list2.add(\"Gaurav\"); // print list 2 System.out.println(\"List2: \" + list2); // Find common elements System.out.print(\"Common elements: \"); System.out.println(list1.stream() .filter(list2::contains) .collect(Collectors .toList())); }}Output:List1: [Hii, Geeks, for, Geeks]\nList2: [Hii, Geeks, Gaurav]\nCommon elements: [Hii, Geeks, Geeks]\n" }, { "code": null, "e": 15262, "s": 15254, "text": "Syntax:" }, { "code": null, "e": 15402, "s": 15262, "text": "list1.stream()\n .filter(list2::contains)\n .collect(Collectors\n .toList()));\n\nThis method returns element if found in second list.\n" }, { "code": null, "e": 15412, "s": 15402, "text": "Approach:" }, { "code": null, "e": 15705, "s": 15412, "text": "First create two ArrayList and add values of list.Convert the ArrayList to Stream using stream() method.Set the filter condition to be distinct using contains() method.Collect the filtered values as List using collect() method. This list will be return common element in both list.Print list3" }, { "code": null, "e": 15756, "s": 15705, "text": "First create two ArrayList and add values of list." }, { "code": null, "e": 15811, "s": 15756, "text": "Convert the ArrayList to Stream using stream() method." }, { "code": null, "e": 15876, "s": 15811, "text": "Set the filter condition to be distinct using contains() method." }, { "code": null, "e": 15990, "s": 15876, "text": "Collect the filtered values as List using collect() method. This list will be return common element in both list." }, { "code": null, "e": 16002, "s": 15990, "text": "Print list3" }, { "code": null, "e": 16053, "s": 16002, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 16062, "s": 16053, "text": "Program:" }, { "code": "// Java Program to find common elements// in two ArrayLists// Using Stream filter method // import ArrayList packageimport java.util.*;import java.util.stream.*; public class GFG { // main method public static void main(String[] args) { // create ArrayList list1 ArrayList<String> list1 = new ArrayList<String>(); // Add values in ArrayList list1.add(\"Hii\"); list1.add(\"Geeks\"); list1.add(\"for\"); list1.add(\"Geeks\"); // print list 1 System.out.println(\"List1: \" + list1); // Create ArrayList list2 ArrayList<String> list2 = new ArrayList<String>(); // Add values in ArrayList list2.add(\"Hii\"); list2.add(\"Geeks\"); list2.add(\"Gaurav\"); // print list 2 System.out.println(\"List2: \" + list2); // Find common elements System.out.print(\"Common elements: \"); System.out.println(list1.stream() .filter(list2::contains) .collect(Collectors .toList())); }}", "e": 17258, "s": 16062, "text": null }, { "code": null, "e": 17356, "s": 17258, "text": "List1: [Hii, Geeks, for, Geeks]\nList2: [Hii, Geeks, Gaurav]\nCommon elements: [Hii, Geeks, Geeks]\n" }, { "code": null, "e": 19267, "s": 17356, "text": "Naive approach:First create two ArrayList and add values of list.Create a temporary ArrayList to contain common elements.Iterate through the list1 and check if that element is present in the list2 using ArrayList.contains() method.If found, add it to the list3Print the common elements from list3Below is the implementation of the above approach:// Java Program to find common elements// in two ArrayLists// Using Stream filter method // import ArrayList packageimport java.util.ArrayList; public class GFG { // main method public static void main(String[] args) { // create ArrayList list1 ArrayList<String> list1 = new ArrayList<String>(); // Add values in ArrayList list1.add(\"Hii\"); list1.add(\"Geeks\"); list1.add(\"for\"); list1.add(\"Geeks\"); // print list 1 System.out.println(\"List1: \" + list1); // Create ArrayList list2 ArrayList<String> list2 = new ArrayList<String>(); // Add values in ArrayList list2.add(\"Hii\"); list2.add(\"Geeks\"); list2.add(\"Gaurav\"); // print list 2 System.out.println(\"List2: \" + list2); // Create ArrayList list3 ArrayList<String> list3 = new ArrayList<String>(); // Find common elements // while iterating through list1 for (String temp : list1) { // Check if theis element is // present in list2 or not if (list2.contains(temp)) { // Since present, add it to list3 list3.add(temp); } } // print common elements from list 3 System.out.println(\"Common elements: \" + list3); }}Output:List1: [Hii, Geeks, for, Geeks]\nList2: [Hii, Geeks, Gaurav]\nCommon elements: [Hii, Geeks, Geeks]\n" }, { "code": null, "e": 19549, "s": 19267, "text": "First create two ArrayList and add values of list.Create a temporary ArrayList to contain common elements.Iterate through the list1 and check if that element is present in the list2 using ArrayList.contains() method.If found, add it to the list3Print the common elements from list3" }, { "code": null, "e": 19600, "s": 19549, "text": "First create two ArrayList and add values of list." }, { "code": null, "e": 19657, "s": 19600, "text": "Create a temporary ArrayList to contain common elements." }, { "code": null, "e": 19768, "s": 19657, "text": "Iterate through the list1 and check if that element is present in the list2 using ArrayList.contains() method." }, { "code": null, "e": 19798, "s": 19768, "text": "If found, add it to the list3" }, { "code": null, "e": 19835, "s": 19798, "text": "Print the common elements from list3" }, { "code": null, "e": 19886, "s": 19835, "text": "Below is the implementation of the above approach:" }, { "code": "// Java Program to find common elements// in two ArrayLists// Using Stream filter method // import ArrayList packageimport java.util.ArrayList; public class GFG { // main method public static void main(String[] args) { // create ArrayList list1 ArrayList<String> list1 = new ArrayList<String>(); // Add values in ArrayList list1.add(\"Hii\"); list1.add(\"Geeks\"); list1.add(\"for\"); list1.add(\"Geeks\"); // print list 1 System.out.println(\"List1: \" + list1); // Create ArrayList list2 ArrayList<String> list2 = new ArrayList<String>(); // Add values in ArrayList list2.add(\"Hii\"); list2.add(\"Geeks\"); list2.add(\"Gaurav\"); // print list 2 System.out.println(\"List2: \" + list2); // Create ArrayList list3 ArrayList<String> list3 = new ArrayList<String>(); // Find common elements // while iterating through list1 for (String temp : list1) { // Check if theis element is // present in list2 or not if (list2.contains(temp)) { // Since present, add it to list3 list3.add(temp); } } // print common elements from list 3 System.out.println(\"Common elements: \" + list3); }}", "e": 21347, "s": 19886, "text": null }, { "code": null, "e": 21445, "s": 21347, "text": "List1: [Hii, Geeks, for, Geeks]\nList2: [Hii, Geeks, Gaurav]\nCommon elements: [Hii, Geeks, Geeks]\n" }, { "code": null, "e": 21465, "s": 21445, "text": "Java - util package" }, { "code": null, "e": 21482, "s": 21465, "text": "Java-Collections" }, { "code": null, "e": 21501, "s": 21482, "text": "Java-List-Programs" }, { "code": null, "e": 21525, "s": 21501, "text": "Technical Scripter 2018" }, { "code": null, "e": 21530, "s": 21525, "text": "Java" }, { "code": null, "e": 21549, "s": 21530, "text": "Technical Scripter" }, { "code": null, "e": 21554, "s": 21549, "text": "Java" }, { "code": null, "e": 21571, "s": 21554, "text": "Java-Collections" } ]
Scrape Google Search Results using Python BeautifulSoup
29 Dec, 2020 In this article, we are going to see how to Scrape Google Search Results using Python BeautifulSoup. bs4: Beautiful Soup(bs4) is a Python library for pulling data out of HTML and XML files. This module does not come built-in with Python. To install this type the below command in the terminal. pip install bs4 requests: Requests allows you to send HTTP/1.1 requests extremely easily. This module also does not come built-in with Python. To install this type the below command in the terminal. pip install requests Import the beautifulsoup and request libraries. Make two strings with the default Google search URL, ‘https://google.com/search?q=’ and our customized search keyword. Concatenate these two strings to get our search URL. Fetch the URL data using requests.get(url), store it in a variable, request_result. Create a string and store the result of our fetched request, using request_result.text. Now we use BeautifulSoup to analyze the extracted page. We can simply create an object to perform those operations but beautifulsoup comes with a lot of in-built features to scrape the web. We have created a soup object first using beautifulsoup from the request-response We can do soup.find.all(h3) to grab all major headings of our search result, Iterate through the object and print it as a string. Example 1: Below is the implementation of the above approach. Python3 # Import the beautifulsoup # and request libraries of python.import requestsimport bs4 # Make two strings with default google search URL# 'https://google.com/search?q=' and# our customized search keyword.# Concatenate themtext= "geeksforgeeks"url = 'https://google.com/search?q=' + text # Fetch the URL data using requests.get(url),# store it in a variable, request_result.request_result=requests.get( url ) # Creating soup from the fetched requestsoup = bs4.BeautifulSoup(request_result.text, "html.parser")print(soup) Output: Let’s We can do soup.find.all(h3) to grab all major headings of our search result, Iterate through the object and print it as a string. Python3 # soup.find.all( h3 ) to grab # all major headings of our search result,heading_object=soup.find_all( 'h3' ) # Iterate through the object # and print it as a string.for info in heading_object: print(info.getText()) print("------") Output: Example 2: Below is the implementation. In the form of extracting the city temperature using Google search: Python # import moduleimport requests import bs4 # Taking thecity name as an input from the usercity = "Imphal" # Generating the url url = "https://google.com/search?q=weather+in+" + city # Sending HTTP request request_result = requests.get( url ) # Pulling HTTP data from internet soup = bs4.BeautifulSoup( request_result.text , "html.parser" ) # Finding temperature in Celsius.# The temperature is stored inside the class "BNeawe". temp = soup.find( "div" , class_='BNeawe' ).text print( temp ) Output: Python BeautifulSoup Python web-scraping-exercises Technical Scripter 2020 Web-scraping Python Technical Scripter Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to iterate through Excel rows in Python? Deque in Python Defaultdict in Python Queue in Python Rotate axis tick labels in Seaborn and Matplotlib Check if element exists in list in Python Python Classes and Objects Bar Plot in Matplotlib Python OOPs Concepts How To Convert Python Dictionary To JSON?
[ { "code": null, "e": 53, "s": 25, "text": "\n29 Dec, 2020" }, { "code": null, "e": 154, "s": 53, "text": "In this article, we are going to see how to Scrape Google Search Results using Python BeautifulSoup." }, { "code": null, "e": 347, "s": 154, "text": "bs4: Beautiful Soup(bs4) is a Python library for pulling data out of HTML and XML files. This module does not come built-in with Python. To install this type the below command in the terminal." }, { "code": null, "e": 364, "s": 347, "text": "pip install bs4\n" }, { "code": null, "e": 548, "s": 364, "text": "requests: Requests allows you to send HTTP/1.1 requests extremely easily. This module also does not come built-in with Python. To install this type the below command in the terminal." }, { "code": null, "e": 570, "s": 548, "text": "pip install requests\n" }, { "code": null, "e": 618, "s": 570, "text": "Import the beautifulsoup and request libraries." }, { "code": null, "e": 737, "s": 618, "text": "Make two strings with the default Google search URL, ‘https://google.com/search?q=’ and our customized search keyword." }, { "code": null, "e": 790, "s": 737, "text": "Concatenate these two strings to get our search URL." }, { "code": null, "e": 874, "s": 790, "text": "Fetch the URL data using requests.get(url), store it in a variable, request_result." }, { "code": null, "e": 962, "s": 874, "text": "Create a string and store the result of our fetched request, using request_result.text." }, { "code": null, "e": 1234, "s": 962, "text": "Now we use BeautifulSoup to analyze the extracted page. We can simply create an object to perform those operations but beautifulsoup comes with a lot of in-built features to scrape the web. We have created a soup object first using beautifulsoup from the request-response" }, { "code": null, "e": 1365, "s": 1234, "text": " We can do soup.find.all(h3) to grab all major headings of our search result, Iterate through the object and print it as a string." }, { "code": null, "e": 1427, "s": 1365, "text": "Example 1: Below is the implementation of the above approach." }, { "code": null, "e": 1435, "s": 1427, "text": "Python3" }, { "code": "# Import the beautifulsoup # and request libraries of python.import requestsimport bs4 # Make two strings with default google search URL# 'https://google.com/search?q=' and# our customized search keyword.# Concatenate themtext= \"geeksforgeeks\"url = 'https://google.com/search?q=' + text # Fetch the URL data using requests.get(url),# store it in a variable, request_result.request_result=requests.get( url ) # Creating soup from the fetched requestsoup = bs4.BeautifulSoup(request_result.text, \"html.parser\")print(soup)", "e": 1982, "s": 1435, "text": null }, { "code": null, "e": 1990, "s": 1982, "text": "Output:" }, { "code": null, "e": 2126, "s": 1990, "text": "Let’s We can do soup.find.all(h3) to grab all major headings of our search result, Iterate through the object and print it as a string." }, { "code": null, "e": 2134, "s": 2126, "text": "Python3" }, { "code": "# soup.find.all( h3 ) to grab # all major headings of our search result,heading_object=soup.find_all( 'h3' ) # Iterate through the object # and print it as a string.for info in heading_object: print(info.getText()) print(\"------\")", "e": 2372, "s": 2134, "text": null }, { "code": null, "e": 2380, "s": 2372, "text": "Output:" }, { "code": null, "e": 2488, "s": 2380, "text": "Example 2: Below is the implementation. In the form of extracting the city temperature using Google search:" }, { "code": null, "e": 2495, "s": 2488, "text": "Python" }, { "code": "# import moduleimport requests import bs4 # Taking thecity name as an input from the usercity = \"Imphal\" # Generating the url url = \"https://google.com/search?q=weather+in+\" + city # Sending HTTP request request_result = requests.get( url ) # Pulling HTTP data from internet soup = bs4.BeautifulSoup( request_result.text , \"html.parser\" ) # Finding temperature in Celsius.# The temperature is stored inside the class \"BNeawe\". temp = soup.find( \"div\" , class_='BNeawe' ).text print( temp ) ", "e": 3022, "s": 2495, "text": null }, { "code": null, "e": 3030, "s": 3022, "text": "Output:" }, { "code": null, "e": 3051, "s": 3030, "text": "Python BeautifulSoup" }, { "code": null, "e": 3081, "s": 3051, "text": "Python web-scraping-exercises" }, { "code": null, "e": 3105, "s": 3081, "text": "Technical Scripter 2020" }, { "code": null, "e": 3118, "s": 3105, "text": "Web-scraping" }, { "code": null, "e": 3125, "s": 3118, "text": "Python" }, { "code": null, "e": 3144, "s": 3125, "text": "Technical Scripter" }, { "code": null, "e": 3242, "s": 3144, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3287, "s": 3242, "text": "How to iterate through Excel rows in Python?" }, { "code": null, "e": 3303, "s": 3287, "text": "Deque in Python" }, { "code": null, "e": 3325, "s": 3303, "text": "Defaultdict in Python" }, { "code": null, "e": 3341, "s": 3325, "text": "Queue in Python" }, { "code": null, "e": 3391, "s": 3341, "text": "Rotate axis tick labels in Seaborn and Matplotlib" }, { "code": null, "e": 3433, "s": 3391, "text": "Check if element exists in list in Python" }, { "code": null, "e": 3460, "s": 3433, "text": "Python Classes and Objects" }, { "code": null, "e": 3483, "s": 3460, "text": "Bar Plot in Matplotlib" }, { "code": null, "e": 3504, "s": 3483, "text": "Python OOPs Concepts" } ]
Ruby | Array size() operation
06 Dec, 2019 Array#size() : size() is a Array class method which returns the length of elements in the array. Syntax: Array.size() Parameter: Array Return: the length of elements in the array. Example #1 : # Ruby code for size() method # declaring arraya = [18, 22, 33, nil, 5, 6] # declaring arrayb = [1, 4, 1, 1, 88, 9] # declaring arrayc = [18, 22, 50, 6] # size method exampleputs "size() method form : #{a.size()}\n\n" puts "size() method form : #{b.size()}\n\n" puts "size() method form : #{c.size()}\n\n" Output : size() method form : 6 size() method form : 6 size() method form : 4 Example #2 : # Ruby code for size() method # declaring arraya = ["abc", "nil", "dog"] # declaring arrayc = ["cat", nil] # declaring arrayb = ["cow", nil, "dog"] # size method exampleputs "size() method form : #{a.size()}\n\n" puts "size() method form : #{b.size()}\n\n" puts "size() method form : #{c.size()}\n\n" Output : size() method form : 3 size() method form : 3 size() method form : 2 Ruby Array-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": "\n06 Dec, 2019" }, { "code": null, "e": 125, "s": 28, "text": "Array#size() : size() is a Array class method which returns the length of elements in the array." }, { "code": null, "e": 146, "s": 125, "text": "Syntax: Array.size()" }, { "code": null, "e": 163, "s": 146, "text": "Parameter: Array" }, { "code": null, "e": 208, "s": 163, "text": "Return: the length of elements in the array." }, { "code": null, "e": 221, "s": 208, "text": "Example #1 :" }, { "code": "# Ruby code for size() method # declaring arraya = [18, 22, 33, nil, 5, 6] # declaring arrayb = [1, 4, 1, 1, 88, 9] # declaring arrayc = [18, 22, 50, 6] # size method exampleputs \"size() method form : #{a.size()}\\n\\n\" puts \"size() method form : #{b.size()}\\n\\n\" puts \"size() method form : #{c.size()}\\n\\n\"", "e": 533, "s": 221, "text": null }, { "code": null, "e": 542, "s": 533, "text": "Output :" }, { "code": null, "e": 615, "s": 542, "text": "size() method form : 6\n\nsize() method form : 6\n\nsize() method form : 4\n\n" }, { "code": null, "e": 628, "s": 615, "text": "Example #2 :" }, { "code": "# Ruby code for size() method # declaring arraya = [\"abc\", \"nil\", \"dog\"] # declaring arrayc = [\"cat\", nil] # declaring arrayb = [\"cow\", nil, \"dog\"] # size method exampleputs \"size() method form : #{a.size()}\\n\\n\" puts \"size() method form : #{b.size()}\\n\\n\" puts \"size() method form : #{c.size()}\\n\\n\"", "e": 937, "s": 628, "text": null }, { "code": null, "e": 946, "s": 937, "text": "Output :" }, { "code": null, "e": 1019, "s": 946, "text": "size() method form : 3\n\nsize() method form : 3\n\nsize() method form : 2\n\n" }, { "code": null, "e": 1036, "s": 1019, "text": "Ruby Array-class" }, { "code": null, "e": 1049, "s": 1036, "text": "Ruby-Methods" }, { "code": null, "e": 1054, "s": 1049, "text": "Ruby" } ]
Sum of square-sums of first n natural numbers
01 Sep, 2021 Given a positive integer n. The task is to find the sum of the sum of square of first n natural number. Examples : Input : n = 3 Output : 20 Sum of square of first natural number = 1 Sum of square of first two natural number = 1^2 + 2^2 = 5 Sum of square of first three natural number = 1^2 + 2^2 + 3^2 = 14 Sum of sum of square of first three natural number = 1 + 5 + 14 = 20 Input : n = 2 Output : 6 Method 1: O(n) The idea is to find sum of square of first i natural number, where 1 <= i <= n. And them add them all. We can find sum of squares of first n natural number by formula: n * (n + 1)* (2*n + 1)/6Below is the implementation of this approach: C++ Java Python3 C# PHP Javascript // CPP Program to find the sum of sum of// squares of first n natural number#include <bits/stdc++.h>using namespace std; // Function to find sum of sum of square of// first n natural numberint findSum(int n){ int sum = 0; for (int i = 1; i <= n; i++) sum += ((i * (i + 1) * (2 * i + 1)) / 6); return sum;} // Driven Programint main(){ int n = 3; cout << findSum(n) << endl; return 0;} // Java Program to find the sum of// sum of squares of first n natural// number class GFG { // Function to find sum of sum of // square of first n natural number static int findSum(int n) { int sum = 0; for (int i = 1; i <= n; i++) sum += ((i * (i + 1) * (2 * i + 1)) / 6); return sum; } // Driver Program public static void main(String[] args) { int n = 3; System.out.println( findSum(n)); }} // This code is contributed by// Arnab Kundu # Python3 Program to find the sum# of sum of squares of first n# natural number # Function to find sum of sum of# square of first n natural numberdef findSum(n): summ = 0 for i in range(1, n+1): summ = (summ + ((i * (i + 1) * (2 * i + 1)) / 6)) return summ # Driven Programn = 3print(int(findSum(n))) # This code is contributed by# Prasad Kshirsagar // C# Program to find the sum of sum of// squares of first n natural numberusing System; public class GFG { // Function to find sum of sum of // square of first n natural number static int findSum(int n) { int sum = 0; for (int i = 1; i <= n; i++) sum += ((i * (i + 1) * (2 * i + 1)) / 6); return sum; } // Driver Program static public void Main() { int n = 3; Console.WriteLine(findSum(n)); }} // This code is contributed by// Arnab Kundu. <?php// PHP Program to find the sum of// squares of first n natural number // Function to find sum of sum of// square of first n natural numberfunction findSum( $n){ $sum = 0; for ($i = 1; $i <= $n; $i++) $sum += (($i * ($i + 1) * (2 * $i + 1)) / 6); return $sum;} // Driver Code$n = 3;echo findSum($n) ; // This code is contributed by anuj_67.?> <script> // Javascript Program to find the sum of sum of// squares of first n natural number // Function to find sum of sum of square// of first n natural numberfunction findSum(n){ return (n * (n + 1) * (n + 1) * (n + 2)) / 12;} // Driven Program let n = 3; document.write(findSum(n) + "<br>"); // This code is contributed by Mayank Tyagi </script> 20 Time Complexity : O(n) Auxiliary Space : O(1)Method 2: O(1) Mathematically, we need to find, Σ ((i * (i + 1) * (2*i + 1)/6), where 1 <= i <= n So, lets solve this summation, Sum = Σ ((i * (i + 1) * (2*i + 1)/6), where 1 <= i <= n = (1/6)*(Σ ((i * (i + 1) * (2*i + 1))) = (1/6)*(Σ ((i2 + i) * (2*i + 1)) = (1/6)*(Σ ((2*i3 + 3*i2 + i)) = (1/6)*(Σ 2*i3 + Σ 3*i2 + Σ i) = (1/6)*(2*Σ i3 + 3*Σ i2 + Σ i) = (1/6)*(2*(i*(i + 1)/2)2 + 3*(i * (i + 1) * (2*i + 1))/6 + i * (i + 1)/2) = (1/6)*(i * (i + 1))((i*(i + 1)/2) + ((2*i + 1)/2) + 1/2) = (1/12) * (i * (i + 1)) * ((i*(i + 1)) + (2*i + 1) + 1) = (1/12) * (i * (i + 1)) * ((i2 + 3 * i + 2) = (1/12) * (i * (i + 1)) * ((i + 1) * (i + 2)) = (1/12) * (i * (i + 1)2 * (i + 2)) Below is the implementation of this approach: C++ Java Python3 C# PHP Javascript // CPP Program to find the sum of sum of// squares of first n natural number#include <bits/stdc++.h>using namespace std; // Function to find sum of sum of square// of first n natural numberint findSum(int n){ return (n * (n + 1) * (n + 1) * (n + 2)) / 12;} // Driven Programint main(){ int n = 3; cout << findSum(n) << endl; return 0;} // Java Program to find the sum of sum of// squares of first n natural numberclass GFG { // Function to find sum of sum of // square of first n natural number static int findSum(int n) { return (n * (n + 1) * (n + 1) * (n + 2)) / 12; } // Driver Program public static void main(String[] args) { int n = 3; System.out.println(findSum(n) ); }} // This code is contributed by Arnab Kundu # Python3 Program to find the sum# of sum of squares of first n# natural number # Function to find sum of sum of# square of first n natural numberdef findSum(n): return ((n * (n + 1) * (n + 1) * (n + 2)) / 12) # Driven Programn = 3print(int(findSum(n))) # This code is contributed by# Prasad Kshirsagar // C# Program to find the sum of sum of// squares of first n natural numberusing System; class GFG { // Function to find sum of sum of // square of first n natural number static int findSum(int n) { return (n * (n + 1) * (n + 1) * (n + 2)) / 12; } // Driver Program static public void Main() { int n = 3; Console.WriteLine(findSum(n) ); }} // This code is contributed by Arnab Kundu <?php// PHP Program to find the sum of sum of// squares of first n natural number // Function to find sum of sum of square// of first n natural numberfunction findSum($n){ return ($n * ($n + 1) * ($n + 1) * ($n + 2)) / 12;} // Driver Code $n = 3; echo findSum($n) ; // This code is contributed by nitin mittal?> <script>// js Program to find the sum of sum of// squares of first n natural number // Function to find sum of sum of square// of first n natural numberfunction findSum($n){ return (n * (n + 1) *(n + 1) * (n + 2)) / 12;} // Driver Code n = 3; document.write(findSum(n)) ; // This code is contributed by sravan kumar</script> 20 Time Complexity : O(1) Auxiliary Space : O(1) andrew1234 nitin mittal Prasad_Kshirsagar vt_m mayanktyagi1709 sravankumar8128 kalrap615 series series-sum Mathematical Mathematical series Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Algorithm to solve Rubik's Cube Merge two sorted arrays with O(1) extra space Program to print prime numbers from 1 to N. Segment Tree | Set 1 (Sum of given range) Check if a number is Palindrome Count ways to reach the n'th stair Fizz Buzz Implementation Median of two sorted arrays of same size Product of Array except itself Find Union and Intersection of two unsorted arrays
[ { "code": null, "e": 28, "s": 0, "text": "\n01 Sep, 2021" }, { "code": null, "e": 145, "s": 28, "text": "Given a positive integer n. The task is to find the sum of the sum of square of first n natural number. Examples : " }, { "code": null, "e": 433, "s": 145, "text": "Input : n = 3\nOutput : 20\nSum of square of first natural number = 1\nSum of square of first two natural number = 1^2 + 2^2 = 5\nSum of square of first three natural number = 1^2 + 2^2 + 3^2 = 14\nSum of sum of square of first three natural number = 1 + 5 + 14 = 20\n\nInput : n = 2\nOutput : 6" }, { "code": null, "e": 690, "s": 435, "text": "Method 1: O(n) The idea is to find sum of square of first i natural number, where 1 <= i <= n. And them add them all. We can find sum of squares of first n natural number by formula: n * (n + 1)* (2*n + 1)/6Below is the implementation of this approach: " }, { "code": null, "e": 694, "s": 690, "text": "C++" }, { "code": null, "e": 699, "s": 694, "text": "Java" }, { "code": null, "e": 707, "s": 699, "text": "Python3" }, { "code": null, "e": 710, "s": 707, "text": "C#" }, { "code": null, "e": 714, "s": 710, "text": "PHP" }, { "code": null, "e": 725, "s": 714, "text": "Javascript" }, { "code": "// CPP Program to find the sum of sum of// squares of first n natural number#include <bits/stdc++.h>using namespace std; // Function to find sum of sum of square of// first n natural numberint findSum(int n){ int sum = 0; for (int i = 1; i <= n; i++) sum += ((i * (i + 1) * (2 * i + 1)) / 6); return sum;} // Driven Programint main(){ int n = 3; cout << findSum(n) << endl; return 0;}", "e": 1135, "s": 725, "text": null }, { "code": "// Java Program to find the sum of// sum of squares of first n natural// number class GFG { // Function to find sum of sum of // square of first n natural number static int findSum(int n) { int sum = 0; for (int i = 1; i <= n; i++) sum += ((i * (i + 1) * (2 * i + 1)) / 6); return sum; } // Driver Program public static void main(String[] args) { int n = 3; System.out.println( findSum(n)); }} // This code is contributed by// Arnab Kundu", "e": 1677, "s": 1135, "text": null }, { "code": "# Python3 Program to find the sum# of sum of squares of first n# natural number # Function to find sum of sum of# square of first n natural numberdef findSum(n): summ = 0 for i in range(1, n+1): summ = (summ + ((i * (i + 1) * (2 * i + 1)) / 6)) return summ # Driven Programn = 3print(int(findSum(n))) # This code is contributed by# Prasad Kshirsagar", "e": 2059, "s": 1677, "text": null }, { "code": "// C# Program to find the sum of sum of// squares of first n natural numberusing System; public class GFG { // Function to find sum of sum of // square of first n natural number static int findSum(int n) { int sum = 0; for (int i = 1; i <= n; i++) sum += ((i * (i + 1) * (2 * i + 1)) / 6); return sum; } // Driver Program static public void Main() { int n = 3; Console.WriteLine(findSum(n)); }} // This code is contributed by// Arnab Kundu.", "e": 2609, "s": 2059, "text": null }, { "code": "<?php// PHP Program to find the sum of// squares of first n natural number // Function to find sum of sum of// square of first n natural numberfunction findSum( $n){ $sum = 0; for ($i = 1; $i <= $n; $i++) $sum += (($i * ($i + 1) * (2 * $i + 1)) / 6); return $sum;} // Driver Code$n = 3;echo findSum($n) ; // This code is contributed by anuj_67.?>", "e": 2988, "s": 2609, "text": null }, { "code": "<script> // Javascript Program to find the sum of sum of// squares of first n natural number // Function to find sum of sum of square// of first n natural numberfunction findSum(n){ return (n * (n + 1) * (n + 1) * (n + 2)) / 12;} // Driven Program let n = 3; document.write(findSum(n) + \"<br>\"); // This code is contributed by Mayank Tyagi </script>", "e": 3349, "s": 2988, "text": null }, { "code": null, "e": 3352, "s": 3349, "text": "20" }, { "code": null, "e": 3530, "s": 3354, "text": "Time Complexity : O(n) Auxiliary Space : O(1)Method 2: O(1) Mathematically, we need to find, Σ ((i * (i + 1) * (2*i + 1)/6), where 1 <= i <= n So, lets solve this summation, " }, { "code": null, "e": 4117, "s": 3530, "text": "Sum = Σ ((i * (i + 1) * (2*i + 1)/6), where 1 <= i <= n\n = (1/6)*(Σ ((i * (i + 1) * (2*i + 1)))\n = (1/6)*(Σ ((i2 + i) * (2*i + 1))\n = (1/6)*(Σ ((2*i3 + 3*i2 + i))\n = (1/6)*(Σ 2*i3 + Σ 3*i2 + Σ i)\n = (1/6)*(2*Σ i3 + 3*Σ i2 + Σ i)\n = (1/6)*(2*(i*(i + 1)/2)2 + 3*(i * (i + 1) * (2*i + 1))/6 + i * (i + 1)/2)\n = (1/6)*(i * (i + 1))((i*(i + 1)/2) + ((2*i + 1)/2) + 1/2)\n = (1/12) * (i * (i + 1)) * ((i*(i + 1)) + (2*i + 1) + 1)\n = (1/12) * (i * (i + 1)) * ((i2 + 3 * i + 2)\n = (1/12) * (i * (i + 1)) * ((i + 1) * (i + 2))\n = (1/12) * (i * (i + 1)2 * (i + 2))" }, { "code": null, "e": 4165, "s": 4117, "text": "Below is the implementation of this approach: " }, { "code": null, "e": 4169, "s": 4165, "text": "C++" }, { "code": null, "e": 4174, "s": 4169, "text": "Java" }, { "code": null, "e": 4182, "s": 4174, "text": "Python3" }, { "code": null, "e": 4185, "s": 4182, "text": "C#" }, { "code": null, "e": 4189, "s": 4185, "text": "PHP" }, { "code": null, "e": 4200, "s": 4189, "text": "Javascript" }, { "code": "// CPP Program to find the sum of sum of// squares of first n natural number#include <bits/stdc++.h>using namespace std; // Function to find sum of sum of square// of first n natural numberint findSum(int n){ return (n * (n + 1) * (n + 1) * (n + 2)) / 12;} // Driven Programint main(){ int n = 3; cout << findSum(n) << endl; return 0;}", "e": 4548, "s": 4200, "text": null }, { "code": "// Java Program to find the sum of sum of// squares of first n natural numberclass GFG { // Function to find sum of sum of // square of first n natural number static int findSum(int n) { return (n * (n + 1) * (n + 1) * (n + 2)) / 12; } // Driver Program public static void main(String[] args) { int n = 3; System.out.println(findSum(n) ); }} // This code is contributed by Arnab Kundu", "e": 5003, "s": 4548, "text": null }, { "code": "# Python3 Program to find the sum# of sum of squares of first n# natural number # Function to find sum of sum of# square of first n natural numberdef findSum(n): return ((n * (n + 1) * (n + 1) * (n + 2)) / 12) # Driven Programn = 3print(int(findSum(n))) # This code is contributed by# Prasad Kshirsagar", "e": 5325, "s": 5003, "text": null }, { "code": "// C# Program to find the sum of sum of// squares of first n natural numberusing System; class GFG { // Function to find sum of sum of // square of first n natural number static int findSum(int n) { return (n * (n + 1) * (n + 1) * (n + 2)) / 12; } // Driver Program static public void Main() { int n = 3; Console.WriteLine(findSum(n) ); }} // This code is contributed by Arnab Kundu", "e": 5791, "s": 5325, "text": null }, { "code": "<?php// PHP Program to find the sum of sum of// squares of first n natural number // Function to find sum of sum of square// of first n natural numberfunction findSum($n){ return ($n * ($n + 1) * ($n + 1) * ($n + 2)) / 12;} // Driver Code $n = 3; echo findSum($n) ; // This code is contributed by nitin mittal?>", "e": 6144, "s": 5791, "text": null }, { "code": "<script>// js Program to find the sum of sum of// squares of first n natural number // Function to find sum of sum of square// of first n natural numberfunction findSum($n){ return (n * (n + 1) *(n + 1) * (n + 2)) / 12;} // Driver Code n = 3; document.write(findSum(n)) ; // This code is contributed by sravan kumar</script>", "e": 6482, "s": 6144, "text": null }, { "code": null, "e": 6485, "s": 6482, "text": "20" }, { "code": null, "e": 6534, "s": 6487, "text": "Time Complexity : O(1) Auxiliary Space : O(1) " }, { "code": null, "e": 6545, "s": 6534, "text": "andrew1234" }, { "code": null, "e": 6558, "s": 6545, "text": "nitin mittal" }, { "code": null, "e": 6576, "s": 6558, "text": "Prasad_Kshirsagar" }, { "code": null, "e": 6581, "s": 6576, "text": "vt_m" }, { "code": null, "e": 6597, "s": 6581, "text": "mayanktyagi1709" }, { "code": null, "e": 6613, "s": 6597, "text": "sravankumar8128" }, { "code": null, "e": 6623, "s": 6613, "text": "kalrap615" }, { "code": null, "e": 6630, "s": 6623, "text": "series" }, { "code": null, "e": 6641, "s": 6630, "text": "series-sum" }, { "code": null, "e": 6654, "s": 6641, "text": "Mathematical" }, { "code": null, "e": 6667, "s": 6654, "text": "Mathematical" }, { "code": null, "e": 6674, "s": 6667, "text": "series" }, { "code": null, "e": 6772, "s": 6674, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 6804, "s": 6772, "text": "Algorithm to solve Rubik's Cube" }, { "code": null, "e": 6850, "s": 6804, "text": "Merge two sorted arrays with O(1) extra space" }, { "code": null, "e": 6894, "s": 6850, "text": "Program to print prime numbers from 1 to N." }, { "code": null, "e": 6936, "s": 6894, "text": "Segment Tree | Set 1 (Sum of given range)" }, { "code": null, "e": 6968, "s": 6936, "text": "Check if a number is Palindrome" }, { "code": null, "e": 7003, "s": 6968, "text": "Count ways to reach the n'th stair" }, { "code": null, "e": 7028, "s": 7003, "text": "Fizz Buzz Implementation" }, { "code": null, "e": 7069, "s": 7028, "text": "Median of two sorted arrays of same size" }, { "code": null, "e": 7100, "s": 7069, "text": "Product of Array except itself" } ]
Parameter-Ordered Updates
The UPDATE query of raw SQL has SET clause. It is rendered by the update() construct using the column ordering given in the originating Table object. Therefore, a particular UPDATE statement with particular columns will be rendered the same each time. Since the parameters themselves are passed to the Update.values() method as Python dictionary keys, there is no other fixed ordering available. In some cases, the order of parameters rendered in the SET clause are significant. In MySQL, providing updates to column values is based on that of other column values. Following statement’s result − UPDATE table1 SET x = y + 10, y = 20 will have a different result than − UPDATE table1 SET y = 20, x = y + 10 SET clause in MySQL is evaluated on a per-value basis and not on per-row basis. For this purpose, the preserve_parameter_order is used. Python list of 2-tuples is given as argument to the Update.values() method − stmt = table1.update(preserve_parameter_order = True).\ values([(table1.c.y, 20), (table1.c.x, table1.c.y + 10)]) The List object is similar to dictionary except that it is ordered. This ensures that the “y” column’s SET clause will render first, then the “x” column’s SET clause.
[ { "code": null, "e": 2870, "s": 2474, "text": "The UPDATE query of raw SQL has SET clause. It is rendered by the update() construct using the column ordering given in the originating Table object. Therefore, a particular UPDATE statement with particular columns will be rendered the same each time. Since the parameters themselves are passed to the Update.values() method as Python dictionary keys, there is no other fixed ordering available." }, { "code": null, "e": 3039, "s": 2870, "text": "In some cases, the order of parameters rendered in the SET clause are significant. In MySQL, providing updates to column values is based on that of other column values." }, { "code": null, "e": 3070, "s": 3039, "text": "Following statement’s result −" }, { "code": null, "e": 3107, "s": 3070, "text": "UPDATE table1 SET x = y + 10, y = 20" }, { "code": null, "e": 3143, "s": 3107, "text": "will have a different result than −" }, { "code": null, "e": 3180, "s": 3143, "text": "UPDATE table1 SET y = 20, x = y + 10" }, { "code": null, "e": 3393, "s": 3180, "text": "SET clause in MySQL is evaluated on a per-value basis and not on per-row basis. For this purpose, the preserve_parameter_order is used. Python list of 2-tuples is given as argument to the Update.values() method −" }, { "code": null, "e": 3510, "s": 3393, "text": "stmt = table1.update(preserve_parameter_order = True).\\\n values([(table1.c.y, 20), (table1.c.x, table1.c.y + 10)])" } ]
p5.js | loadImage() Function
17 Jan, 2020 The loadImage() function is used to load an image from the given path and create a p5.Image object with the image. It is advised to load an image in the preload() function as the loaded image may not be available for use immediately. The image is preferably loaded from a relative path as some browsers may prevent loading from other remote locations due to the browser’s security features. Syntax: loadImage(path, successCallback, failureCallback) Parameters: This function accepts three parameter as mentioned above and described below. path: This is the path from where the image is to be loaded. successCallback: This is a function which is called if the image successfully loads and it is an optional parameter. failureCallback: This is a function which is called if the image does not load due to any error and it is an optional parameter. Below examples illustrates the loadImage() function in p5.js: Example 1: This example shows the loading of image in preload(). let img; function preload() { img = loadImage('sample-image.png');} function setup() { createCanvas(300, 200); text("The image would be loaded below:", 20, 20); image(img, 20, 40, 100, 100);} Output: Example 2: This example shows loading an image from a URL and both callbacks that may take place. let img;let url = 'https://media.geeksforgeeks.org/wp-content/uploads/20190314004249/sample-image.png'; function setup() { createCanvas(400, 200); textSize(18) text("The image would be loaded below:", 20, 20); loadImage(url, img => { image(img, 20, 40, 100, 100); }, (event) => { fill("red") text("Error: The image could not be loaded.", 20, 40); console.log(event); } );} Output: Image successfully loads Image does not load Online editor: https://editor.p5js.org/Environment Setup: https://www.geeksforgeeks.org/p5-js-soundfile-object-installation-and-methods/ Reference: https://p5js.org/reference/#/p5/loadImage JavaScript-p5.js JavaScript Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n17 Jan, 2020" }, { "code": null, "e": 143, "s": 28, "text": "The loadImage() function is used to load an image from the given path and create a p5.Image object with the image." }, { "code": null, "e": 419, "s": 143, "text": "It is advised to load an image in the preload() function as the loaded image may not be available for use immediately. The image is preferably loaded from a relative path as some browsers may prevent loading from other remote locations due to the browser’s security features." }, { "code": null, "e": 427, "s": 419, "text": "Syntax:" }, { "code": null, "e": 477, "s": 427, "text": "loadImage(path, successCallback, failureCallback)" }, { "code": null, "e": 567, "s": 477, "text": "Parameters: This function accepts three parameter as mentioned above and described below." }, { "code": null, "e": 628, "s": 567, "text": "path: This is the path from where the image is to be loaded." }, { "code": null, "e": 745, "s": 628, "text": "successCallback: This is a function which is called if the image successfully loads and it is an optional parameter." }, { "code": null, "e": 874, "s": 745, "text": "failureCallback: This is a function which is called if the image does not load due to any error and it is an optional parameter." }, { "code": null, "e": 936, "s": 874, "text": "Below examples illustrates the loadImage() function in p5.js:" }, { "code": null, "e": 1001, "s": 936, "text": "Example 1: This example shows the loading of image in preload()." }, { "code": "let img; function preload() { img = loadImage('sample-image.png');} function setup() { createCanvas(300, 200); text(\"The image would be loaded below:\", 20, 20); image(img, 20, 40, 100, 100);}", "e": 1201, "s": 1001, "text": null }, { "code": null, "e": 1209, "s": 1201, "text": "Output:" }, { "code": null, "e": 1307, "s": 1209, "text": "Example 2: This example shows loading an image from a URL and both callbacks that may take place." }, { "code": "let img;let url = 'https://media.geeksforgeeks.org/wp-content/uploads/20190314004249/sample-image.png'; function setup() { createCanvas(400, 200); textSize(18) text(\"The image would be loaded below:\", 20, 20); loadImage(url, img => { image(img, 20, 40, 100, 100); }, (event) => { fill(\"red\") text(\"Error: The image could not be loaded.\", 20, 40); console.log(event); } );}", "e": 1715, "s": 1307, "text": null }, { "code": null, "e": 1723, "s": 1715, "text": "Output:" }, { "code": null, "e": 1748, "s": 1723, "text": "Image successfully loads" }, { "code": null, "e": 1768, "s": 1748, "text": "Image does not load" }, { "code": null, "e": 1905, "s": 1768, "text": "Online editor: https://editor.p5js.org/Environment Setup: https://www.geeksforgeeks.org/p5-js-soundfile-object-installation-and-methods/" }, { "code": null, "e": 1958, "s": 1905, "text": "Reference: https://p5js.org/reference/#/p5/loadImage" }, { "code": null, "e": 1975, "s": 1958, "text": "JavaScript-p5.js" }, { "code": null, "e": 1986, "s": 1975, "text": "JavaScript" }, { "code": null, "e": 2003, "s": 1986, "text": "Web Technologies" } ]
Shading confidence intervals manually with ggplot2 in R
30 Jun, 2021 In this article, we will see how to generate Shading confidence intervals manually with ggplot2 in R Programming language. Let us first draw a regular curve and then add confidence intervals to it. Example: R # Load Packageslibrary("ggplot2") # Create a DataFrame for PlottingDF <- data.frame(X = rnorm(10), Y = rnorm(10)) # Plot the ggplot2 plotggplot(DF, aes(X, Y)) + geom_line(color = "dark green", size = 2) Output: LineGraph using ggplot2 To add shading confidence intervals, geom_ribbon() function is used. Which displays a Y interval defined by ymin and ymax. It has aesthetic mappings of ymin and ymax. Other than that it also has some more parameters which are not necessary. Syntax : geom_ribbon(mapping, color, fill, linetype, alpha, ...) Parameters : mapping : aesthetic created by aes() to define ymin and ymax. color : Specifies the color of border of the Shading interval. fill : Specifies the color of Shading Confidence Interval. linetype : Specifies the linetype of the border of Confidence Interval. alpha : Specifies the Opacity of the Shading Interval. ... : geom_ribbon also has other parameters such as data, stat, position, show.legend, etc. You can use them as per your requirements but in general case they are not useful as much. Return : Y interval with the specified range. Example: R # Load Packageslibrary("ggplot2") # Create DataFrame for PlottingDF <- data.frame(X = rnorm(10), Y = rnorm(10)) # ggplot2 LineGraph with Shading Confidence Intervalggplot(DF, aes(X, Y)) + geom_line(color = "dark green", size = 2) + geom_ribbon(aes(ymin=Y+0.5, ymax=Y-0.5), alpha=0.1, fill = "green", color = "black", linetype = "dotted") Output: LineGraph with shading confidence intervals Picked R-ggplot R Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Change Color of Bars in Barchart using ggplot2 in R How to Split Column Into Multiple Columns in R DataFrame? Group by function in R using Dplyr How to Change Axis Scales in R Plots? R - if statement How to filter R DataFrame by values in a column? Logistic Regression in R Programming Replace Specific Characters in String in R How to import an Excel File into R ? Joining of Dataframes in R Programming
[ { "code": null, "e": 28, "s": 0, "text": "\n30 Jun, 2021" }, { "code": null, "e": 152, "s": 28, "text": "In this article, we will see how to generate Shading confidence intervals manually with ggplot2 in R Programming language. " }, { "code": null, "e": 227, "s": 152, "text": "Let us first draw a regular curve and then add confidence intervals to it." }, { "code": null, "e": 236, "s": 227, "text": "Example:" }, { "code": null, "e": 238, "s": 236, "text": "R" }, { "code": "# Load Packageslibrary(\"ggplot2\") # Create a DataFrame for PlottingDF <- data.frame(X = rnorm(10), Y = rnorm(10)) # Plot the ggplot2 plotggplot(DF, aes(X, Y)) + geom_line(color = \"dark green\", size = 2)", "e": 533, "s": 238, "text": null }, { "code": null, "e": 541, "s": 533, "text": "Output:" }, { "code": null, "e": 565, "s": 541, "text": "LineGraph using ggplot2" }, { "code": null, "e": 807, "s": 565, "text": "To add shading confidence intervals, geom_ribbon() function is used. Which displays a Y interval defined by ymin and ymax. It has aesthetic mappings of ymin and ymax. Other than that it also has some more parameters which are not necessary. " }, { "code": null, "e": 872, "s": 807, "text": "Syntax : geom_ribbon(mapping, color, fill, linetype, alpha, ...)" }, { "code": null, "e": 885, "s": 872, "text": "Parameters :" }, { "code": null, "e": 947, "s": 885, "text": "mapping : aesthetic created by aes() to define ymin and ymax." }, { "code": null, "e": 1010, "s": 947, "text": "color : Specifies the color of border of the Shading interval." }, { "code": null, "e": 1069, "s": 1010, "text": "fill : Specifies the color of Shading Confidence Interval." }, { "code": null, "e": 1141, "s": 1069, "text": "linetype : Specifies the linetype of the border of Confidence Interval." }, { "code": null, "e": 1196, "s": 1141, "text": "alpha : Specifies the Opacity of the Shading Interval." }, { "code": null, "e": 1379, "s": 1196, "text": "... : geom_ribbon also has other parameters such as data, stat, position, show.legend, etc. You can use them as per your requirements but in general case they are not useful as much." }, { "code": null, "e": 1425, "s": 1379, "text": "Return : Y interval with the specified range." }, { "code": null, "e": 1434, "s": 1425, "text": "Example:" }, { "code": null, "e": 1436, "s": 1434, "text": "R" }, { "code": "# Load Packageslibrary(\"ggplot2\") # Create DataFrame for PlottingDF <- data.frame(X = rnorm(10), Y = rnorm(10)) # ggplot2 LineGraph with Shading Confidence Intervalggplot(DF, aes(X, Y)) + geom_line(color = \"dark green\", size = 2) + geom_ribbon(aes(ymin=Y+0.5, ymax=Y-0.5), alpha=0.1, fill = \"green\", color = \"black\", linetype = \"dotted\")", "e": 1881, "s": 1436, "text": null }, { "code": null, "e": 1889, "s": 1881, "text": "Output:" }, { "code": null, "e": 1933, "s": 1889, "text": "LineGraph with shading confidence intervals" }, { "code": null, "e": 1940, "s": 1933, "text": "Picked" }, { "code": null, "e": 1949, "s": 1940, "text": "R-ggplot" }, { "code": null, "e": 1960, "s": 1949, "text": "R Language" }, { "code": null, "e": 2058, "s": 1960, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2110, "s": 2058, "text": "Change Color of Bars in Barchart using ggplot2 in R" }, { "code": null, "e": 2168, "s": 2110, "text": "How to Split Column Into Multiple Columns in R DataFrame?" }, { "code": null, "e": 2203, "s": 2168, "text": "Group by function in R using Dplyr" }, { "code": null, "e": 2241, "s": 2203, "text": "How to Change Axis Scales in R Plots?" }, { "code": null, "e": 2258, "s": 2241, "text": "R - if statement" }, { "code": null, "e": 2307, "s": 2258, "text": "How to filter R DataFrame by values in a column?" }, { "code": null, "e": 2344, "s": 2307, "text": "Logistic Regression in R Programming" }, { "code": null, "e": 2387, "s": 2344, "text": "Replace Specific Characters in String in R" }, { "code": null, "e": 2424, "s": 2387, "text": "How to import an Excel File into R ?" } ]
PLSQL | MOD Function
18 Oct, 2019 The MOD function is an inbuilt function in PLSQL which is used to return the remainder when a is divided by b. Its formula is . Syntax: MOD(a, b) Parameters Used:This function accepts two parameters a and b. This function gives remainder as the output when the input number a is divided by b. Return Value:This function returns the remainder when a is divided by b. Supported Versions of Oracle/PLSQL is given below: Oracle 12cOracle 11gOracle 10gOracle 9iOracle 8i Oracle 12c Oracle 11g Oracle 10g Oracle 9i Oracle 8i Let’s see some examples which illustrate the MOD function: Example-1: DECLARE Test_Number number1 := 15; Test_Number number2 := 4; BEGIN dbms_output.put_line(MOD(Test_Number number1, Test_Number number2)); END; Output: 3 In the above example, when the numeric value 15 is divided by 4 then it returns the remainder of 3 as output. Example-2: DECLARE Test_Number number1 := 15; Test_Number number2 := 0; BEGIN dbms_output.put_line(MOD(Test_Number number1, Test_Number number2)); END; Output: 15 In the above example, when the numeric value 15 is divided by 0 then it returns the remainder of 15 as output. Example-3: DECLARE Test_Number number1 := 11.6; Test_Number number2 := 2.1; BEGIN dbms_output.put_line(MOD(Test_Number number1, Test_Number number2)); END; Output: 1.1 In the above example, when the numeric value 11.6 is divided by 2.1 then it returns the remainder of 1.1 as output. Advantage:This function is used to find the remainder when a is divided by b. SQL-PL/SQL SQL SQL Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. CTE in SQL SQL Trigger | Student Database SQL Interview Questions How to Update Multiple Columns in Single Update Statement in SQL? SQL | Views Difference between DELETE, DROP and TRUNCATE Window functions in SQL Difference between DELETE and TRUNCATE Difference between DDL and DML in DBMS MySQL | Group_CONCAT() Function
[ { "code": null, "e": 28, "s": 0, "text": "\n18 Oct, 2019" }, { "code": null, "e": 156, "s": 28, "text": "The MOD function is an inbuilt function in PLSQL which is used to return the remainder when a is divided by b. Its formula is ." }, { "code": null, "e": 164, "s": 156, "text": "Syntax:" }, { "code": null, "e": 174, "s": 164, "text": "MOD(a, b)" }, { "code": null, "e": 321, "s": 174, "text": "Parameters Used:This function accepts two parameters a and b. This function gives remainder as the output when the input number a is divided by b." }, { "code": null, "e": 394, "s": 321, "text": "Return Value:This function returns the remainder when a is divided by b." }, { "code": null, "e": 445, "s": 394, "text": "Supported Versions of Oracle/PLSQL is given below:" }, { "code": null, "e": 494, "s": 445, "text": "Oracle 12cOracle 11gOracle 10gOracle 9iOracle 8i" }, { "code": null, "e": 505, "s": 494, "text": "Oracle 12c" }, { "code": null, "e": 516, "s": 505, "text": "Oracle 11g" }, { "code": null, "e": 527, "s": 516, "text": "Oracle 10g" }, { "code": null, "e": 537, "s": 527, "text": "Oracle 9i" }, { "code": null, "e": 547, "s": 537, "text": "Oracle 8i" }, { "code": null, "e": 606, "s": 547, "text": "Let’s see some examples which illustrate the MOD function:" }, { "code": null, "e": 617, "s": 606, "text": "Example-1:" }, { "code": null, "e": 809, "s": 617, "text": "DECLARE \n Test_Number number1 := 15;\n Test_Number number2 := 4;\n \nBEGIN \n dbms_output.put_line(MOD(Test_Number number1, \n Test_Number number2)); \n \nEND; " }, { "code": null, "e": 817, "s": 809, "text": "Output:" }, { "code": null, "e": 819, "s": 817, "text": "3" }, { "code": null, "e": 929, "s": 819, "text": "In the above example, when the numeric value 15 is divided by 4 then it returns the remainder of 3 as output." }, { "code": null, "e": 940, "s": 929, "text": "Example-2:" }, { "code": null, "e": 1131, "s": 940, "text": "DECLARE \n Test_Number number1 := 15;\n Test_Number number2 := 0;\n \nBEGIN \n dbms_output.put_line(MOD(Test_Number number1, \n Test_Number number2)); \n \nEND; " }, { "code": null, "e": 1139, "s": 1131, "text": "Output:" }, { "code": null, "e": 1142, "s": 1139, "text": "15" }, { "code": null, "e": 1253, "s": 1142, "text": "In the above example, when the numeric value 15 is divided by 0 then it returns the remainder of 15 as output." }, { "code": null, "e": 1264, "s": 1253, "text": "Example-3:" }, { "code": null, "e": 1459, "s": 1264, "text": "DECLARE \n Test_Number number1 := 11.6;\n Test_Number number2 := 2.1;\n \nBEGIN \n dbms_output.put_line(MOD(Test_Number number1, \n Test_Number number2)); \n \nEND; " }, { "code": null, "e": 1467, "s": 1459, "text": "Output:" }, { "code": null, "e": 1471, "s": 1467, "text": "1.1" }, { "code": null, "e": 1587, "s": 1471, "text": "In the above example, when the numeric value 11.6 is divided by 2.1 then it returns the remainder of 1.1 as output." }, { "code": null, "e": 1665, "s": 1587, "text": "Advantage:This function is used to find the remainder when a is divided by b." }, { "code": null, "e": 1676, "s": 1665, "text": "SQL-PL/SQL" }, { "code": null, "e": 1680, "s": 1676, "text": "SQL" }, { "code": null, "e": 1684, "s": 1680, "text": "SQL" }, { "code": null, "e": 1782, "s": 1684, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1793, "s": 1782, "text": "CTE in SQL" }, { "code": null, "e": 1824, "s": 1793, "text": "SQL Trigger | Student Database" }, { "code": null, "e": 1848, "s": 1824, "text": "SQL Interview Questions" }, { "code": null, "e": 1914, "s": 1848, "text": "How to Update Multiple Columns in Single Update Statement in SQL?" }, { "code": null, "e": 1926, "s": 1914, "text": "SQL | Views" }, { "code": null, "e": 1971, "s": 1926, "text": "Difference between DELETE, DROP and TRUNCATE" }, { "code": null, "e": 1995, "s": 1971, "text": "Window functions in SQL" }, { "code": null, "e": 2034, "s": 1995, "text": "Difference between DELETE and TRUNCATE" }, { "code": null, "e": 2073, "s": 2034, "text": "Difference between DDL and DML in DBMS" } ]
Sum and average of three numbers in PL/SQL
12 Jul, 2018 Prerequisite – PL/SQL introductionIn PL/SQL code groups of commands are arranged within a block. A block group related declarations or statements. In declare part, we declare variables and between begin and end part, we perform the operations. Given three numbers and the task is to find out the sum and average of three numbers.Examples: Input: a = 12, b = 15, c = 32 Output: sum = 59 avg = 19.66 Input: a = 34, b = 45, c = 11 Output: sum = 90 avg = 30 Approach is to take three numbers and find their sum and average using the formula given below-Sum: Average: Where a,b,c are the three numbers. Below is the required implementation: --To find sum and avg of three numbers DECLARE -- Assigning 12 into a a NUMBER := 12; -- Assigning 14 into b b NUMBER := 14; -- Assigning 20 into c c NUMBER := 20; -- Declare variable for sum -- Of Three number (a, b, c) sumOf3 NUMBER; -- Declare variable for average avgOf3 NUMBER; --Start Block BEGIN -- Assigning sum of a, b and c into sumOf3 sumOf3 := a + b + c; -- Assigning average of a, b and c into avgOf3 avgOf3 := sumOf3 / 3; --print Result sum of a, b, c number dbms_output.Put_line('Sum = ' ||sumOf3); --print Average sum of a, b, c number dbms_output.Put_line('Average = ' ||avgOf3); END; --End Program Output: Sum = 46 Average = 15.33 SQL-PL/SQL SQL SQL Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Difference between DELETE, DROP and TRUNCATE CTE in SQL Difference between SQL and NoSQL SQL using Python Difference between DELETE and TRUNCATE SQL | DDL, DML, TCL and DCL Window functions in SQL How to use SQLMAP to test a website for SQL Injection vulnerability Introduction to NoSQL SQL | USING Clause
[ { "code": null, "e": 54, "s": 26, "text": "\n12 Jul, 2018" }, { "code": null, "e": 298, "s": 54, "text": "Prerequisite – PL/SQL introductionIn PL/SQL code groups of commands are arranged within a block. A block group related declarations or statements. In declare part, we declare variables and between begin and end part, we perform the operations." }, { "code": null, "e": 393, "s": 298, "text": "Given three numbers and the task is to find out the sum and average of three numbers.Examples:" }, { "code": null, "e": 510, "s": 393, "text": "Input: a = 12, b = 15, c = 32\nOutput: sum = 59 avg = 19.66\n\nInput: a = 34, b = 45, c = 11\nOutput: sum = 90 avg = 30\n" }, { "code": null, "e": 654, "s": 510, "text": "Approach is to take three numbers and find their sum and average using the formula given below-Sum: Average: Where a,b,c are the three numbers." }, { "code": null, "e": 692, "s": 654, "text": "Below is the required implementation:" }, { "code": "--To find sum and avg of three numbers DECLARE -- Assigning 12 into a a NUMBER := 12; -- Assigning 14 into b b NUMBER := 14; -- Assigning 20 into c c NUMBER := 20; -- Declare variable for sum -- Of Three number (a, b, c) sumOf3 NUMBER; -- Declare variable for average avgOf3 NUMBER; --Start Block BEGIN -- Assigning sum of a, b and c into sumOf3 sumOf3 := a + b + c; -- Assigning average of a, b and c into avgOf3 avgOf3 := sumOf3 / 3; --print Result sum of a, b, c number dbms_output.Put_line('Sum = ' ||sumOf3); --print Average sum of a, b, c number dbms_output.Put_line('Average = ' ||avgOf3); END; --End Program ", "e": 1493, "s": 692, "text": null }, { "code": null, "e": 1501, "s": 1493, "text": "Output:" }, { "code": null, "e": 1527, "s": 1501, "text": "Sum = 46\nAverage = 15.33\n" }, { "code": null, "e": 1538, "s": 1527, "text": "SQL-PL/SQL" }, { "code": null, "e": 1542, "s": 1538, "text": "SQL" }, { "code": null, "e": 1546, "s": 1542, "text": "SQL" }, { "code": null, "e": 1644, "s": 1546, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1689, "s": 1644, "text": "Difference between DELETE, DROP and TRUNCATE" }, { "code": null, "e": 1700, "s": 1689, "text": "CTE in SQL" }, { "code": null, "e": 1733, "s": 1700, "text": "Difference between SQL and NoSQL" }, { "code": null, "e": 1750, "s": 1733, "text": "SQL using Python" }, { "code": null, "e": 1789, "s": 1750, "text": "Difference between DELETE and TRUNCATE" }, { "code": null, "e": 1817, "s": 1789, "text": "SQL | DDL, DML, TCL and DCL" }, { "code": null, "e": 1841, "s": 1817, "text": "Window functions in SQL" }, { "code": null, "e": 1909, "s": 1841, "text": "How to use SQLMAP to test a website for SQL Injection vulnerability" }, { "code": null, "e": 1931, "s": 1909, "text": "Introduction to NoSQL" } ]
Java Program to Convert long to int
27 Nov, 2020 Long is a larger data type than int, we need to explicitly perform typecasting for the conversion. Typecasting is performed through the typecast operator. There are basically three methods to convert long to int: By type-castingUsing toIntExact() methodUsing intValue() method of the Long wrapper class. By type-casting Using toIntExact() method Using intValue() method of the Long wrapper class. 1. Using Explicit Type Casting In typing casting, a data type is converted into another data type by the programmer using the casting operator during the program design. In typing casting, the destination data type may be smaller than the source data type when converting the data type to another data type, that’s why it is also called narrowing conversion. Syntax/Declaration: destination_datatype = (target_datatype)variable; () is a casting operator. target_datatype: is a data type in which we want to convert the source data type. Type Casting Example: float x; byte y; ... ... y=(byte)x; Java // Java Program to convert long to int import java.util.*;class GFG { public static void main(String[] args) { // long value long longnum = 10000; // explicit type casting from long to int int intnum = (int)longnum; System.out.println("Converted type: "+ ((Object)intnum).getClass().getName()); System.out.println("Converted int value is: " + intnum); }} Converted type: java.lang.Integer Converted int value is: 10000 2. Using toIntExact() method Syntax : public static int toIntExact(long value) Parameter: value : the long value Return:This method returns the input argument as an int(integer). Exception:It throws ArithmeticException – if the result overflows an int Java // Java Program to convert long to int class Main { public static void main(String[] args) { // create long variable long value1 = 523386L; long value2 = -4456368L; // change long to int int num1 = Math.toIntExact(value1); int num2 = Math.toIntExact(value2); // print the type System.out.println("Converted type: "+ ((Object)num1).getClass().getName()); System.out.println("Converted type: "+ ((Object)num2).getClass().getName()); // print the int value System.out.println(num1); // 52336 System.out.println(num2); // -445636 }} Converted type: java.lang.Integer Converted type: java.lang.Integer 523386 -4456368 3. Using intValue() method of Long wrapper class Syntax: public int intValue() Parameters: The method does not accept any parameters. Return Value: The method returns the numeric value which is represented by the object after conversion to the integer type. Java // Java Program to convert long to int using intValue()// method class GFG { public static void main(String[] args) { // Long object Long longnum = 100L; // Converting Long object to int primitive type int intnum = longnum.intValue(); // printing the type System.out.println("Converted type: " + ((Object)intnum).getClass().getName()); // printing the int value System.out.println("Converted int value: " + intnum); }} Converted type: java.lang.Integer Converted int value: 100 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. List Interface in Java with Examples Strings in Java Different ways of Reading a text file in Java Reverse an array in Java How to remove an element from ArrayList in Java? Java Programming Examples Convert Double to Integer in Java Implementing a Linked List in Java using Class Traverse Through a HashMap in Java Extends vs Implements in Java
[ { "code": null, "e": 28, "s": 0, "text": "\n27 Nov, 2020" }, { "code": null, "e": 241, "s": 28, "text": "Long is a larger data type than int, we need to explicitly perform typecasting for the conversion. Typecasting is performed through the typecast operator. There are basically three methods to convert long to int:" }, { "code": null, "e": 332, "s": 241, "text": "By type-castingUsing toIntExact() methodUsing intValue() method of the Long wrapper class." }, { "code": null, "e": 348, "s": 332, "text": "By type-casting" }, { "code": null, "e": 374, "s": 348, "text": "Using toIntExact() method" }, { "code": null, "e": 425, "s": 374, "text": "Using intValue() method of the Long wrapper class." }, { "code": null, "e": 456, "s": 425, "text": "1. Using Explicit Type Casting" }, { "code": null, "e": 784, "s": 456, "text": "In typing casting, a data type is converted into another data type by the programmer using the casting operator during the program design. In typing casting, the destination data type may be smaller than the source data type when converting the data type to another data type, that’s why it is also called narrowing conversion." }, { "code": null, "e": 804, "s": 784, "text": "Syntax/Declaration:" }, { "code": null, "e": 881, "s": 804, "text": "destination_datatype = (target_datatype)variable;\n\n() is a casting operator." }, { "code": null, "e": 963, "s": 881, "text": "target_datatype: is a data type in which we want to convert the source data type." }, { "code": null, "e": 985, "s": 963, "text": "Type Casting Example:" }, { "code": null, "e": 1021, "s": 985, "text": "float x;\nbyte y;\n...\n...\ny=(byte)x;" }, { "code": null, "e": 1026, "s": 1021, "text": "Java" }, { "code": "// Java Program to convert long to int import java.util.*;class GFG { public static void main(String[] args) { // long value long longnum = 10000; // explicit type casting from long to int int intnum = (int)longnum; System.out.println(\"Converted type: \"+ ((Object)intnum).getClass().getName()); System.out.println(\"Converted int value is: \" + intnum); }}", "e": 1476, "s": 1026, "text": null }, { "code": null, "e": 1540, "s": 1476, "text": "Converted type: java.lang.Integer\nConverted int value is: 10000" }, { "code": null, "e": 1570, "s": 1540, "text": "2. Using toIntExact() method" }, { "code": null, "e": 1579, "s": 1570, "text": "Syntax :" }, { "code": null, "e": 1621, "s": 1579, "text": "public static int toIntExact(long value)\n" }, { "code": null, "e": 1632, "s": 1621, "text": "Parameter:" }, { "code": null, "e": 1655, "s": 1632, "text": "value : the long value" }, { "code": null, "e": 1721, "s": 1655, "text": "Return:This method returns the input argument as an int(integer)." }, { "code": null, "e": 1794, "s": 1721, "text": "Exception:It throws ArithmeticException – if the result overflows an int" }, { "code": null, "e": 1799, "s": 1794, "text": "Java" }, { "code": "// Java Program to convert long to int class Main { public static void main(String[] args) { // create long variable long value1 = 523386L; long value2 = -4456368L; // change long to int int num1 = Math.toIntExact(value1); int num2 = Math.toIntExact(value2); // print the type System.out.println(\"Converted type: \"+ ((Object)num1).getClass().getName()); System.out.println(\"Converted type: \"+ ((Object)num2).getClass().getName()); // print the int value System.out.println(num1); // 52336 System.out.println(num2); // -445636 }}", "e": 2381, "s": 1799, "text": null }, { "code": null, "e": 2465, "s": 2381, "text": "Converted type: java.lang.Integer\nConverted type: java.lang.Integer\n523386\n-4456368" }, { "code": null, "e": 2514, "s": 2465, "text": "3. Using intValue() method of Long wrapper class" }, { "code": null, "e": 2522, "s": 2514, "text": "Syntax:" }, { "code": null, "e": 2544, "s": 2522, "text": "public int intValue()" }, { "code": null, "e": 2599, "s": 2544, "text": "Parameters: The method does not accept any parameters." }, { "code": null, "e": 2723, "s": 2599, "text": "Return Value: The method returns the numeric value which is represented by the object after conversion to the integer type." }, { "code": null, "e": 2728, "s": 2723, "text": "Java" }, { "code": "// Java Program to convert long to int using intValue()// method class GFG { public static void main(String[] args) { // Long object Long longnum = 100L; // Converting Long object to int primitive type int intnum = longnum.intValue(); // printing the type System.out.println(\"Converted type: \" + ((Object)intnum).getClass().getName()); // printing the int value System.out.println(\"Converted int value: \" + intnum); }}", "e": 3256, "s": 2728, "text": null }, { "code": null, "e": 3315, "s": 3256, "text": "Converted type: java.lang.Integer\nConverted int value: 100" }, { "code": null, "e": 3322, "s": 3315, "text": "Picked" }, { "code": null, "e": 3346, "s": 3322, "text": "Technical Scripter 2020" }, { "code": null, "e": 3351, "s": 3346, "text": "Java" }, { "code": null, "e": 3365, "s": 3351, "text": "Java Programs" }, { "code": null, "e": 3384, "s": 3365, "text": "Technical Scripter" }, { "code": null, "e": 3389, "s": 3384, "text": "Java" }, { "code": null, "e": 3487, "s": 3389, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3524, "s": 3487, "text": "List Interface in Java with Examples" }, { "code": null, "e": 3540, "s": 3524, "text": "Strings in Java" }, { "code": null, "e": 3586, "s": 3540, "text": "Different ways of Reading a text file in Java" }, { "code": null, "e": 3611, "s": 3586, "text": "Reverse an array in Java" }, { "code": null, "e": 3660, "s": 3611, "text": "How to remove an element from ArrayList in Java?" }, { "code": null, "e": 3686, "s": 3660, "text": "Java Programming Examples" }, { "code": null, "e": 3720, "s": 3686, "text": "Convert Double to Integer in Java" }, { "code": null, "e": 3767, "s": 3720, "text": "Implementing a Linked List in Java using Class" }, { "code": null, "e": 3802, "s": 3767, "text": "Traverse Through a HashMap in Java" } ]
DOM-based Cross-Site Scripting Attack in Depth
21 Jun, 2021 In this article, we will be understanding one of the types of Cross-Site Scripting in-depth i.e DOM-based XSS. Let’s discuss it one by one as follows. DOM-based Cross Site Scripting : DOM XSS stands for Document Object Model-based Cross-site Scripting. DOM-based vulnerabilities occur in the content processing stage performed on the client, typically in client-side JavaScript. DOM-based XSS works similar to reflected XSS one — attacker manipulates client’s browser environment (Document Object Model) and places payload into page content. The main difference is, that since the malicious payload is stored in the browser environment, it may be not sent on the server-side. This way all protection mechanisms related to traffic analysis will fail. In reflective and stored Cross-site scripting attacks you can see the vulnerability malicious script in the response page but in DOM-based cross-site scripting, the HTML source code and the response of the attack will be the same, i.e. the malicious script cannot be found in the response from the web server. In a DOM-based XSS attack, the malicious string is not parsed by the victim’s browser until the website’s legitimate JavaScript is executed. To perform a DOM-based XSS attack, you need to place data into a source so that it is propagated to a sink and causes the execution of arbitrary JavaScript code. Breakdown of a DOM-based XSS attack :The following is a breakdown of a DOM-based XSS attack as follows. Attacker discovers the DOM-based XSS vulnerabilityThe hacker or attacker crafts a malicious script and sends the URL to the target(Email, social media, etc)Victim clicks on the URLVictims browser sends a request to the vulnerable site (note: the request does not contain the XSS malicious script)The web server responds with the web page (note: this response does not contain the XSS malicious script)Victims web browser renders the page, with the hackers or attackers XSS malicious script Attacker discovers the DOM-based XSS vulnerability The hacker or attacker crafts a malicious script and sends the URL to the target(Email, social media, etc) Victim clicks on the URL Victims browser sends a request to the vulnerable site (note: the request does not contain the XSS malicious script) The web server responds with the web page (note: this response does not contain the XSS malicious script) Victims web browser renders the page, with the hackers or attackers XSS malicious script Impact : Steal another client’s cookies or sessions.Modify another client’s cookies or sessions.Steal another client’s submitted form information or some sensitive credentials.Modify another client’s submitted form data or information by intercepting the request (before it reaches the server). Steal another client’s cookies or sessions. Modify another client’s cookies or sessions. Steal another client’s submitted form information or some sensitive credentials. Modify another client’s submitted form data or information by intercepting the request (before it reaches the server). Note –Submit a form to your application on the user’s behalf which modifies passwords or sensitive data on server or other application data. Finding DOM-based Cross Site Scripting : Most DOM XSS vulnerabilities can be found rapidly and efficiently using Burp Suite’s tool scanner or some other scripts which are available on GitHub.To test for DOM-based cross-site scripting manually, you generally need to use a web browser with developer tools, such as Chrome or Firefox.You need to work through each available source or input field in turn and test each one individually. Most DOM XSS vulnerabilities can be found rapidly and efficiently using Burp Suite’s tool scanner or some other scripts which are available on GitHub. To test for DOM-based cross-site scripting manually, you generally need to use a web browser with developer tools, such as Chrome or Firefox. You need to work through each available source or input field in turn and test each one individually. Understanding DOM-based Attack via Diagram: DOM XSS Steps Diagram Description –From the above fig, “Consider diagram arrow numbers (Step 1 to Step 6) as steps” as follows. Step-1: An attacker crafts the URL and sends it to a victim. Step-2: The victim clicks on it and the request goes to the server. Step-3: The server response contains the hard-coded JavaScript. Step-4: The attacker’s URL is processed by hard-coded JavaScript, triggering his payload. Step-5: The victim’s browser sends the cookies to the attacker. Step-6: Attacker hijacks user’s session. Example :Example of a DOM-based XSS Attack as follows. <HTML> <TITLE>Hello!</TITLE> <SCRIPT> var pos=document.URL.indexOf("name=")+5; document.write(document.URL.substring(pos,document.URL.length)); </SCRIPT> <BR> Welcome To Our Website ... </HTML> Explanation –Normally, this HTML page would be used for welcoming the user, e.g – http://www.victim.site/hello.html?name=Gaurav However, a request such as the one below would result in an XSS condition as follows. http://www.victim.site/hello.html?name=alert(document.domain) Detecting DOM XSS is hard using purely server-side detection (i.e. HTTP requests), which is why providers like Acunetix leverages DeepScan to do it. These malicious scripts or payloads are never sent to the web server due to being behind an HTML fragment (everything behind the # symbol). As a result, the root issue is in the code (i.e. JavaScript) that is on the source page. This means that you should always sanitize or filter user input, irrespective of whether it is client-side To remediate DOM-based XSS, data must not be dynamically written from any un-trusted source into the HTML document. Security controls must be in place if the functionality requires it. It may involve a combination of JavaScript escaping, HTML encoding, and URL encoding. Frameworks like AngularJS and React use templates that make the construction of ad-hoc HTML an explicit (and rare) action. This will boost your development team towards best practices, and make unsafe operations easier to detect. Note – The following source attributes should be avoided like URL, document URI, location, href, search, hash. Cyber-security Information-Security vulnerability Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 53, "s": 25, "text": "\n21 Jun, 2021" }, { "code": null, "e": 204, "s": 53, "text": "In this article, we will be understanding one of the types of Cross-Site Scripting in-depth i.e DOM-based XSS. Let’s discuss it one by one as follows." }, { "code": null, "e": 237, "s": 204, "text": "DOM-based Cross Site Scripting :" }, { "code": null, "e": 432, "s": 237, "text": "DOM XSS stands for Document Object Model-based Cross-site Scripting. DOM-based vulnerabilities occur in the content processing stage performed on the client, typically in client-side JavaScript." }, { "code": null, "e": 803, "s": 432, "text": "DOM-based XSS works similar to reflected XSS one — attacker manipulates client’s browser environment (Document Object Model) and places payload into page content. The main difference is, that since the malicious payload is stored in the browser environment, it may be not sent on the server-side. This way all protection mechanisms related to traffic analysis will fail." }, { "code": null, "e": 1113, "s": 803, "text": "In reflective and stored Cross-site scripting attacks you can see the vulnerability malicious script in the response page but in DOM-based cross-site scripting, the HTML source code and the response of the attack will be the same, i.e. the malicious script cannot be found in the response from the web server." }, { "code": null, "e": 1416, "s": 1113, "text": "In a DOM-based XSS attack, the malicious string is not parsed by the victim’s browser until the website’s legitimate JavaScript is executed. To perform a DOM-based XSS attack, you need to place data into a source so that it is propagated to a sink and causes the execution of arbitrary JavaScript code." }, { "code": null, "e": 1520, "s": 1416, "text": "Breakdown of a DOM-based XSS attack :The following is a breakdown of a DOM-based XSS attack as follows." }, { "code": null, "e": 2010, "s": 1520, "text": "Attacker discovers the DOM-based XSS vulnerabilityThe hacker or attacker crafts a malicious script and sends the URL to the target(Email, social media, etc)Victim clicks on the URLVictims browser sends a request to the vulnerable site (note: the request does not contain the XSS malicious script)The web server responds with the web page (note: this response does not contain the XSS malicious script)Victims web browser renders the page, with the hackers or attackers XSS malicious script" }, { "code": null, "e": 2061, "s": 2010, "text": "Attacker discovers the DOM-based XSS vulnerability" }, { "code": null, "e": 2168, "s": 2061, "text": "The hacker or attacker crafts a malicious script and sends the URL to the target(Email, social media, etc)" }, { "code": null, "e": 2193, "s": 2168, "text": "Victim clicks on the URL" }, { "code": null, "e": 2310, "s": 2193, "text": "Victims browser sends a request to the vulnerable site (note: the request does not contain the XSS malicious script)" }, { "code": null, "e": 2416, "s": 2310, "text": "The web server responds with the web page (note: this response does not contain the XSS malicious script)" }, { "code": null, "e": 2505, "s": 2416, "text": "Victims web browser renders the page, with the hackers or attackers XSS malicious script" }, { "code": null, "e": 2514, "s": 2505, "text": "Impact :" }, { "code": null, "e": 2800, "s": 2514, "text": "Steal another client’s cookies or sessions.Modify another client’s cookies or sessions.Steal another client’s submitted form information or some sensitive credentials.Modify another client’s submitted form data or information by intercepting the request (before it reaches the server)." }, { "code": null, "e": 2844, "s": 2800, "text": "Steal another client’s cookies or sessions." }, { "code": null, "e": 2889, "s": 2844, "text": "Modify another client’s cookies or sessions." }, { "code": null, "e": 2970, "s": 2889, "text": "Steal another client’s submitted form information or some sensitive credentials." }, { "code": null, "e": 3089, "s": 2970, "text": "Modify another client’s submitted form data or information by intercepting the request (before it reaches the server)." }, { "code": null, "e": 3230, "s": 3089, "text": "Note –Submit a form to your application on the user’s behalf which modifies passwords or sensitive data on server or other application data." }, { "code": null, "e": 3271, "s": 3230, "text": "Finding DOM-based Cross Site Scripting :" }, { "code": null, "e": 3664, "s": 3271, "text": "Most DOM XSS vulnerabilities can be found rapidly and efficiently using Burp Suite’s tool scanner or some other scripts which are available on GitHub.To test for DOM-based cross-site scripting manually, you generally need to use a web browser with developer tools, such as Chrome or Firefox.You need to work through each available source or input field in turn and test each one individually." }, { "code": null, "e": 3815, "s": 3664, "text": "Most DOM XSS vulnerabilities can be found rapidly and efficiently using Burp Suite’s tool scanner or some other scripts which are available on GitHub." }, { "code": null, "e": 3957, "s": 3815, "text": "To test for DOM-based cross-site scripting manually, you generally need to use a web browser with developer tools, such as Chrome or Firefox." }, { "code": null, "e": 4059, "s": 3957, "text": "You need to work through each available source or input field in turn and test each one individually." }, { "code": null, "e": 4103, "s": 4059, "text": "Understanding DOM-based Attack via Diagram:" }, { "code": null, "e": 4117, "s": 4103, "text": "DOM XSS Steps" }, { "code": null, "e": 4231, "s": 4117, "text": "Diagram Description –From the above fig, “Consider diagram arrow numbers (Step 1 to Step 6) as steps” as follows." }, { "code": null, "e": 4292, "s": 4231, "text": "Step-1: An attacker crafts the URL and sends it to a victim." }, { "code": null, "e": 4360, "s": 4292, "text": "Step-2: The victim clicks on it and the request goes to the server." }, { "code": null, "e": 4424, "s": 4360, "text": "Step-3: The server response contains the hard-coded JavaScript." }, { "code": null, "e": 4514, "s": 4424, "text": "Step-4: The attacker’s URL is processed by hard-coded JavaScript, triggering his payload." }, { "code": null, "e": 4578, "s": 4514, "text": "Step-5: The victim’s browser sends the cookies to the attacker." }, { "code": null, "e": 4619, "s": 4578, "text": "Step-6: Attacker hijacks user’s session." }, { "code": null, "e": 4674, "s": 4619, "text": "Example :Example of a DOM-based XSS Attack as follows." }, { "code": null, "e": 4868, "s": 4674, "text": "<HTML>\n<TITLE>Hello!</TITLE>\n<SCRIPT>\nvar pos=document.URL.indexOf(\"name=\")+5;\ndocument.write(document.URL.substring(pos,document.URL.length));\n</SCRIPT>\n<BR>\nWelcome To Our Website\n...\n</HTML>" }, { "code": null, "e": 4950, "s": 4868, "text": "Explanation –Normally, this HTML page would be used for welcoming the user, e.g –" }, { "code": null, "e": 4996, "s": 4950, "text": "http://www.victim.site/hello.html?name=Gaurav" }, { "code": null, "e": 5082, "s": 4996, "text": "However, a request such as the one below would result in an XSS condition as follows." }, { "code": null, "e": 5144, "s": 5082, "text": "http://www.victim.site/hello.html?name=alert(document.domain)" }, { "code": null, "e": 5293, "s": 5144, "text": "Detecting DOM XSS is hard using purely server-side detection (i.e. HTTP requests), which is why providers like Acunetix leverages DeepScan to do it." }, { "code": null, "e": 5433, "s": 5293, "text": "These malicious scripts or payloads are never sent to the web server due to being behind an HTML fragment (everything behind the # symbol)." }, { "code": null, "e": 5629, "s": 5433, "text": "As a result, the root issue is in the code (i.e. JavaScript) that is on the source page. This means that you should always sanitize or filter user input, irrespective of whether it is client-side" }, { "code": null, "e": 5814, "s": 5629, "text": "To remediate DOM-based XSS, data must not be dynamically written from any un-trusted source into the HTML document. Security controls must be in place if the functionality requires it." }, { "code": null, "e": 5900, "s": 5814, "text": "It may involve a combination of JavaScript escaping, HTML encoding, and URL encoding." }, { "code": null, "e": 6130, "s": 5900, "text": "Frameworks like AngularJS and React use templates that make the construction of ad-hoc HTML an explicit (and rare) action. This will boost your development team towards best practices, and make unsafe operations easier to detect." }, { "code": null, "e": 6243, "s": 6130, "text": "Note – The following source attributes should be avoided like URL, document URI, location, href, search, hash." }, { "code": null, "e": 6258, "s": 6243, "text": "Cyber-security" }, { "code": null, "e": 6279, "s": 6258, "text": "Information-Security" }, { "code": null, "e": 6293, "s": 6279, "text": "vulnerability" }, { "code": null, "e": 6310, "s": 6293, "text": "Web Technologies" } ]
How to place a button at any position in Tkinter?
24 Jan, 2021 Prerequisite: Creating a button in Tkinter Tkinter is the most commonly used library for developing GUI (Graphical User Interface) in Python. It is a standard Python interface to the Tk GUI toolkit shipped with Python. Python offers multiple options for developing a GUI (Graphical User Interface). Out of all the GUI methods, tkinter is the most commonly used method. It is a standard Python interface to the Tk GUI toolkit shipped with Python. Python with tkinter is the fastest and easiest way to create GUI applications. Creating a GUI using tkinter is an easy task. Approach: Import the tkinter module Create the main window Add a button to the window. Place the button. The button in the tkinter module can be placed or move to any position in two ways: By using the place() method. And by using the pack() method. Method 1: Using the place() method This method is used to place a button at an absolute defined position. Syntax : button1.place(x=some_value, y=some_value) Parameters : x : It defines the x-coordinate of the button’s position. y : It defines the y-coordinate of the button’s position. Below is the implementation of the approach shown above: Python3 # Importing tkinter module from tkinter import * # Creating a tkinter windowroot = Tk() # Initialize tkinter window with dimensions 300 x 250 root.geometry('300x250') # Creating a Buttonbtn = Button(root, text = 'Click me !', command = root.destroy) # Set the position of button to coordinate (100, 20)btn.place(x=100, y=20) root.mainloop() Output: Method 2: Using the pack() method This method is used to place a button at a relative position. Syntax : button1.pack(side=some_side, padx=some_value, pady=some_value) Parameters : side : It defines the side where the button will be placed. padx : It defines the padding on x-axis from the defined side. pady : It defines the padding on y-axis from tht defines side. Below is the implementation of the approach shown above: Python3 # Importing tkinter module from tkinter import * # Creating a tkinter windowroot = Tk() # Initialize tkinter window with dimensions 300 x 250 root.geometry('300x250') # Creating a Buttonbtn = Button(root, text = 'Click me !', command = root.destroy) # Set a relative position of buttonbtn.pack(side=RIGHT, padx=15, pady=20) root.mainloop() Output: Python-tkinter Technical Scripter 2020 Python Technical Scripter Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 53, "s": 25, "text": "\n24 Jan, 2021" }, { "code": null, "e": 96, "s": 53, "text": "Prerequisite: Creating a button in Tkinter" }, { "code": null, "e": 624, "s": 96, "text": "Tkinter is the most commonly used library for developing GUI (Graphical User Interface) in Python. It is a standard Python interface to the Tk GUI toolkit shipped with Python. Python offers multiple options for developing a GUI (Graphical User Interface). Out of all the GUI methods, tkinter is the most commonly used method. It is a standard Python interface to the Tk GUI toolkit shipped with Python. Python with tkinter is the fastest and easiest way to create GUI applications. Creating a GUI using tkinter is an easy task." }, { "code": null, "e": 634, "s": 624, "text": "Approach:" }, { "code": null, "e": 661, "s": 634, "text": "Import the tkinter module " }, { "code": null, "e": 685, "s": 661, "text": "Create the main window " }, { "code": null, "e": 713, "s": 685, "text": "Add a button to the window." }, { "code": null, "e": 731, "s": 713, "text": "Place the button." }, { "code": null, "e": 815, "s": 731, "text": "The button in the tkinter module can be placed or move to any position in two ways:" }, { "code": null, "e": 844, "s": 815, "text": "By using the place() method." }, { "code": null, "e": 876, "s": 844, "text": "And by using the pack() method." }, { "code": null, "e": 911, "s": 876, "text": "Method 1: Using the place() method" }, { "code": null, "e": 982, "s": 911, "text": "This method is used to place a button at an absolute defined position." }, { "code": null, "e": 1033, "s": 982, "text": "Syntax : button1.place(x=some_value, y=some_value)" }, { "code": null, "e": 1046, "s": 1033, "text": "Parameters :" }, { "code": null, "e": 1104, "s": 1046, "text": "x : It defines the x-coordinate of the button’s position." }, { "code": null, "e": 1162, "s": 1104, "text": "y : It defines the y-coordinate of the button’s position." }, { "code": null, "e": 1219, "s": 1162, "text": "Below is the implementation of the approach shown above:" }, { "code": null, "e": 1227, "s": 1219, "text": "Python3" }, { "code": "# Importing tkinter module from tkinter import * # Creating a tkinter windowroot = Tk() # Initialize tkinter window with dimensions 300 x 250 root.geometry('300x250') # Creating a Buttonbtn = Button(root, text = 'Click me !', command = root.destroy) # Set the position of button to coordinate (100, 20)btn.place(x=100, y=20) root.mainloop()", "e": 1599, "s": 1227, "text": null }, { "code": null, "e": 1607, "s": 1599, "text": "Output:" }, { "code": null, "e": 1641, "s": 1607, "text": "Method 2: Using the pack() method" }, { "code": null, "e": 1703, "s": 1641, "text": "This method is used to place a button at a relative position." }, { "code": null, "e": 1775, "s": 1703, "text": "Syntax : button1.pack(side=some_side, padx=some_value, pady=some_value)" }, { "code": null, "e": 1788, "s": 1775, "text": "Parameters :" }, { "code": null, "e": 1848, "s": 1788, "text": "side : It defines the side where the button will be placed." }, { "code": null, "e": 1911, "s": 1848, "text": "padx : It defines the padding on x-axis from the defined side." }, { "code": null, "e": 1974, "s": 1911, "text": "pady : It defines the padding on y-axis from tht defines side." }, { "code": null, "e": 2031, "s": 1974, "text": "Below is the implementation of the approach shown above:" }, { "code": null, "e": 2039, "s": 2031, "text": "Python3" }, { "code": "# Importing tkinter module from tkinter import * # Creating a tkinter windowroot = Tk() # Initialize tkinter window with dimensions 300 x 250 root.geometry('300x250') # Creating a Buttonbtn = Button(root, text = 'Click me !', command = root.destroy) # Set a relative position of buttonbtn.pack(side=RIGHT, padx=15, pady=20) root.mainloop()", "e": 2410, "s": 2039, "text": null }, { "code": null, "e": 2418, "s": 2410, "text": "Output:" }, { "code": null, "e": 2433, "s": 2418, "text": "Python-tkinter" }, { "code": null, "e": 2457, "s": 2433, "text": "Technical Scripter 2020" }, { "code": null, "e": 2464, "s": 2457, "text": "Python" }, { "code": null, "e": 2483, "s": 2464, "text": "Technical Scripter" } ]
numpy.isinf() in Python
28 Mar, 2022 The numpy.isinf() function tests element-wise whether it is +ve or -ve infinity or not return the result as a boolean array. Syntax: numpy.isinf(array [, out]) Parameters : array : [array_like]Input array or object whose elements, we need to test for infinity out : [ndarray, optional]Output array placed with result. Its type is preserved and it must be of the right shape to hold the output. Return : boolean array containing the result. For scalar input, the result is a new boolean with value True if the input is positive or negative infinity; otherwise the value is False. For array input, the result is a boolean array with the same shape as the input and the values are True where the corresponding element of the input is positive or negative infinity; elsewhere the values are False. Code 1 : Python # Python Program illustrating# numpy.isinf() method import numpy as geek print("Finite : ", geek.isinf(1), "\n") print("Finite : ", geek.isinf(0), "\n") # not a numberprint("Finite : ", geek.isinf(geek.nan), "\n") # infinityprint("Finite : ", geek.isinf(geek.inf), "\n") print("Finite : ", geek.isinf(geek.NINF), "\n") x = geek.array([-geek.inf, 0., geek.inf])y = geek.array([2, 2, 2])print("Checking for infinity : ", geek.isinf(x, y)) Output : Finite : False Finite : False Finite : False Finite : True Finite : True Checking for infinity : [1 0 1] Code 2 : Python # Python Program illustrating# numpy.isinf() method import numpy as geek # Returns True/False value for each elementb = geek.arange(8).reshape(2, 4) print("\n",b)print("\nIs Infinity : \n", geek.isinf(b)) # geek.inf : Positive Infinity# geek.NINF : negative Infinityb = [[geek.inf], [geek.NINF]]print("\nIs Infinity : \n", geek.isinf(b)) Output : [[0 1 2 3] [4 5 6 7]] Is Infinity : [[False False False False] [False False False False]] Is Infinity : [[ True] [ True]] References : https://docs.scipy.org/doc/numpy-dev/reference/generated/numpy.isinf.html#numpy.isinf Note : These codes won’t run on online IDE’s. So please, run them on your systems to explore the working. This article is contributed by Mohit Gupta_OMG . If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. 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. akshaysingh98088 vinayedula Python numpy-Logic Functions Python-numpy Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 53, "s": 25, "text": "\n28 Mar, 2022" }, { "code": null, "e": 179, "s": 53, "text": "The numpy.isinf() function tests element-wise whether it is +ve or -ve infinity or not return the result as a boolean array. " }, { "code": null, "e": 214, "s": 179, "text": "Syntax: numpy.isinf(array [, out])" }, { "code": null, "e": 229, "s": 214, "text": "Parameters : " }, { "code": null, "e": 491, "s": 229, "text": "array : [array_like]Input array or object whose \n elements, we need to test for infinity\nout : [ndarray, optional]Output array placed \n with result. Its type is preserved and\n it must be of the right shape to hold \n the output." }, { "code": null, "e": 502, "s": 491, "text": "Return : " }, { "code": null, "e": 898, "s": 502, "text": "boolean array containing the result. For scalar \ninput, the result is a new boolean with value\nTrue if the input is positive or negative infinity; \notherwise the value is False. For array input, the \nresult is a boolean array with the same shape as \nthe input and the values are True where the \ncorresponding element of the input is positive\nor negative infinity; elsewhere the values are False." }, { "code": null, "e": 909, "s": 898, "text": "Code 1 : " }, { "code": null, "e": 916, "s": 909, "text": "Python" }, { "code": "# Python Program illustrating# numpy.isinf() method import numpy as geek print(\"Finite : \", geek.isinf(1), \"\\n\") print(\"Finite : \", geek.isinf(0), \"\\n\") # not a numberprint(\"Finite : \", geek.isinf(geek.nan), \"\\n\") # infinityprint(\"Finite : \", geek.isinf(geek.inf), \"\\n\") print(\"Finite : \", geek.isinf(geek.NINF), \"\\n\") x = geek.array([-geek.inf, 0., geek.inf])y = geek.array([2, 2, 2])print(\"Checking for infinity : \", geek.isinf(x, y))", "e": 1355, "s": 916, "text": null }, { "code": null, "e": 1365, "s": 1355, "text": "Output : " }, { "code": null, "e": 1486, "s": 1365, "text": "Finite : False \n\nFinite : False \n\nFinite : False \n\nFinite : True \n\nFinite : True \n\nChecking for infinity : [1 0 1]" }, { "code": null, "e": 1496, "s": 1486, "text": "Code 2 : " }, { "code": null, "e": 1503, "s": 1496, "text": "Python" }, { "code": "# Python Program illustrating# numpy.isinf() method import numpy as geek # Returns True/False value for each elementb = geek.arange(8).reshape(2, 4) print(\"\\n\",b)print(\"\\nIs Infinity : \\n\", geek.isinf(b)) # geek.inf : Positive Infinity# geek.NINF : negative Infinityb = [[geek.inf], [geek.NINF]]print(\"\\nIs Infinity : \\n\", geek.isinf(b))", "e": 1864, "s": 1503, "text": null }, { "code": null, "e": 1874, "s": 1864, "text": "Output : " }, { "code": null, "e": 2006, "s": 1874, "text": " [[0 1 2 3]\n [4 5 6 7]]\n\nIs Infinity : \n [[False False False False]\n [False False False False]]\n\nIs Infinity : \n [[ True]\n [ True]]" }, { "code": null, "e": 2105, "s": 2006, "text": "References : https://docs.scipy.org/doc/numpy-dev/reference/generated/numpy.isinf.html#numpy.isinf" }, { "code": null, "e": 2636, "s": 2105, "text": "Note : These codes won’t run on online IDE’s. So please, run them on your systems to explore the working. This article is contributed by Mohit Gupta_OMG . If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. 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": 2653, "s": 2636, "text": "akshaysingh98088" }, { "code": null, "e": 2664, "s": 2653, "text": "vinayedula" }, { "code": null, "e": 2693, "s": 2664, "text": "Python numpy-Logic Functions" }, { "code": null, "e": 2706, "s": 2693, "text": "Python-numpy" }, { "code": null, "e": 2713, "s": 2706, "text": "Python" } ]
How to Create Menu Folder & Menu File in Android Studio?
07 Mar, 2021 Menus are the common user interface component in almost all the application. This interface provides a few options from which the user can select an option. There are 3 types of menu types available in Android: Options menu and app barContext menu and contextual action modePopup menu Options menu and app bar Context menu and contextual action mode Popup menu In android, we can build the menu on our activity page but which is not standard practice, instead we define it in the menu resource then we inflate that menu resource into our activity. The reason why we should define menu in menu resource: The first and most important thing it separates from our activity so visualization and debugging is easy. Separating the menu gives us flexibility like for different platform versions, screen sizes we can make some changes to our menu resource file. Easy to manage as it’s separate from our activity. Step 1: Open your project in “Project” mode Open your android project in “Project” mode If the project is already opened in the “Android” mode. Step 2: In your project Go to the app > src > main > res as shown in the below image. Step 3: Right-click on the res folder > New > Android Resource Directory as shown in the below image. Step 4: Now you select the menu option from the values drop-down section. After selecting you can see a screen like this. And now just hit OK. Step 4: Now you can see the menu folder inside the res folder. Step 5: Now to create a menu file select the menu folder and right-click on it and select Menu Resource File. Step 6: Give a name to your menu file, for instance here we have given the name as my_menu. Then hit OK. Now you can see the my_menu.xml file inside the menu folder. Woah, you just create your menu file in android studio. So now we just write few lines of code to see that our menu file is working or not. XML <?xml version="1.0" encoding="utf-8"?><menu xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:android="http://schemas.android.com/apk/res/android"> <item android:id="@+id/new_game" android:icon="@drawable/ic_baseline_local_see_24" android:title="@string/new_game"/> <item android:id="@+id/help" android:icon="@drawable/ic_baseline_first_page_24" android:title="@string/help" /></menu> Now look at the codes you see the menu tag i.e <menu> <menu>: It is just a container and it holds the menu items or group of menu items. <item>: It creates menu item Title and icon properties are self-explanatory so I don’t think I have to explain them. Note: Look at the above code, android: icon, those are the icon that we have created. In your case just look at your drawable folder and give your icon name there. Ok, we just completed our 80% of work now just inflate our menu to our MainActvity.kt file Kotlin import androidx.appcompat.app.AppCompatActivityimport android.os.Bundleimport android.view.Menuimport android.view.MenuInflater class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) } // look at this section override fun onCreateOptionsMenu(menu: Menu?): Boolean { val inflater: MenuInflater = menuInflater inflater.inflate(R.menu.my_menu,menu) return super.onCreateOptionsMenu(menu) }} Just focus on the codes after the comment line that block of codes used to inflate our menu in our app. Now run your app and you can see the result. Android-Studio Android Android Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Add Views Dynamically and Store Data in Arraylist in Android? Android SDK and it's Components Flutter - Custom Bottom Navigation Bar How to Communicate Between Fragments in Android? Retrofit with Kotlin Coroutine in Android How to Post Data to API using Retrofit in Android? Flutter - Stack Widget Introduction to Android Development Activity Lifecycle in Android with Demo App Fragment Lifecycle in Android
[ { "code": null, "e": 28, "s": 0, "text": "\n07 Mar, 2021" }, { "code": null, "e": 239, "s": 28, "text": "Menus are the common user interface component in almost all the application. This interface provides a few options from which the user can select an option. There are 3 types of menu types available in Android:" }, { "code": null, "e": 313, "s": 239, "text": "Options menu and app barContext menu and contextual action modePopup menu" }, { "code": null, "e": 338, "s": 313, "text": "Options menu and app bar" }, { "code": null, "e": 378, "s": 338, "text": "Context menu and contextual action mode" }, { "code": null, "e": 389, "s": 378, "text": "Popup menu" }, { "code": null, "e": 631, "s": 389, "text": "In android, we can build the menu on our activity page but which is not standard practice, instead we define it in the menu resource then we inflate that menu resource into our activity. The reason why we should define menu in menu resource:" }, { "code": null, "e": 737, "s": 631, "text": "The first and most important thing it separates from our activity so visualization and debugging is easy." }, { "code": null, "e": 881, "s": 737, "text": "Separating the menu gives us flexibility like for different platform versions, screen sizes we can make some changes to our menu resource file." }, { "code": null, "e": 932, "s": 881, "text": "Easy to manage as it’s separate from our activity." }, { "code": null, "e": 976, "s": 932, "text": "Step 1: Open your project in “Project” mode" }, { "code": null, "e": 1076, "s": 976, "text": "Open your android project in “Project” mode If the project is already opened in the “Android” mode." }, { "code": null, "e": 1163, "s": 1076, "text": "Step 2: In your project Go to the app > src > main > res as shown in the below image." }, { "code": null, "e": 1265, "s": 1163, "text": "Step 3: Right-click on the res folder > New > Android Resource Directory as shown in the below image." }, { "code": null, "e": 1339, "s": 1265, "text": "Step 4: Now you select the menu option from the values drop-down section." }, { "code": null, "e": 1387, "s": 1339, "text": "After selecting you can see a screen like this." }, { "code": null, "e": 1408, "s": 1387, "text": "And now just hit OK." }, { "code": null, "e": 1471, "s": 1408, "text": "Step 4: Now you can see the menu folder inside the res folder." }, { "code": null, "e": 1581, "s": 1471, "text": "Step 5: Now to create a menu file select the menu folder and right-click on it and select Menu Resource File." }, { "code": null, "e": 1673, "s": 1581, "text": "Step 6: Give a name to your menu file, for instance here we have given the name as my_menu." }, { "code": null, "e": 1887, "s": 1673, "text": "Then hit OK. Now you can see the my_menu.xml file inside the menu folder. Woah, you just create your menu file in android studio. So now we just write few lines of code to see that our menu file is working or not." }, { "code": null, "e": 1891, "s": 1887, "text": "XML" }, { "code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><menu xmlns:app=\"http://schemas.android.com/apk/res-auto\" xmlns:android=\"http://schemas.android.com/apk/res/android\"> <item android:id=\"@+id/new_game\" android:icon=\"@drawable/ic_baseline_local_see_24\" android:title=\"@string/new_game\"/> <item android:id=\"@+id/help\" android:icon=\"@drawable/ic_baseline_first_page_24\" android:title=\"@string/help\" /></menu>", "e": 2323, "s": 1891, "text": null }, { "code": null, "e": 2377, "s": 2323, "text": "Now look at the codes you see the menu tag i.e <menu>" }, { "code": null, "e": 2460, "s": 2377, "text": "<menu>: It is just a container and it holds the menu items or group of menu items." }, { "code": null, "e": 2491, "s": 2460, "text": "<item>: It creates menu item " }, { "code": null, "e": 2579, "s": 2491, "text": "Title and icon properties are self-explanatory so I don’t think I have to explain them." }, { "code": null, "e": 2743, "s": 2579, "text": "Note: Look at the above code, android: icon, those are the icon that we have created. In your case just look at your drawable folder and give your icon name there." }, { "code": null, "e": 2834, "s": 2743, "text": "Ok, we just completed our 80% of work now just inflate our menu to our MainActvity.kt file" }, { "code": null, "e": 2841, "s": 2834, "text": "Kotlin" }, { "code": "import androidx.appcompat.app.AppCompatActivityimport android.os.Bundleimport android.view.Menuimport android.view.MenuInflater class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) } // look at this section override fun onCreateOptionsMenu(menu: Menu?): Boolean { val inflater: MenuInflater = menuInflater inflater.inflate(R.menu.my_menu,menu) return super.onCreateOptionsMenu(menu) }}", "e": 3397, "s": 2841, "text": null }, { "code": null, "e": 3546, "s": 3397, "text": "Just focus on the codes after the comment line that block of codes used to inflate our menu in our app. Now run your app and you can see the result." }, { "code": null, "e": 3561, "s": 3546, "text": "Android-Studio" }, { "code": null, "e": 3569, "s": 3561, "text": "Android" }, { "code": null, "e": 3577, "s": 3569, "text": "Android" }, { "code": null, "e": 3675, "s": 3577, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3744, "s": 3675, "text": "How to Add Views Dynamically and Store Data in Arraylist in Android?" }, { "code": null, "e": 3776, "s": 3744, "text": "Android SDK and it's Components" }, { "code": null, "e": 3815, "s": 3776, "text": "Flutter - Custom Bottom Navigation Bar" }, { "code": null, "e": 3864, "s": 3815, "text": "How to Communicate Between Fragments in Android?" }, { "code": null, "e": 3906, "s": 3864, "text": "Retrofit with Kotlin Coroutine in Android" }, { "code": null, "e": 3957, "s": 3906, "text": "How to Post Data to API using Retrofit in Android?" }, { "code": null, "e": 3980, "s": 3957, "text": "Flutter - Stack Widget" }, { "code": null, "e": 4016, "s": 3980, "text": "Introduction to Android Development" }, { "code": null, "e": 4060, "s": 4016, "text": "Activity Lifecycle in Android with Demo App" } ]
Python | Find keys with duplicate values in dictionary
07 Aug, 2019 Given a dictionary, the task is to find keys with duplicate values. Let’s discuss a few methods for the same. Method #1: Using Naive approachIn this method first, we convert dictionary values to keys with the inverse mapping and then find the duplicate keys # Python code to demonstrate # finding duplicate values from a dictionary # initialising dictionaryini_dict = {'a':1, 'b':2, 'c':3, 'd':2} # printing initial_dictionaryprint("initial_dictionary", str(ini_dict)) # finding duplicate values# from dictionary# using a naive approachrev_dict = {} for key, value in ini_dict.items(): rev_dict.setdefault(value, set()).add(key) result = [key for key, values in rev_dict.items() if len(values) > 1] # printing resultprint("duplicate values", str(result)) initial_dictionary {'c': 3, 'b': 2, 'd': 2, 'a': 1} duplicate values [2] Method #2: Using flipping dictionary # Python code to demonstrate # finding duplicate values from dictionary # initialising dictionaryini_dict = {'a':1, 'b':2, 'c':3, 'd':2} # printing initial_dictionaryprint("initial_dictionary", str(ini_dict)) # finding duplicate values# from dictionary using flipflipped = {} for key, value in ini_dict.items(): if value not in flipped: flipped[value] = [key] else: flipped[value].append(key) # printing resultprint("final_dictionary", str(flipped)) initial_dictionary {'a': 1, 'c': 3, 'd': 2, 'b': 2} final_dictionary {1: ['a'], 2: ['d', 'b'], 3: ['c']} Method #3: Using chain and set Suppose you need to find keys having duplicate values. # Python code to demonstrate # finding duplicate values from dictionaryfrom itertools import chain # initialising dictionaryini_dict = {'a':1, 'b':2, 'c':3, 'd':2} # printing initial_dictionaryprint("initial_dictionary", str(ini_dict)) # finding duplicate values# from dictionary using setrev_dict = {}for key, value in ini_dict.items(): rev_dict.setdefault(value, set()).add(key) result = set(chain.from_iterable( values for key, values in rev_dict.items() if len(values) > 1)) # printing resultprint("resultant key", str(result)) initial_dictionary {'b': 2, 'd': 2, 'c': 3, 'a': 1} resultant key {'d', 'b'} Instead of result = set(chain.from_iterable( values for key, values in rev_dict.items() if len(values) > 1)) Use this: result = filter(lambda x: len(x)>1, rev_dict.values())print(list(result)) AyeshaBhatnagar Python dictionary-programs python-dict Python Python Programs python-dict Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Python Classes and Objects Python | os.path.join() method Introduction To PYTHON Python OOPs Concepts Defaultdict in Python Python | Get dictionary keys as a list Python | Convert a list to dictionary Python | Convert string dictionary to dictionary Python Program for Fibonacci numbers
[ { "code": null, "e": 28, "s": 0, "text": "\n07 Aug, 2019" }, { "code": null, "e": 138, "s": 28, "text": "Given a dictionary, the task is to find keys with duplicate values. Let’s discuss a few methods for the same." }, { "code": null, "e": 286, "s": 138, "text": "Method #1: Using Naive approachIn this method first, we convert dictionary values to keys with the inverse mapping and then find the duplicate keys" }, { "code": "# Python code to demonstrate # finding duplicate values from a dictionary # initialising dictionaryini_dict = {'a':1, 'b':2, 'c':3, 'd':2} # printing initial_dictionaryprint(\"initial_dictionary\", str(ini_dict)) # finding duplicate values# from dictionary# using a naive approachrev_dict = {} for key, value in ini_dict.items(): rev_dict.setdefault(value, set()).add(key) result = [key for key, values in rev_dict.items() if len(values) > 1] # printing resultprint(\"duplicate values\", str(result))", "e": 825, "s": 286, "text": null }, { "code": null, "e": 899, "s": 825, "text": "initial_dictionary {'c': 3, 'b': 2, 'd': 2, 'a': 1}\nduplicate values [2]\n" }, { "code": null, "e": 937, "s": 899, "text": " Method #2: Using flipping dictionary" }, { "code": "# Python code to demonstrate # finding duplicate values from dictionary # initialising dictionaryini_dict = {'a':1, 'b':2, 'c':3, 'd':2} # printing initial_dictionaryprint(\"initial_dictionary\", str(ini_dict)) # finding duplicate values# from dictionary using flipflipped = {} for key, value in ini_dict.items(): if value not in flipped: flipped[value] = [key] else: flipped[value].append(key) # printing resultprint(\"final_dictionary\", str(flipped))", "e": 1412, "s": 937, "text": null }, { "code": null, "e": 1518, "s": 1412, "text": "initial_dictionary {'a': 1, 'c': 3, 'd': 2, 'b': 2}\nfinal_dictionary {1: ['a'], 2: ['d', 'b'], 3: ['c']}\n" }, { "code": null, "e": 1550, "s": 1518, "text": " Method #3: Using chain and set" }, { "code": null, "e": 1605, "s": 1550, "text": "Suppose you need to find keys having duplicate values." }, { "code": "# Python code to demonstrate # finding duplicate values from dictionaryfrom itertools import chain # initialising dictionaryini_dict = {'a':1, 'b':2, 'c':3, 'd':2} # printing initial_dictionaryprint(\"initial_dictionary\", str(ini_dict)) # finding duplicate values# from dictionary using setrev_dict = {}for key, value in ini_dict.items(): rev_dict.setdefault(value, set()).add(key) result = set(chain.from_iterable( values for key, values in rev_dict.items() if len(values) > 1)) # printing resultprint(\"resultant key\", str(result))", "e": 2163, "s": 1605, "text": null }, { "code": null, "e": 2241, "s": 2163, "text": "initial_dictionary {'b': 2, 'd': 2, 'c': 3, 'a': 1}\nresultant key {'d', 'b'}\n" }, { "code": null, "e": 2252, "s": 2241, "text": "Instead of" }, { "code": "result = set(chain.from_iterable( values for key, values in rev_dict.items() if len(values) > 1))", "e": 2366, "s": 2252, "text": null }, { "code": null, "e": 2376, "s": 2366, "text": "Use this:" }, { "code": "result = filter(lambda x: len(x)>1, rev_dict.values())print(list(result))", "e": 2450, "s": 2376, "text": null }, { "code": null, "e": 2466, "s": 2450, "text": "AyeshaBhatnagar" }, { "code": null, "e": 2493, "s": 2466, "text": "Python dictionary-programs" }, { "code": null, "e": 2505, "s": 2493, "text": "python-dict" }, { "code": null, "e": 2512, "s": 2505, "text": "Python" }, { "code": null, "e": 2528, "s": 2512, "text": "Python Programs" }, { "code": null, "e": 2540, "s": 2528, "text": "python-dict" }, { "code": null, "e": 2638, "s": 2540, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2670, "s": 2638, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 2697, "s": 2670, "text": "Python Classes and Objects" }, { "code": null, "e": 2728, "s": 2697, "text": "Python | os.path.join() method" }, { "code": null, "e": 2751, "s": 2728, "text": "Introduction To PYTHON" }, { "code": null, "e": 2772, "s": 2751, "text": "Python OOPs Concepts" }, { "code": null, "e": 2794, "s": 2772, "text": "Defaultdict in Python" }, { "code": null, "e": 2833, "s": 2794, "text": "Python | Get dictionary keys as a list" }, { "code": null, "e": 2871, "s": 2833, "text": "Python | Convert a list to dictionary" }, { "code": null, "e": 2920, "s": 2871, "text": "Python | Convert string dictionary to dictionary" } ]
HTML dt Tag - GeeksforGeeks
17 Mar, 2022 The <dt> tag in HTML is used to specify the description list. It is used inside the <dl> element. It is usually followed by a <dd> tag. The subsequent <dd> elements provides some related text associated with the term specified using <dt>. Syntax: <dt> Content... </dt> Example: HTML <!DOCTYPE html> <html> <body> <h1>GeeksforGeeks</h1> <h2><dt> Tag</h2> <dl> <!-- HTML dt tag --> <dt>Geeks Classes</dt> <dd>It is an extensive classroom programme for enhancing DS and Algo concepts.</dd><br> <!-- HTML dt tag --> <dt>Fork Python</dt> <dd>It is a course designed for beginners in python.</dd><br> <!-- HTML dt tag --> <dt>Interview Preparation</dt> <dd>It is a course designed for preparation of interviews in top product based companies.</dd> </dl> </body> </html> Output: Supported Browsers: Google Chrome Internet Explorer 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. shubhamyadav4 HTML-Tags Picked HTML 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 set the default value for an HTML <select> element ? How to set input type date in dd-mm-yyyy format using HTML ? Hide or show elements in HTML using display property How to Insert Form Data into Database using PHP ? REST API (Introduction) CSS to put icon inside an input element in a form Types of CSS (Cascading Style Sheet)
[ { "code": null, "e": 23049, "s": 23021, "text": "\n17 Mar, 2022" }, { "code": null, "e": 23289, "s": 23049, "text": "The <dt> tag in HTML is used to specify the description list. It is used inside the <dl> element. It is usually followed by a <dd> tag. The subsequent <dd> elements provides some related text associated with the term specified using <dt>. " }, { "code": null, "e": 23298, "s": 23289, "text": "Syntax: " }, { "code": null, "e": 23320, "s": 23298, "text": "<dt> Content... </dt>" }, { "code": null, "e": 23331, "s": 23320, "text": "Example: " }, { "code": null, "e": 23336, "s": 23331, "text": "HTML" }, { "code": "<!DOCTYPE html> <html> <body> <h1>GeeksforGeeks</h1> <h2><dt> Tag</h2> <dl> <!-- HTML dt tag --> <dt>Geeks Classes</dt> <dd>It is an extensive classroom programme for enhancing DS and Algo concepts.</dd><br> <!-- HTML dt tag --> <dt>Fork Python</dt> <dd>It is a course designed for beginners in python.</dd><br> <!-- HTML dt tag --> <dt>Interview Preparation</dt> <dd>It is a course designed for preparation of interviews in top product based companies.</dd> </dl> </body> </html> ", "e": 24025, "s": 23336, "text": null }, { "code": null, "e": 24035, "s": 24025, "text": "Output: " }, { "code": null, "e": 24058, "s": 24035, "text": "Supported Browsers: " }, { "code": null, "e": 24072, "s": 24058, "text": "Google Chrome" }, { "code": null, "e": 24090, "s": 24072, "text": "Internet Explorer" }, { "code": null, "e": 24098, "s": 24090, "text": "Firefox" }, { "code": null, "e": 24104, "s": 24098, "text": "Opera" }, { "code": null, "e": 24111, "s": 24104, "text": "Safari" }, { "code": null, "e": 24250, "s": 24113, "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": 24264, "s": 24250, "text": "shubhamyadav4" }, { "code": null, "e": 24274, "s": 24264, "text": "HTML-Tags" }, { "code": null, "e": 24281, "s": 24274, "text": "Picked" }, { "code": null, "e": 24286, "s": 24281, "text": "HTML" }, { "code": null, "e": 24291, "s": 24286, "text": "HTML" }, { "code": null, "e": 24389, "s": 24291, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 24398, "s": 24389, "text": "Comments" }, { "code": null, "e": 24411, "s": 24398, "text": "Old Comments" }, { "code": null, "e": 24473, "s": 24411, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 24523, "s": 24473, "text": "How to insert spaces/tabs in text using HTML/CSS?" }, { "code": null, "e": 24571, "s": 24523, "text": "How to update Node.js and NPM to next version ?" }, { "code": null, "e": 24631, "s": 24571, "text": "How to set the default value for an HTML <select> element ?" }, { "code": null, "e": 24692, "s": 24631, "text": "How to set input type date in dd-mm-yyyy format using HTML ?" }, { "code": null, "e": 24745, "s": 24692, "text": "Hide or show elements in HTML using display property" }, { "code": null, "e": 24795, "s": 24745, "text": "How to Insert Form Data into Database using PHP ?" }, { "code": null, "e": 24819, "s": 24795, "text": "REST API (Introduction)" }, { "code": null, "e": 24869, "s": 24819, "text": "CSS to put icon inside an input element in a form" } ]
React Native - Status Bar
In this chapter, we will show you how to control the status bar appearance in React Native. The Status bar is easy to use and all you need to do is set properties to change it. The hidden property can be used to hide the status bar. In our example it is set to false. This is default value. The barStyle can have three values – dark-content, light-content and default. This component has several other properties that can be used. Some of them are Android or IOS specific. You can check it in official documentation. import React, { Component } from 'react'; import { StatusBar } from 'react-native' const App = () => { return ( <StatusBar barStyle = "dark-content" hidden = {false} backgroundColor = "#00BCD4" translucent = {true}/> ) } export default App If we run the app, the status bar will be visible and content will have dark color. 20 Lectures 1.5 hours Anadi Sharma 61 Lectures 6.5 hours A To Z Mentor 40 Lectures 4.5 hours Eduonix Learning Solutions 56 Lectures 12.5 hours Eduonix Learning Solutions 62 Lectures 4.5 hours Senol Atac 67 Lectures 4.5 hours Senol Atac Print Add Notes Bookmark this page
[ { "code": null, "e": 2436, "s": 2344, "text": "In this chapter, we will show you how to control the status bar appearance in React Native." }, { "code": null, "e": 2521, "s": 2436, "text": "The Status bar is easy to use and all you need to do is set properties to change it." }, { "code": null, "e": 2635, "s": 2521, "text": "The hidden property can be used to hide the status bar. In our example it is set to false. This is default value." }, { "code": null, "e": 2713, "s": 2635, "text": "The barStyle can have three values – dark-content, light-content and default." }, { "code": null, "e": 2861, "s": 2713, "text": "This component has several other properties that can be used. Some of them are Android or IOS specific. You can check it in official documentation." }, { "code": null, "e": 3114, "s": 2861, "text": "import React, { Component } from 'react';\nimport { StatusBar } from 'react-native'\n\nconst App = () => {\n return (\n <StatusBar barStyle = \"dark-content\" hidden = {false} backgroundColor = \"#00BCD4\" translucent = {true}/>\n )\n}\nexport default App" }, { "code": null, "e": 3198, "s": 3114, "text": "If we run the app, the status bar will be visible and content will have dark color." }, { "code": null, "e": 3233, "s": 3198, "text": "\n 20 Lectures \n 1.5 hours \n" }, { "code": null, "e": 3247, "s": 3233, "text": " Anadi Sharma" }, { "code": null, "e": 3282, "s": 3247, "text": "\n 61 Lectures \n 6.5 hours \n" }, { "code": null, "e": 3297, "s": 3282, "text": " A To Z Mentor" }, { "code": null, "e": 3332, "s": 3297, "text": "\n 40 Lectures \n 4.5 hours \n" }, { "code": null, "e": 3360, "s": 3332, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 3396, "s": 3360, "text": "\n 56 Lectures \n 12.5 hours \n" }, { "code": null, "e": 3424, "s": 3396, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 3459, "s": 3424, "text": "\n 62 Lectures \n 4.5 hours \n" }, { "code": null, "e": 3471, "s": 3459, "text": " Senol Atac" }, { "code": null, "e": 3506, "s": 3471, "text": "\n 67 Lectures \n 4.5 hours \n" }, { "code": null, "e": 3518, "s": 3506, "text": " Senol Atac" }, { "code": null, "e": 3525, "s": 3518, "text": " Print" }, { "code": null, "e": 3536, "s": 3525, "text": " Add Notes" } ]
While Statement Implementation
There is no direct while statement available in Batch Script but we can do an implementation of this loop very easily by using the if statement and labels. The following diagram shows the diagrammatic explanation of this loop. The first part of the while implementation is to set the counters which will be used to control the evaluation of the ‘if’ condition. We then define our label which will be used to embody the entire code for the while loop implementation. The ‘if’ condition evaluates an expression. If the expression evaluates to true, the code block is executed. If the condition evaluates to false then the loop is exited. When the code block is executed, it will return back to the label statement for execution again. Following is the syntax of the general implementation of the while statement. Set counters :label If (expression) ( Do_something Increment counter Go back to :label ) The entire code for the while implementation is placed inside of a label. The entire code for the while implementation is placed inside of a label. The counter variables must be set or initialized before the while loop implementation starts. The counter variables must be set or initialized before the while loop implementation starts. The expression for the while condition is done using the ‘if’ statement. If the expression evaluates to true then the relevant code inside the ‘if’ loop is executed. The expression for the while condition is done using the ‘if’ statement. If the expression evaluates to true then the relevant code inside the ‘if’ loop is executed. A counter needs to be properly incremented inside of ‘if’ statement so that the while implementation can terminate at some point in time. A counter needs to be properly incremented inside of ‘if’ statement so that the while implementation can terminate at some point in time. Finally, we will go back to our label so that we can evaluate our ‘if’ statement again. Finally, we will go back to our label so that we can evaluate our ‘if’ statement again. Following is an example of a while loop statement. @echo off SET /A "index = 1" SET /A "count = 5" :while if %index% leq %count% ( echo The value of index is %index% SET /A "index = index + 1" goto :while ) In the above example, we are first initializing the value of an index integer variable to 1. Then our condition in the ‘if’ loop is that we are evaluating the condition of the expression to be that index should it be less than the value of the count variable. Till the value of index is less than 5, we will print the value of index and then increment the value of index. The above command produces the following output. The value of index is 1 The value of index is 2 The value of index is 3 The value of index is 4 The value of index is 5 Print Add Notes Bookmark this page
[ { "code": null, "e": 2325, "s": 2169, "text": "There is no direct while statement available in Batch Script but we can do an implementation of this loop very easily by using the if statement and labels." }, { "code": null, "e": 2396, "s": 2325, "text": "The following diagram shows the diagrammatic explanation of this loop." }, { "code": null, "e": 2902, "s": 2396, "text": "The first part of the while implementation is to set the counters which will be used to control the evaluation of the ‘if’ condition. We then define our label which will be used to embody the entire code for the while loop implementation. The ‘if’ condition evaluates an expression. If the expression evaluates to true, the code block is executed. If the condition evaluates to false then the loop is exited. When the code block is executed, it will return back to the label statement for execution again." }, { "code": null, "e": 2980, "s": 2902, "text": "Following is the syntax of the general implementation of the while statement." }, { "code": null, "e": 3079, "s": 2980, "text": "Set counters\n:label\nIf (expression) (\n Do_something\n Increment counter\n Go back to :label\n)\n" }, { "code": null, "e": 3153, "s": 3079, "text": "The entire code for the while implementation is placed inside of a label." }, { "code": null, "e": 3227, "s": 3153, "text": "The entire code for the while implementation is placed inside of a label." }, { "code": null, "e": 3321, "s": 3227, "text": "The counter variables must be set or initialized before the while loop implementation starts." }, { "code": null, "e": 3415, "s": 3321, "text": "The counter variables must be set or initialized before the while loop implementation starts." }, { "code": null, "e": 3581, "s": 3415, "text": "The expression for the while condition is done using the ‘if’ statement. If the expression evaluates to true then the relevant code inside the ‘if’ loop is executed." }, { "code": null, "e": 3747, "s": 3581, "text": "The expression for the while condition is done using the ‘if’ statement. If the expression evaluates to true then the relevant code inside the ‘if’ loop is executed." }, { "code": null, "e": 3885, "s": 3747, "text": "A counter needs to be properly incremented inside of ‘if’ statement so that the while implementation can terminate at some point in time." }, { "code": null, "e": 4023, "s": 3885, "text": "A counter needs to be properly incremented inside of ‘if’ statement so that the while implementation can terminate at some point in time." }, { "code": null, "e": 4111, "s": 4023, "text": "Finally, we will go back to our label so that we can evaluate our ‘if’ statement again." }, { "code": null, "e": 4199, "s": 4111, "text": "Finally, we will go back to our label so that we can evaluate our ‘if’ statement again." }, { "code": null, "e": 4250, "s": 4199, "text": "Following is an example of a while loop statement." }, { "code": null, "e": 4415, "s": 4250, "text": "@echo off\nSET /A \"index = 1\"\nSET /A \"count = 5\"\n:while\nif %index% leq %count% (\n echo The value of index is %index%\n SET /A \"index = index + 1\"\n goto :while\n)" }, { "code": null, "e": 4787, "s": 4415, "text": "In the above example, we are first initializing the value of an index integer variable to 1. Then our condition in the ‘if’ loop is that we are evaluating the condition of the expression to be that index should it be less than the value of the count variable. Till the value of index is less than 5, we will print the value of index and then increment the value of index." }, { "code": null, "e": 4836, "s": 4787, "text": "The above command produces the following output." }, { "code": null, "e": 4957, "s": 4836, "text": "The value of index is 1\nThe value of index is 2\nThe value of index is 3\nThe value of index is 4\nThe value of index is 5\n" }, { "code": null, "e": 4964, "s": 4957, "text": " Print" }, { "code": null, "e": 4975, "s": 4964, "text": " Add Notes" } ]
iBATIS - Update Operation
We discussed, in the last chapter, how to perform READ operation on a table using iBATIS. This chapter explains how you can update records in a table using iBATIS. We have the following EMPLOYEE table in MySQL − CREATE TABLE EMPLOYEE ( id INT NOT NULL auto_increment, first_name VARCHAR(20) default NULL, last_name VARCHAR(20) default NULL, salary INT default NULL, PRIMARY KEY (id) ); This table has only one record as follows − mysql> select * from EMPLOYEE; +----+------------+-----------+--------+ | id | first_name | last_name | salary | +----+------------+-----------+--------+ | 1 | Zara | Ali | 5000 | +----+------------+-----------+--------+ 1 row in set (0.00 sec) To perform udpate operation, you would need to modify Employee.java file as follows − public class Employee { private int id; private String first_name; private String last_name; private int salary; /* Define constructors for the Employee class. */ public Employee() {} public Employee(String fname, String lname, int salary) { this.first_name = fname; this.last_name = lname; this.salary = salary; } /* Here are the required method definitions */ public int getId() { return id; } public void setId(int id) { this.id = id; } public String getFirstName() { return first_name; } public void setFirstName(String fname) { this.first_name = fname; } public String getLastName() { return last_name; } public void setlastName(String lname) { this.last_name = lname; } public int getSalary() { return salary; } public void setSalary(int salary) { this.salary = salary; } } /* End of Employee */ To define SQL mapping statement using iBATIS, we would add <update> tag in Employee.xml and inside this tag definition, we would define an "id" which will be used in IbatisUpdate.java file for executing SQL UPDATE query on database. <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE sqlMap PUBLIC "-//ibatis.apache.org//DTD SQL Map 2.0//EN" "http://ibatis.apache.org/dtd/sql-map-2.dtd"> <sqlMap namespace="Employee"> <insert id="insert" parameterClass="Employee"> INSERT INTO EMPLOYEE(first_name, last_name, salary) values (#first_name#, #last_name#, #salary#) <selectKey resultClass="int" keyProperty="id"> select last_insert_id() as id </selectKey> </insert> <select id="getAll" resultClass="Employee"> SELECT * FROM EMPLOYEE </select> <update id="update" parameterClass="Employee"> UPDATE EMPLOYEE SET first_name = #first_name# WHERE id = #id# </update> </sqlMap> This file has application level logic to update records into the Employee table − import com.ibatis.common.resources.Resources; import com.ibatis.sqlmap.client.SqlMapClient; import com.ibatis.sqlmap.client.SqlMapClientBuilder; import java.io.*; import java.sql.SQLException; import java.util.*; public class IbatisUpdate{ public static void main(String[] args) throws IOException,SQLException{ Reader rd = Resources.getResourceAsReader("SqlMapConfig.xml"); SqlMapClient smc = SqlMapClientBuilder.buildSqlMapClient(rd); /* This would update one record in Employee table. */ System.out.println("Going to update record....."); Employee rec = new Employee(); rec.setId(1); rec.setFirstName( "Roma"); smc.update("Employee.update", rec ); System.out.println("Record updated Successfully "); System.out.println("Going to read records....."); List <Employee> ems = (List<Employee>) smc.queryForList("Employee.getAll", null); Employee em = null; for (Employee e : ems) { System.out.print(" " + e.getId()); System.out.print(" " + e.getFirstName()); System.out.print(" " + e.getLastName()); System.out.print(" " + e.getSalary()); em = e; System.out.println(""); } System.out.println("Records Read Successfully "); } } Here are the steps to compile and run the above-mentioned software. Make sure you have set PATH and CLASSPATH appropriately before proceeding for compilation and execution. Create Employee.xml as shown above. Create Employee.java as shown above and compile it. Create IbatisUpdate.java as shown above and compile it. Execute IbatisUpdate binary to run the program. You would get following result, and a record would be updated in EMPLOYEE table and later, the same record would be read from the EMPLOYEE table. Going to update record..... Record updated Successfully Going to read records..... 1 Roma Ali 5000 Records Read Successfully Print Add Notes Bookmark this page
[ { "code": null, "e": 2008, "s": 1844, "text": "We discussed, in the last chapter, how to perform READ operation on a table using iBATIS. This chapter explains how you can update records in a table using iBATIS." }, { "code": null, "e": 2056, "s": 2008, "text": "We have the following EMPLOYEE table in MySQL −" }, { "code": null, "e": 2252, "s": 2056, "text": "CREATE TABLE EMPLOYEE (\n id INT NOT NULL auto_increment,\n first_name VARCHAR(20) default NULL,\n last_name VARCHAR(20) default NULL,\n salary INT default NULL,\n PRIMARY KEY (id)\n);\n" }, { "code": null, "e": 2296, "s": 2252, "text": "This table has only one record as follows −" }, { "code": null, "e": 2557, "s": 2296, "text": "mysql> select * from EMPLOYEE;\n+----+------------+-----------+--------+\n| id | first_name | last_name | salary |\n+----+------------+-----------+--------+\n| 1 | Zara | Ali | 5000 |\n+----+------------+-----------+--------+\n1 row in set (0.00 sec)\n" }, { "code": null, "e": 2643, "s": 2557, "text": "To perform udpate operation, you would need to modify Employee.java file as follows −" }, { "code": null, "e": 3610, "s": 2643, "text": "public class Employee {\n private int id;\n private String first_name; \n private String last_name; \n private int salary; \n\n /* Define constructors for the Employee class. */\n public Employee() {}\n \n public Employee(String fname, String lname, int salary) {\n this.first_name = fname;\n this.last_name = lname;\n this.salary = salary;\n }\n\n /* Here are the required method definitions */\n public int getId() {\n return id;\n }\n\t\n public void setId(int id) {\n this.id = id;\n }\n\t\n public String getFirstName() {\n return first_name;\n }\n\t\n public void setFirstName(String fname) {\n this.first_name = fname;\n }\n\t\n public String getLastName() {\n return last_name;\n }\n public void setlastName(String lname) {\n this.last_name = lname;\n }\n\t\n public int getSalary() {\n return salary;\n }\n\t\n public void setSalary(int salary) {\n this.salary = salary;\n }\n\n} /* End of Employee */" }, { "code": null, "e": 3843, "s": 3610, "text": "To define SQL mapping statement using iBATIS, we would add <update> tag in Employee.xml and inside this tag definition, we would define an \"id\" which will be used in IbatisUpdate.java file for executing SQL UPDATE query on database." }, { "code": null, "e": 4562, "s": 3843, "text": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!DOCTYPE sqlMap PUBLIC \"-//ibatis.apache.org//DTD SQL Map 2.0//EN\" \"http://ibatis.apache.org/dtd/sql-map-2.dtd\">\n\n<sqlMap namespace=\"Employee\">\n\n <insert id=\"insert\" parameterClass=\"Employee\">\n INSERT INTO EMPLOYEE(first_name, last_name, salary)\n values (#first_name#, #last_name#, #salary#)\n\n <selectKey resultClass=\"int\" keyProperty=\"id\">\n select last_insert_id() as id\n </selectKey>\n </insert>\n\n <select id=\"getAll\" resultClass=\"Employee\">\n SELECT * FROM EMPLOYEE\n </select>\n\n <update id=\"update\" parameterClass=\"Employee\">\n UPDATE EMPLOYEE\n SET first_name = #first_name#\n WHERE id = #id#\n </update>\n\t\n</sqlMap>" }, { "code": null, "e": 4644, "s": 4562, "text": "This file has application level logic to update records into the Employee table −" }, { "code": null, "e": 5949, "s": 4644, "text": "import com.ibatis.common.resources.Resources;\nimport com.ibatis.sqlmap.client.SqlMapClient;\nimport com.ibatis.sqlmap.client.SqlMapClientBuilder;\n\nimport java.io.*;\nimport java.sql.SQLException;\nimport java.util.*;\n\npublic class IbatisUpdate{\n public static void main(String[] args)\n throws IOException,SQLException{\n Reader rd = Resources.getResourceAsReader(\"SqlMapConfig.xml\");\n SqlMapClient smc = SqlMapClientBuilder.buildSqlMapClient(rd);\n\n /* This would update one record in Employee table. */\n System.out.println(\"Going to update record.....\");\n Employee rec = new Employee();\n rec.setId(1);\n rec.setFirstName( \"Roma\");\n smc.update(\"Employee.update\", rec );\n System.out.println(\"Record updated Successfully \");\n\n System.out.println(\"Going to read records.....\");\n List <Employee> ems = (List<Employee>)\n smc.queryForList(\"Employee.getAll\", null);\n Employee em = null;\n\t\t\n for (Employee e : ems) {\n System.out.print(\" \" + e.getId());\n System.out.print(\" \" + e.getFirstName());\n System.out.print(\" \" + e.getLastName());\n System.out.print(\" \" + e.getSalary());\n em = e; \n System.out.println(\"\");\n } \n\n System.out.println(\"Records Read Successfully \");\n }\n} " }, { "code": null, "e": 6122, "s": 5949, "text": "Here are the steps to compile and run the above-mentioned software. Make sure you have set PATH and CLASSPATH appropriately before proceeding for compilation and execution." }, { "code": null, "e": 6158, "s": 6122, "text": "Create Employee.xml as shown above." }, { "code": null, "e": 6210, "s": 6158, "text": "Create Employee.java as shown above and compile it." }, { "code": null, "e": 6266, "s": 6210, "text": "Create IbatisUpdate.java as shown above and compile it." }, { "code": null, "e": 6314, "s": 6266, "text": "Execute IbatisUpdate binary to run the program." }, { "code": null, "e": 6460, "s": 6314, "text": "You would get following result, and a record would be updated in EMPLOYEE table and later, the same record would be read from the EMPLOYEE table." }, { "code": null, "e": 6592, "s": 6460, "text": "Going to update record.....\nRecord updated Successfully\nGoing to read records.....\n 1 Roma Ali 5000\nRecords Read Successfully\n" }, { "code": null, "e": 6599, "s": 6592, "text": " Print" }, { "code": null, "e": 6610, "s": 6599, "text": " Add Notes" } ]
Different Ways to Add Parentheses in C++
Suppose we have a string of numbers and operators, we have to find all possible results from computing all the different possible ways to group the numbers and operators. Here the valid operators are +, - and *. So if the input is like “2*3-4*5”, then the output will be [-34, -14, -10, -10, 10]. This is because − (2*(3-(4*5))) = -34 (2*(3-(4*5))) = -34 ((2*3)-(4*5)) = -14 ((2*3)-(4*5)) = -14 ((2*(3-4))*5) = -10 ((2*(3-4))*5) = -10 (2*((3-4)*5)) = -10 (2*((3-4)*5)) = -10 (((2*3)-4)*5) = 10 (((2*3)-4)*5) = 10 To solve this, we will follow these steps − Define a map called a memo. Define a map called a memo. Define a method called solve(). This will take the input string as input. Define a method called solve(). This will take the input string as input. create an array called ret create an array called ret if the memo has input, then return memo[input] if the memo has input, then return memo[input] for i in range 0 to the size of input string −if input[i] is any supported operator, thenan array part1 := solve(substring of input from 0 to i - 1)an array part2 := solve(substring of input from i to end of string)for j in range 0 to size of part1for k in range 0 to size of part2if input[i] is addition, thenperform part[j] + part[k] and add into retif input[i] is multiplication, thenperform part[j] * part[k] and add into retif input[i] is subtraction, thenperform part[j] - part[k] and add into ret for i in range 0 to the size of input string − if input[i] is any supported operator, thenan array part1 := solve(substring of input from 0 to i - 1)an array part2 := solve(substring of input from i to end of string)for j in range 0 to size of part1for k in range 0 to size of part2if input[i] is addition, thenperform part[j] + part[k] and add into retif input[i] is multiplication, thenperform part[j] * part[k] and add into retif input[i] is subtraction, thenperform part[j] - part[k] and add into ret if input[i] is any supported operator, then an array part1 := solve(substring of input from 0 to i - 1) an array part1 := solve(substring of input from 0 to i - 1) an array part2 := solve(substring of input from i to end of string) an array part2 := solve(substring of input from i to end of string) for j in range 0 to size of part1for k in range 0 to size of part2if input[i] is addition, thenperform part[j] + part[k] and add into retif input[i] is multiplication, thenperform part[j] * part[k] and add into retif input[i] is subtraction, thenperform part[j] - part[k] and add into ret for j in range 0 to size of part1 for k in range 0 to size of part2if input[i] is addition, thenperform part[j] + part[k] and add into retif input[i] is multiplication, thenperform part[j] * part[k] and add into retif input[i] is subtraction, thenperform part[j] - part[k] and add into ret for k in range 0 to size of part2 if input[i] is addition, thenperform part[j] + part[k] and add into ret if input[i] is addition, then perform part[j] + part[k] and add into ret perform part[j] + part[k] and add into ret if input[i] is multiplication, thenperform part[j] * part[k] and add into ret if input[i] is multiplication, then perform part[j] * part[k] and add into ret perform part[j] * part[k] and add into ret if input[i] is subtraction, thenperform part[j] - part[k] and add into ret if input[i] is subtraction, then perform part[j] - part[k] and add into ret perform part[j] - part[k] and add into ret if ret is empty, then return input string as an integer if ret is empty, then return input string as an integer memo[input] := ret, and return ret memo[input] := ret, and return ret Let us see the following implementation to get a better understanding − Live Demo #include <bits/stdc++.h> using namespace std; void print_vector(vector<auto> v){ cout << "["; for(int i = 0; i<v.size(); i++){ cout << v[i] << ", "; } cout << "]"<<endl; } class Solution { public: map <string, vector<int>> memo; vector<int> diffWaysToCompute(string input) { vector <int> ret; if(memo.count(input)) return memo[input]; for(int i = 0; i < input.size(); i++){ if(input[i] == '+' || input[i] == '*' || input[i] == '-'){ vector <int> part1 = diffWaysToCompute(input.substr(0, i)); vector <int> part2 = diffWaysToCompute(input.substr(i + 1)); for(int j = 0; j < part1.size(); j++ ){ for(int k = 0; k < part2.size(); k++){ if(input[i] == '+'){ ret.push_back(part1[j] + part2[k]); } else if(input[i] == '*'){ ret.push_back(part1[j] * part2[k]); } else { ret.push_back(part1[j] - part2[k]); } } } } } if(ret.empty()){ ret.push_back(stoi(input)); } return memo[input] = ret; } }; main(){ Solution ob; print_vector(ob.diffWaysToCompute("2*3-4*5")); } "2*3-4*5" [-34, -10, -14, -10, 10, ]
[ { "code": null, "e": 1377, "s": 1062, "text": "Suppose we have a string of numbers and operators, we have to find all possible results from computing all the different possible ways to group the numbers and operators. Here the valid operators are +, - and *. So if the input is like “2*3-4*5”, then the output will be [-34, -14, -10, -10, 10]. This is because −" }, { "code": null, "e": 1397, "s": 1377, "text": "(2*(3-(4*5))) = -34" }, { "code": null, "e": 1417, "s": 1397, "text": "(2*(3-(4*5))) = -34" }, { "code": null, "e": 1437, "s": 1417, "text": "((2*3)-(4*5)) = -14" }, { "code": null, "e": 1457, "s": 1437, "text": "((2*3)-(4*5)) = -14" }, { "code": null, "e": 1477, "s": 1457, "text": "((2*(3-4))*5) = -10" }, { "code": null, "e": 1497, "s": 1477, "text": "((2*(3-4))*5) = -10" }, { "code": null, "e": 1517, "s": 1497, "text": "(2*((3-4)*5)) = -10" }, { "code": null, "e": 1537, "s": 1517, "text": "(2*((3-4)*5)) = -10" }, { "code": null, "e": 1556, "s": 1537, "text": "(((2*3)-4)*5) = 10" }, { "code": null, "e": 1575, "s": 1556, "text": "(((2*3)-4)*5) = 10" }, { "code": null, "e": 1619, "s": 1575, "text": "To solve this, we will follow these steps −" }, { "code": null, "e": 1647, "s": 1619, "text": "Define a map called a memo." }, { "code": null, "e": 1675, "s": 1647, "text": "Define a map called a memo." }, { "code": null, "e": 1749, "s": 1675, "text": "Define a method called solve(). This will take the input string as input." }, { "code": null, "e": 1823, "s": 1749, "text": "Define a method called solve(). This will take the input string as input." }, { "code": null, "e": 1850, "s": 1823, "text": "create an array called ret" }, { "code": null, "e": 1877, "s": 1850, "text": "create an array called ret" }, { "code": null, "e": 1924, "s": 1877, "text": "if the memo has input, then return memo[input]" }, { "code": null, "e": 1971, "s": 1924, "text": "if the memo has input, then return memo[input]" }, { "code": null, "e": 2475, "s": 1971, "text": "for i in range 0 to the size of input string −if input[i] is any supported operator, thenan array part1 := solve(substring of input from 0 to i - 1)an array part2 := solve(substring of input from i to end of string)for j in range 0 to size of part1for k in range 0 to size of part2if input[i] is addition, thenperform part[j] + part[k] and add into retif input[i] is multiplication, thenperform part[j] * part[k] and add into retif input[i] is subtraction, thenperform part[j] - part[k] and add into ret" }, { "code": null, "e": 2522, "s": 2475, "text": "for i in range 0 to the size of input string −" }, { "code": null, "e": 2980, "s": 2522, "text": "if input[i] is any supported operator, thenan array part1 := solve(substring of input from 0 to i - 1)an array part2 := solve(substring of input from i to end of string)for j in range 0 to size of part1for k in range 0 to size of part2if input[i] is addition, thenperform part[j] + part[k] and add into retif input[i] is multiplication, thenperform part[j] * part[k] and add into retif input[i] is subtraction, thenperform part[j] - part[k] and add into ret" }, { "code": null, "e": 3024, "s": 2980, "text": "if input[i] is any supported operator, then" }, { "code": null, "e": 3084, "s": 3024, "text": "an array part1 := solve(substring of input from 0 to i - 1)" }, { "code": null, "e": 3144, "s": 3084, "text": "an array part1 := solve(substring of input from 0 to i - 1)" }, { "code": null, "e": 3212, "s": 3144, "text": "an array part2 := solve(substring of input from i to end of string)" }, { "code": null, "e": 3280, "s": 3212, "text": "an array part2 := solve(substring of input from i to end of string)" }, { "code": null, "e": 3569, "s": 3280, "text": "for j in range 0 to size of part1for k in range 0 to size of part2if input[i] is addition, thenperform part[j] + part[k] and add into retif input[i] is multiplication, thenperform part[j] * part[k] and add into retif input[i] is subtraction, thenperform part[j] - part[k] and add into ret" }, { "code": null, "e": 3603, "s": 3569, "text": "for j in range 0 to size of part1" }, { "code": null, "e": 3859, "s": 3603, "text": "for k in range 0 to size of part2if input[i] is addition, thenperform part[j] + part[k] and add into retif input[i] is multiplication, thenperform part[j] * part[k] and add into retif input[i] is subtraction, thenperform part[j] - part[k] and add into ret" }, { "code": null, "e": 3893, "s": 3859, "text": "for k in range 0 to size of part2" }, { "code": null, "e": 3965, "s": 3893, "text": "if input[i] is addition, thenperform part[j] + part[k] and add into ret" }, { "code": null, "e": 3995, "s": 3965, "text": "if input[i] is addition, then" }, { "code": null, "e": 4038, "s": 3995, "text": "perform part[j] + part[k] and add into ret" }, { "code": null, "e": 4081, "s": 4038, "text": "perform part[j] + part[k] and add into ret" }, { "code": null, "e": 4159, "s": 4081, "text": "if input[i] is multiplication, thenperform part[j] * part[k] and add into ret" }, { "code": null, "e": 4195, "s": 4159, "text": "if input[i] is multiplication, then" }, { "code": null, "e": 4238, "s": 4195, "text": "perform part[j] * part[k] and add into ret" }, { "code": null, "e": 4281, "s": 4238, "text": "perform part[j] * part[k] and add into ret" }, { "code": null, "e": 4356, "s": 4281, "text": "if input[i] is subtraction, thenperform part[j] - part[k] and add into ret" }, { "code": null, "e": 4389, "s": 4356, "text": "if input[i] is subtraction, then" }, { "code": null, "e": 4432, "s": 4389, "text": "perform part[j] - part[k] and add into ret" }, { "code": null, "e": 4475, "s": 4432, "text": "perform part[j] - part[k] and add into ret" }, { "code": null, "e": 4531, "s": 4475, "text": "if ret is empty, then return input string as an integer" }, { "code": null, "e": 4587, "s": 4531, "text": "if ret is empty, then return input string as an integer" }, { "code": null, "e": 4622, "s": 4587, "text": "memo[input] := ret, and return ret" }, { "code": null, "e": 4657, "s": 4622, "text": "memo[input] := ret, and return ret" }, { "code": null, "e": 4729, "s": 4657, "text": "Let us see the following implementation to get a better understanding −" }, { "code": null, "e": 4740, "s": 4729, "text": " Live Demo" }, { "code": null, "e": 6033, "s": 4740, "text": "#include <bits/stdc++.h>\nusing namespace std;\nvoid print_vector(vector<auto> v){\n cout << \"[\";\n for(int i = 0; i<v.size(); i++){\n cout << v[i] << \", \";\n }\n cout << \"]\"<<endl;\n}\nclass Solution {\n public:\n map <string, vector<int>> memo;\n vector<int> diffWaysToCompute(string input) {\n vector <int> ret;\n if(memo.count(input)) return memo[input];\n for(int i = 0; i < input.size(); i++){\n if(input[i] == '+' || input[i] == '*' || input[i] == '-'){\n vector <int> part1 = diffWaysToCompute(input.substr(0, i));\n vector <int> part2 = diffWaysToCompute(input.substr(i + 1));\n for(int j = 0; j < part1.size(); j++ ){\n for(int k = 0; k < part2.size(); k++){\n if(input[i] == '+'){\n ret.push_back(part1[j] + part2[k]);\n }\n else if(input[i] == '*'){\n ret.push_back(part1[j] * part2[k]);\n } else {\n ret.push_back(part1[j] - part2[k]);\n }\n }\n }\n }\n }\n if(ret.empty()){\n ret.push_back(stoi(input));\n }\n return memo[input] = ret;\n }\n};\nmain(){\n Solution ob;\n print_vector(ob.diffWaysToCompute(\"2*3-4*5\"));\n}" }, { "code": null, "e": 6043, "s": 6033, "text": "\"2*3-4*5\"" }, { "code": null, "e": 6070, "s": 6043, "text": "[-34, -10, -14, -10, 10, ]" } ]
Neural Network Optimization Algorithms | by Vadim Smolyakov | Towards Data Science
What are some of the popular optimization algorithms used for training neural networks? How do they compare? This article attempts to answer these questions using a Convolutional Neural Network (CNN) as an example trained on MNIST dataset with TensorFlow. SGD updates model parameters (theta) in the negative direction of the gradient (g) by taking a subset or a mini-batch of data of size (m): The neural network is represented by f(x(i); theta) where x(i) are the training data and y(i) are the training labels, the gradient of the loss L is computed with respect to model parameters theta. The learning rate (eps_k) determines the size of the step that the algorithm takes along the gradient (in the negative direction in the case of minimization and in the positive direction in the case of maximization). The learning rate is a function of iteration k and is a single most important hyper-parameter. A learning rate that is too high (e.g. > 0.1) can lead to parameter updates that miss the optimum value, a learning rate that is too low (e.g. < 1e-5) will result in unnecessarily long training time. A good strategy is to start with a learning rate of 1e-3 and use a learning rate schedule that reduces the learning rate as a function of iterations (e.g. a step scheduler that halves the learning rate every 4 epochs): def step_decay(epoch): lr_init = 0.001 drop = 0.5 epochs_drop = 4.0 lr_new = lr_init * \ math.pow(drop, math.floor((1+epoch)/epochs_drop)) return lr_new In general, we want the learning rate (eps_k) to satisfy the Robbins-Monroe conditions: The first condition ensures that the algorithm will be able to find a locally optimal solution regardless of the starting point and the second one controls oscillations. Momentum accumulates exponentially decaying moving average of past gradients and continues to move in their direction: Thus step size depends on how large and how aligned the sequence of gradients are, common values of momentum parameter alpha are 0.5 and 0.9. Nesterov Momentum is inspired by Nesterov’s accelerated gradient method: The difference between Nesterov and standard momentum is where the gradient is evaluated, with Nesterov’s momentum the gradient is evaluated after the current velocity is applied, thus Nesterov’s momentum adds a correction factor to the gradient. AdaGrad is an adaptive method for setting the learning rate [3]. Consider two scenarios in the Figure below. In the case of a slowly varying objective (left), the gradient would typically (at most points) have a small magnitude. As a result, we would need a large learning rate to quickly reach the optimum. In the case of a rapidly varying objective (right), the gradient would typically be very large. Using a large learning rate would result in very large steps, oscillating around but not reaching the optimum. These two situations occur because the learning rate is set independent of the gradient. AdaGrad solves this by accumulating squared norms of gradients seen so far and dividing the learning rate by the square root of this sum: As a result parameters that receive high gradients will have their effective learning rate reduced and parameters that receive small gradients will have their effective learning rate increased. The net effect is greater progress in the more gently sloped directions of parameter space and more cautious updates in the presence of large gradients. RMSProp modifies AdaGrad by changing the gradient accumulation into an exponentially weighted moving average, i.e. it discards history from the distant past [4]: Notice that AdaGrad implies a decreasing learning rate even if the gradients remain constant due to accumulation of gradients from the beginning of training. By introducing exponentially weighted moving average we are weighing recent past more heavily in comparison to distant past. As a result, RMSProp has been shown to be an effective and practical optimization algorithm for deep neural networks. Adam derives from “adaptive moments”, it can be seen as a variant on the combination of RMSProp and momentum, the update looks like RMSProp except that a smooth version of the gradient is used instead of the raw stochastic gradient, the full Adam update also includes a bias correction mechanism [5]: The recommended values are beta_1 = 0.9, beta_2 = 0.999, and eps = 1e-8. A simple CNN architecture was trained on MNIST dataset using TensorFlow with 1e-3 learning rate and cross-entropy loss using four different optimizers: SGD, Nesterov Momentum, RMSProp and Adam. The Figure below shows the value of the training loss vs iterations: We can see from the plot that Adam and Nesterov Momentum optimizers produce the lowest training loss! All code is available in the following ipython notebook. We compared different optimizers used in training neural networks and gained intuition for how they work. We found that SGD with Nesterov Momentum and Adam produce the best results when training a simple CNN on MNIST data in TensorFlow. [1] Ian Goodfellow et. al., “Deep Learning”, MIT Press, 2016 [2] Andrej Karpathy, http://cs231n.github.io/neural-networks-3/ [3] Duchi, J. ,Hazan, E. and Singer, Y. “Adaptive subgradient methods for online learning and stochastic optimization”, JMLR, 2011. [4] Tieleman, T. and Hinton, G. “Lecture 6.5 — RMSProp, COURSERA: Neural Networks for Machine Learning”, Technical Report, 2012. [5] Diederik Kingma and Jimmy Ba, “Adam: A Method for Stochastic Optimization”, ICLR, 2015
[ { "code": null, "e": 280, "s": 171, "text": "What are some of the popular optimization algorithms used for training neural networks? How do they compare?" }, { "code": null, "e": 427, "s": 280, "text": "This article attempts to answer these questions using a Convolutional Neural Network (CNN) as an example trained on MNIST dataset with TensorFlow." }, { "code": null, "e": 566, "s": 427, "text": "SGD updates model parameters (theta) in the negative direction of the gradient (g) by taking a subset or a mini-batch of data of size (m):" }, { "code": null, "e": 981, "s": 566, "text": "The neural network is represented by f(x(i); theta) where x(i) are the training data and y(i) are the training labels, the gradient of the loss L is computed with respect to model parameters theta. The learning rate (eps_k) determines the size of the step that the algorithm takes along the gradient (in the negative direction in the case of minimization and in the positive direction in the case of maximization)." }, { "code": null, "e": 1495, "s": 981, "text": "The learning rate is a function of iteration k and is a single most important hyper-parameter. A learning rate that is too high (e.g. > 0.1) can lead to parameter updates that miss the optimum value, a learning rate that is too low (e.g. < 1e-5) will result in unnecessarily long training time. A good strategy is to start with a learning rate of 1e-3 and use a learning rate schedule that reduces the learning rate as a function of iterations (e.g. a step scheduler that halves the learning rate every 4 epochs):" }, { "code": null, "e": 1675, "s": 1495, "text": "def step_decay(epoch): lr_init = 0.001 drop = 0.5 epochs_drop = 4.0 lr_new = lr_init * \\ math.pow(drop, math.floor((1+epoch)/epochs_drop)) return lr_new" }, { "code": null, "e": 1763, "s": 1675, "text": "In general, we want the learning rate (eps_k) to satisfy the Robbins-Monroe conditions:" }, { "code": null, "e": 1933, "s": 1763, "text": "The first condition ensures that the algorithm will be able to find a locally optimal solution regardless of the starting point and the second one controls oscillations." }, { "code": null, "e": 2052, "s": 1933, "text": "Momentum accumulates exponentially decaying moving average of past gradients and continues to move in their direction:" }, { "code": null, "e": 2194, "s": 2052, "text": "Thus step size depends on how large and how aligned the sequence of gradients are, common values of momentum parameter alpha are 0.5 and 0.9." }, { "code": null, "e": 2267, "s": 2194, "text": "Nesterov Momentum is inspired by Nesterov’s accelerated gradient method:" }, { "code": null, "e": 2514, "s": 2267, "text": "The difference between Nesterov and standard momentum is where the gradient is evaluated, with Nesterov’s momentum the gradient is evaluated after the current velocity is applied, thus Nesterov’s momentum adds a correction factor to the gradient." }, { "code": null, "e": 2623, "s": 2514, "text": "AdaGrad is an adaptive method for setting the learning rate [3]. Consider two scenarios in the Figure below." }, { "code": null, "e": 3029, "s": 2623, "text": "In the case of a slowly varying objective (left), the gradient would typically (at most points) have a small magnitude. As a result, we would need a large learning rate to quickly reach the optimum. In the case of a rapidly varying objective (right), the gradient would typically be very large. Using a large learning rate would result in very large steps, oscillating around but not reaching the optimum." }, { "code": null, "e": 3256, "s": 3029, "text": "These two situations occur because the learning rate is set independent of the gradient. AdaGrad solves this by accumulating squared norms of gradients seen so far and dividing the learning rate by the square root of this sum:" }, { "code": null, "e": 3603, "s": 3256, "text": "As a result parameters that receive high gradients will have their effective learning rate reduced and parameters that receive small gradients will have their effective learning rate increased. The net effect is greater progress in the more gently sloped directions of parameter space and more cautious updates in the presence of large gradients." }, { "code": null, "e": 3765, "s": 3603, "text": "RMSProp modifies AdaGrad by changing the gradient accumulation into an exponentially weighted moving average, i.e. it discards history from the distant past [4]:" }, { "code": null, "e": 4166, "s": 3765, "text": "Notice that AdaGrad implies a decreasing learning rate even if the gradients remain constant due to accumulation of gradients from the beginning of training. By introducing exponentially weighted moving average we are weighing recent past more heavily in comparison to distant past. As a result, RMSProp has been shown to be an effective and practical optimization algorithm for deep neural networks." }, { "code": null, "e": 4467, "s": 4166, "text": "Adam derives from “adaptive moments”, it can be seen as a variant on the combination of RMSProp and momentum, the update looks like RMSProp except that a smooth version of the gradient is used instead of the raw stochastic gradient, the full Adam update also includes a bias correction mechanism [5]:" }, { "code": null, "e": 4540, "s": 4467, "text": "The recommended values are beta_1 = 0.9, beta_2 = 0.999, and eps = 1e-8." }, { "code": null, "e": 4803, "s": 4540, "text": "A simple CNN architecture was trained on MNIST dataset using TensorFlow with 1e-3 learning rate and cross-entropy loss using four different optimizers: SGD, Nesterov Momentum, RMSProp and Adam. The Figure below shows the value of the training loss vs iterations:" }, { "code": null, "e": 4905, "s": 4803, "text": "We can see from the plot that Adam and Nesterov Momentum optimizers produce the lowest training loss!" }, { "code": null, "e": 4962, "s": 4905, "text": "All code is available in the following ipython notebook." }, { "code": null, "e": 5199, "s": 4962, "text": "We compared different optimizers used in training neural networks and gained intuition for how they work. We found that SGD with Nesterov Momentum and Adam produce the best results when training a simple CNN on MNIST data in TensorFlow." }, { "code": null, "e": 5260, "s": 5199, "text": "[1] Ian Goodfellow et. al., “Deep Learning”, MIT Press, 2016" }, { "code": null, "e": 5324, "s": 5260, "text": "[2] Andrej Karpathy, http://cs231n.github.io/neural-networks-3/" }, { "code": null, "e": 5456, "s": 5324, "text": "[3] Duchi, J. ,Hazan, E. and Singer, Y. “Adaptive subgradient methods for online learning and stochastic optimization”, JMLR, 2011." }, { "code": null, "e": 5585, "s": 5456, "text": "[4] Tieleman, T. and Hinton, G. “Lecture 6.5 — RMSProp, COURSERA: Neural Networks for Machine Learning”, Technical Report, 2012." } ]
SAP ABAP - Function Modules
Function modules make up a major part of a SAP system, because for years SAP has modularized code using function modules, allowing for code reuse, by themselves, their developers and also by their customers. Function modules are sub-programs that contain a set of reusable statements with importing and exporting parameters. Unlike Include programs, function modules can be executed independently. SAP system contains several predefined function modules that can be called from any ABAP program. The function group acts as a kind of container for a number of function modules that would logically belong together. For instance, the function modules for an HR payroll system would be put together into a function group. To look at how to create function modules, the function builder must be explored. You can find the function builder with transaction code SE37. Just type a part of a function module name with a wild card character to demonstrate the way function modules can be searched for. Type *amount* and then press the F4 key. The results of the search will be displayed in a new window. The function modules are displayed in the lines with blue background and their function groups in pink lines. You may look further at the function group ISOC by using the Object Navigator screen (Transaction SE80). You can see a list of function modules and also other objects held in the function group. Let's consider the function module SPELL_AMOUNT. This function module converts numeric figures into words. Step 1 − Go to transaction SE38 and create a new program called Z_SPELLAMOUNT. Step 2 − Enter some code so that a parameter can be set up where a value could be entered and passed on to the function module. The text element text-001 here reads ‘Enter a Value’. Step 3 − To write the code for this, use CTRL+F6. After this, a window appears where ‘CALL FUNCTION’ is the first option in a list. Enter 'spell_amount' in the text box and click the continue button. Step 4 − Some code is generated automatically. But we need to enhance the IF statement to include a code to WRITE a message to the screen to say "The function module returned a value of: sy-subrc” and add the ELSE statement so as to write the correct result out when the function module is successful. Here, a new variable must be set up to hold the value returned from the function module. Let's call this as 'result'. Following is the code − REPORT Z_SPELLAMOUNT. data result like SPELL. selection-screen begin of line. selection-screen comment 1(15) text-001. parameter num_1 Type I. selection-screen end of line. CALL FUNCTION 'SPELL_AMOUNT' EXPORTING AMOUNT = num_1 IMPORTING IN_WORDS = result. IF SY-SUBRC <> 0. Write: 'Value returned is:', SY-SUBRC. else. Write: 'Amount in words is:', result-word. ENDIF. Step 5 − The variable which the function module returns is called IN_WORDS. Set up the corresponding variable in the program called ‘result’. Define IN_WORDS by using the LIKE statement to refer to a structure called SPELL. Step 6 − Save, activate and execute the program. Enter a value as shown in the following screenshot and press F8. The above code produces the following output − Spelling the Amount Amount in words is: FIVE THOUSAND SIX HUNDRED EIGHTY 25 Lectures 6 hours Sanjo Thomas 26 Lectures 2 hours Neha Gupta 30 Lectures 2.5 hours Sumit Agarwal 30 Lectures 4 hours Sumit Agarwal 14 Lectures 1.5 hours Neha Malik 13 Lectures 1.5 hours Neha Malik Print Add Notes Bookmark this page
[ { "code": null, "e": 3106, "s": 2898, "text": "Function modules make up a major part of a SAP system, because for years SAP has modularized code using function modules, allowing for code reuse, by themselves, their developers and also by their customers." }, { "code": null, "e": 3617, "s": 3106, "text": "Function modules are sub-programs that contain a set of reusable statements with importing and exporting parameters. Unlike Include programs, function modules can be executed independently. SAP system contains several predefined function modules that can be called from any ABAP program. The function group acts as a kind of container for a number of function modules that would logically belong together. For instance, the function modules for an HR payroll system would be put together into a function group." }, { "code": null, "e": 3933, "s": 3617, "text": "To look at how to create function modules, the function builder must be explored. You can find the function builder with transaction code SE37. Just type a part of a function module name with a wild card character to demonstrate the way function modules can be searched for. Type *amount* and then press the F4 key." }, { "code": null, "e": 4406, "s": 3933, "text": "The results of the search will be displayed in a new window. The function modules are displayed in the lines with blue background and their function groups in pink lines. You may look further at the function group ISOC by using the Object Navigator screen (Transaction SE80). You can see a list of function modules and also other objects held in the function group. Let's consider the function module SPELL_AMOUNT. This function module converts numeric figures into words." }, { "code": null, "e": 4485, "s": 4406, "text": "Step 1 − Go to transaction SE38 and create a new program called Z_SPELLAMOUNT." }, { "code": null, "e": 4667, "s": 4485, "text": "Step 2 − Enter some code so that a parameter can be set up where a value could be entered and passed on to the function module. The text element text-001 here reads ‘Enter a Value’." }, { "code": null, "e": 4867, "s": 4667, "text": "Step 3 − To write the code for this, use CTRL+F6. After this, a window appears where ‘CALL FUNCTION’ is the first option in a list. Enter 'spell_amount' in the text box and click the continue button." }, { "code": null, "e": 5287, "s": 4867, "text": "Step 4 − Some code is generated automatically. But we need to enhance the IF statement to include a code to WRITE a message to the screen to say \"The function module returned a value of: sy-subrc” and add the ELSE statement so as to write the correct result out when the function module is successful. Here, a new variable must be set up to hold the value returned from the function module. Let's call this as 'result'." }, { "code": null, "e": 5311, "s": 5287, "text": "Following is the code −" }, { "code": null, "e": 5704, "s": 5311, "text": "REPORT Z_SPELLAMOUNT. \ndata result like SPELL. \n\nselection-screen begin of line. \nselection-screen comment 1(15) text-001. \n\nparameter num_1 Type I. \nselection-screen end of line. \nCALL FUNCTION 'SPELL_AMOUNT' \nEXPORTING \nAMOUNT = num_1 \nIMPORTING \nIN_WORDS = result. \n\nIF SY-SUBRC <> 0. \n Write: 'Value returned is:', SY-SUBRC. \nelse. \n Write: 'Amount in words is:', result-word. \nENDIF." }, { "code": null, "e": 5928, "s": 5704, "text": "Step 5 − The variable which the function module returns is called IN_WORDS. Set up the corresponding variable in the program called ‘result’. Define IN_WORDS by using the LIKE statement to refer to a structure called SPELL." }, { "code": null, "e": 6042, "s": 5928, "text": "Step 6 − Save, activate and execute the program. Enter a value as shown in the following screenshot and press F8." }, { "code": null, "e": 6089, "s": 6042, "text": "The above code produces the following output −" }, { "code": null, "e": 6165, "s": 6089, "text": "Spelling the Amount \nAmount in words is: \nFIVE THOUSAND SIX HUNDRED EIGHTY\n" }, { "code": null, "e": 6198, "s": 6165, "text": "\n 25 Lectures \n 6 hours \n" }, { "code": null, "e": 6212, "s": 6198, "text": " Sanjo Thomas" }, { "code": null, "e": 6245, "s": 6212, "text": "\n 26 Lectures \n 2 hours \n" }, { "code": null, "e": 6257, "s": 6245, "text": " Neha Gupta" }, { "code": null, "e": 6292, "s": 6257, "text": "\n 30 Lectures \n 2.5 hours \n" }, { "code": null, "e": 6307, "s": 6292, "text": " Sumit Agarwal" }, { "code": null, "e": 6340, "s": 6307, "text": "\n 30 Lectures \n 4 hours \n" }, { "code": null, "e": 6355, "s": 6340, "text": " Sumit Agarwal" }, { "code": null, "e": 6390, "s": 6355, "text": "\n 14 Lectures \n 1.5 hours \n" }, { "code": null, "e": 6402, "s": 6390, "text": " Neha Malik" }, { "code": null, "e": 6437, "s": 6402, "text": "\n 13 Lectures \n 1.5 hours \n" }, { "code": null, "e": 6449, "s": 6437, "text": " Neha Malik" }, { "code": null, "e": 6456, "s": 6449, "text": " Print" }, { "code": null, "e": 6467, "s": 6456, "text": " Add Notes" } ]
XML DOM - Replace Node
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 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": 2564, "s": 2288, "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": 2616, "s": 2564, "text": "Following are the two methods to replace the nodes." }, { "code": null, "e": 2631, "s": 2616, "text": "replaceChild()" }, { "code": null, "e": 2645, "s": 2631, "text": "replaceData()" }, { "code": null, "e": 2718, "s": 2645, "text": "The method replaceChild() replaces the specified node with the new node." }, { "code": null, "e": 2762, "s": 2718, "text": "The insertData() has the following syntax −" }, { "code": null, "e": 2831, "s": 2762, "text": "Node replaceChild(Node newChild, Node oldChild) throws DOMException\n" }, { "code": null, "e": 2838, "s": 2831, "text": "Where," }, { "code": null, "e": 2891, "s": 2838, "text": "newChild − is the new node to put in the child list." }, { "code": null, "e": 2944, "s": 2891, "text": "newChild − is the new node to put in the child list." }, { "code": null, "e": 2995, "s": 2944, "text": "oldChild − is the node being replaced in the list." }, { "code": null, "e": 3046, "s": 2995, "text": "oldChild − is the node being replaced in the list." }, { "code": null, "e": 3085, "s": 3046, "text": "This method returns the node replaced." }, { "code": null, "e": 3124, "s": 3085, "text": "This method returns the node replaced." }, { "code": null, "e": 3299, "s": 3124, "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": 5025, "s": 3299, "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": 5194, "s": 5025, "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": 5340, "s": 5194, "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": 5461, "s": 5340, "text": "The method replaceData() replaces the characters starting at the specified 16-bit unit offset with the specified string." }, { "code": null, "e": 5506, "s": 5461, "text": "The replaceData() has the following syntax −" }, { "code": null, "e": 5589, "s": 5506, "text": "void replaceData(int offset, int count, java.lang.String arg) throws DOMException\n" }, { "code": null, "e": 5595, "s": 5589, "text": "Where" }, { "code": null, "e": 5649, "s": 5595, "text": "offset − is the offset from which to start replacing." }, { "code": null, "e": 5703, "s": 5649, "text": "offset − is the offset from which to start replacing." }, { "code": null, "e": 5863, "s": 5703, "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": 6023, "s": 5863, "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": 6082, "s": 6023, "text": "arg − the DOMString with which the range must be replaced." }, { "code": null, "e": 6141, "s": 6082, "text": "arg − the DOMString with which the range must be replaced." }, { "code": null, "e": 6263, "s": 6141, "text": "The following example (replacedata_example.htm) parses an XML document (node.xml) into an XML DOM object and replaces it." }, { "code": null, "e": 7128, "s": 6263, "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": 7151, "s": 7128, "text": "In the above example −" }, { "code": null, "e": 7339, "s": 7151, "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": 7527, "s": 7339, "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": 7696, "s": 7527, "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": 7794, "s": 7696, "text": "ContactNo before replace operation: 1234567890\n\nContactNo after replace operation: 199999997890 \n" }, { "code": null, "e": 7827, "s": 7794, "text": "\n 41 Lectures \n 5 hours \n" }, { "code": null, "e": 7849, "s": 7827, "text": " Abhishek And Pukhraj" }, { "code": null, "e": 7884, "s": 7849, "text": "\n 33 Lectures \n 3.5 hours \n" }, { "code": null, "e": 7906, "s": 7884, "text": " Abhishek And Pukhraj" }, { "code": null, "e": 7939, "s": 7906, "text": "\n 15 Lectures \n 1 hours \n" }, { "code": null, "e": 7952, "s": 7939, "text": " Zach Miller" }, { "code": null, "e": 7985, "s": 7952, "text": "\n 15 Lectures \n 4 hours \n" }, { "code": null, "e": 8009, "s": 7985, "text": " Prof. Paul Cline, Ed.D" }, { "code": null, "e": 8042, "s": 8009, "text": "\n 13 Lectures \n 4 hours \n" }, { "code": null, "e": 8066, "s": 8042, "text": " Prof. Paul Cline, Ed.D" }, { "code": null, "e": 8099, "s": 8066, "text": "\n 17 Lectures \n 2 hours \n" }, { "code": null, "e": 8116, "s": 8099, "text": " Laurence Svekis" }, { "code": null, "e": 8123, "s": 8116, "text": " Print" }, { "code": null, "e": 8134, "s": 8123, "text": " Add Notes" } ]
Cordova - Environment Setup
In this chapter, we will understand the Environment Setup of Cordova. To begin with the setup, we need to first install a few components. The components are listed in the following table. NodeJS and NPM NodeJS is the platform needed for Cordova development. Check out our NodeJS Environment Setup for more details. Android SDK For Android platform, you need to have Android SDK installed on your machine. Check out Android Environment Setup for more details. XCode For iOS platform, you need to have xCode installed on your machine. Check out iOS Environment Setup for more details Before we start, you need to know that we will use Windows command prompt in our tutorial. Even if you don't use git, it should be installed since Cordova is using it for some background processes. You can download git here. After you install git, open your environment variable. Right-Click on Computer Properties Advanced System settings Environment Variables System Variables Edit Copy the following at the end of the variable value field. This is default path of the git installation. If you installed it on a different path you should use that instead of our example code below. ;C:\Program Files (x86)\Git\bin;C:\Program Files (x86)\Git\cmd Now you can type git in your command prompt to test if the installation is successful. This step will download and install Cordova module globally. Open the command prompt and run the following − C:\Users\username>npm install -g cordova You can check the installed version by running − C:\Users\username>cordova -v This is everything you need to start developing the Cordova apps on Windows operating system. In our next tutorial, we will show you how to create first application. 45 Lectures 2 hours Skillbakerystudios 16 Lectures 1 hours Nilay Mehta Print Add Notes Bookmark this page
[ { "code": null, "e": 2368, "s": 2180, "text": "In this chapter, we will understand the Environment Setup of Cordova. To begin with the setup, we need to first install a few components. The components are listed in the following table." }, { "code": null, "e": 2383, "s": 2368, "text": "NodeJS and NPM" }, { "code": null, "e": 2495, "s": 2383, "text": "NodeJS is the platform needed for Cordova development. Check out our NodeJS Environment Setup for more details." }, { "code": null, "e": 2507, "s": 2495, "text": "Android SDK" }, { "code": null, "e": 2639, "s": 2507, "text": "For Android platform, you need to have Android SDK installed on your machine. Check out Android Environment Setup for more details." }, { "code": null, "e": 2645, "s": 2639, "text": "XCode" }, { "code": null, "e": 2762, "s": 2645, "text": "For iOS platform, you need to have xCode installed on your machine. Check out iOS Environment Setup for more details" }, { "code": null, "e": 2853, "s": 2762, "text": "Before we start, you need to know that we will use Windows command prompt in our tutorial." }, { "code": null, "e": 3042, "s": 2853, "text": "Even if you don't use git, it should be installed since Cordova is using it for some background processes. You can download git here. After you install git, open your environment variable." }, { "code": null, "e": 3066, "s": 3042, "text": "Right-Click on Computer" }, { "code": null, "e": 3077, "s": 3066, "text": "Properties" }, { "code": null, "e": 3102, "s": 3077, "text": "Advanced System settings" }, { "code": null, "e": 3124, "s": 3102, "text": "Environment Variables" }, { "code": null, "e": 3141, "s": 3124, "text": "System Variables" }, { "code": null, "e": 3146, "s": 3141, "text": "Edit" }, { "code": null, "e": 3346, "s": 3146, "text": "Copy the following at the end of the variable value field. This is default path of the git installation. If you installed it on a different path you should use that instead of our example code below." }, { "code": null, "e": 3410, "s": 3346, "text": ";C:\\Program Files (x86)\\Git\\bin;C:\\Program Files (x86)\\Git\\cmd\n" }, { "code": null, "e": 3497, "s": 3410, "text": "Now you can type git in your command prompt to test if the installation is successful." }, { "code": null, "e": 3606, "s": 3497, "text": "This step will download and install Cordova module globally. Open the command prompt and run the following −" }, { "code": null, "e": 3649, "s": 3606, "text": "C:\\Users\\username>npm install -g cordova \n" }, { "code": null, "e": 3698, "s": 3649, "text": "You can check the installed version by running −" }, { "code": null, "e": 3729, "s": 3698, "text": "C:\\Users\\username>cordova -v \n" }, { "code": null, "e": 3895, "s": 3729, "text": "This is everything you need to start developing the Cordova apps on Windows operating system. In our next tutorial, we will show you how to create first application." }, { "code": null, "e": 3928, "s": 3895, "text": "\n 45 Lectures \n 2 hours \n" }, { "code": null, "e": 3948, "s": 3928, "text": " Skillbakerystudios" }, { "code": null, "e": 3981, "s": 3948, "text": "\n 16 Lectures \n 1 hours \n" }, { "code": null, "e": 3994, "s": 3981, "text": " Nilay Mehta" }, { "code": null, "e": 4001, "s": 3994, "text": " Print" }, { "code": null, "e": 4012, "s": 4001, "text": " Add Notes" } ]
Convert a given Binary Tree to Doubly Linked List | Set 4 - GeeksforGeeks
10 May, 2021 Given a Binary Tree (BT), convert it to a Doubly Linked List(DLL) In-Place. The left and right pointers in nodes are to be used as previous and next pointers respectively in converted DLL. The order of nodes in DLL must be same as Inorder of the given Binary Tree. The first node of Inorder traversal (left most node in BT) must be head node of the DLL. Below three different solutions have been discussed for this problem. Convert a given Binary Tree to Doubly Linked List | Set 1 Convert a given Binary Tree to Doubly Linked List | Set 2 Convert a given Binary Tree to Doubly Linked List | Set 3In the following implementation, we traverse the tree in inorder fashion. We add nodes at the beginning of current linked list and update head of the list using pointer to head pointer. Since we insert at the beginning, we need to process leaves in reverse order. For reverse order, we first traverse the right subtree before the left subtree. i.e. do a reverse inorder traversal. C++ Java Python3 C# Javascript // C++ program to convert a given Binary Tree to Doubly Linked List#include <bits/stdc++.h> // Structure for tree and linked liststruct Node { int data; Node *left, *right;}; // Utility function for allocating node for Binary// Tree.Node* newNode(int data){ Node* node = new Node; node->data = data; node->left = node->right = NULL; return node;} // A simple recursive function to convert a given// Binary tree to Doubly Linked List// root --> Root of Binary Tree// head --> Pointer to head node of created doubly linked listvoid BToDLL(Node* root, Node*& head){ // Base cases if (root == NULL) return; // Recursively convert right subtree BToDLL(root->right, head); // insert root into DLL root->right = head; // Change left pointer of previous head if (head != NULL) head->left = root; // Change head of Doubly linked list head = root; // Recursively convert left subtree BToDLL(root->left, head);} // Utility function for printing double linked list.void printList(Node* head){ printf("Extracted Double Linked list is:\n"); while (head) { printf("%d ", head->data); head = head->right; }} // Driver program to test above functionint main(){ /* Constructing below tree 5 / \ 3 6 / \ \ 1 4 8 / \ / \ 0 2 7 9 */ Node* root = newNode(5); root->left = newNode(3); root->right = newNode(6); root->left->left = newNode(1); root->left->right = newNode(4); root->right->right = newNode(8); root->left->left->left = newNode(0); root->left->left->right = newNode(2); root->right->right->left = newNode(7); root->right->right->right = newNode(9); Node* head = NULL; BToDLL(root, head); printList(head); return 0;} // Java program to convert a given Binary Tree to Doubly Linked List /* Structure for tree and Linked List */class Node { int data; Node left, right; public Node(int data) { this.data = data; left = right = null; }} class BinaryTree { // root --> Root of Binary Tree Node root; // head --> Pointer to head node of created doubly linked list Node head; // A simple recursive function to convert a given // Binary tree to Doubly Linked List void BToDLL(Node root) { // Base cases if (root == null) return; // Recursively convert right subtree BToDLL(root.right); // insert root into DLL root.right = head; // Change left pointer of previous head if (head != null) head.left = root; // Change head of Doubly linked list head = root; // Recursively convert left subtree BToDLL(root.left); } // Utility function for printing double linked list. void printList(Node head) { System.out.println("Extracted Double Linked List is : "); while (head != null) { System.out.print(head.data + " "); head = head.right; } } // Driver program to test the above functions public static void main(String[] args) { /* Constructing below tree 5 / \ 3 6 / \ \ 1 4 8 / \ / \ 0 2 7 9 */ BinaryTree tree = new BinaryTree(); tree.root = new Node(5); tree.root.left = new Node(3); tree.root.right = new Node(6); tree.root.left.right = new Node(4); tree.root.left.left = new Node(1); tree.root.right.right = new Node(8); tree.root.left.left.right = new Node(2); tree.root.left.left.left = new Node(0); tree.root.right.right.left = new Node(7); tree.root.right.right.right = new Node(9); tree.BToDLL(tree.root); tree.printList(tree.head); }} // This code has been contributed by Mayank Jaiswal(mayank_24) # Python3 program to convert a given Binary Tree to Doubly Linked Listclass Node: def __init__(self, data): self.data = data self.left = self.right = None class BinaryTree: # A simple recursive function to convert a given # Binary tree to Doubly Linked List # root --> Root of Binary Tree # head --> Pointer to head node of created doubly linked list root, head = None, None def BToDll(self, root: Node): if root is None: return # Recursively convert right subtree self.BToDll(root.right) # Insert root into doubly linked list root.right = self.head # Change left pointer of previous head if self.head is not None: self.head.left = root # Change head of doubly linked list self.head = root # Recursively convert left subtree self.BToDll(root.left) @staticmethod def print_list(head: Node): print('Extracted Double Linked list is:') while head is not None: print(head.data, end = ' ') head = head.right # Driver program to test above functionif __name__ == '__main__': """ Constructing below tree 5 // \\ 3 6 // \\ \\ 1 4 8 // \\ // \\ 0 2 7 9 """ tree = BinaryTree() tree.root = Node(5) tree.root.left = Node(3) tree.root.right = Node(6) tree.root.left.left = Node(1) tree.root.left.right = Node(4) tree.root.right.right = Node(8) tree.root.left.left.left = Node(0) tree.root.left.left.right = Node(2) tree.root.right.right.left = Node(7) tree.root.right.right.right = Node(9) tree.BToDll(tree.root) tree.print_list(tree.head) # This code is contributed by Rajat Srivastava // C# program to convert a given Binary Tree to Doubly Linked Listusing System; /* Structure for tree and Linked List */public class Node { public int data; public Node left, right; public Node(int data) { this.data = data; left = right = null; }} class GFG { // root --> Root of Binary Tree public Node root; // head --> Pointer to head node of created doubly linked list public Node head; // A simple recursive function to convert a given // Binary tree to Doubly Linked List public virtual void BToDLL(Node root) { // Base cases if (root == null) return; // Recursively convert right subtree BToDLL(root.right); // insert root into DLL root.right = head; // Change left pointer of previous head if (head != null) head.left = root; // Change head of Doubly linked list head = root; // Recursively convert left subtree BToDLL(root.left); } // Utility function for printing double linked list. public virtual void printList(Node head) { Console.WriteLine("Extracted Double " + "Linked List is : "); while (head != null) { Console.Write(head.data + " "); head = head.right; } } // Driver program to test above function public static void Main(string[] args) { /* Constructing below tree 5 / \ 3 6 / \ \ 1 4 8 / \ / \ 0 2 7 9 */ GFG tree = new GFG(); tree.root = new Node(5); tree.root.left = new Node(3); tree.root.right = new Node(6); tree.root.left.right = new Node(4); tree.root.left.left = new Node(1); tree.root.right.right = new Node(8); tree.root.left.left.right = new Node(2); tree.root.left.left.left = new Node(0); tree.root.right.right.left = new Node(7); tree.root.right.right.right = new Node(9); tree.BToDLL(tree.root); tree.printList(tree.head); }} // This code is contributed by Shrikant13 <script>// javascript program to convert a given// Binary Tree to Doubly Linked List /* Structure for tree and Linked List */class Node { constructor(data) { this.data = data; this.left = this.right = null; }} // root --> Root of Binary Tree var root; // head --> Pointer to head node of created doubly linked list var head; // A simple recursive function to convert a given // Binary tree to Doubly Linked List function BToDLL( root) { // Base cases if (root == null) return; // Recursively convert right subtree BToDLL(root.right); // insert root into DLL root.right = head; // Change left pointer of previous head if (head != null) head.left = root; // Change head of Doubly linked list head = root; // Recursively convert left subtree BToDLL(root.left); } // Utility function for printing var linked list. function printList( head) { document.write("Extracted Double Linked List is :<br/> "); while (head != null) { document.write(head.data + " "); head = head.right; } } // Driver program to test the above functions /* Constructing below tree 5 / \ 3 6 / \ \ 1 4 8 / \ / \ 0 2 7 9 */ root = new Node(5); root.left = new Node(3); root.right = new Node(6); root.left.right = new Node(4); root.left.left = new Node(1); root.right.right = new Node(8); root.left.left.right = new Node(2); root.left.left.left = new Node(0); root.right.right.left = new Node(7); root.right.right.right = new Node(9); BToDLL(root); printList(head); // This code contributed by umadevi9616</script> Output : Extracted Double Linked list is: 0 1 2 3 4 5 6 7 8 9 Time Complexity: O(n), as the solution does a single traversal of given Binary Tree. YouTubeGeeksforGeeks501K subscribersConvert a given Binary Tree to Doubly Linked List | Set 4 | 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 / 5:05•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=lxeWqcTsmg0" 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 Aditya Goel. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. shrikanth13 rajatsri94 mesajidiqbal umadevi9616 Amazon doubly linked list Goldman Sachs Microsoft Linked List Tree Amazon Microsoft Goldman Sachs Linked List Tree Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Linked List | Set 1 (Introduction) Linked List | Set 2 (Inserting a node) Stack Data Structure (Introduction and Program) Linked List | Set 3 (Deleting a node) LinkedList in Java Tree Traversals (Inorder, Preorder and Postorder) Binary Tree | Set 1 (Introduction) Level Order Binary Tree Traversal AVL Tree | Set 1 (Insertion) Inorder Tree Traversal without Recursion
[ { "code": null, "e": 31010, "s": 30982, "text": "\n10 May, 2021" }, { "code": null, "e": 31365, "s": 31010, "text": "Given a Binary Tree (BT), convert it to a Doubly Linked List(DLL) In-Place. The left and right pointers in nodes are to be used as previous and next pointers respectively in converted DLL. The order of nodes in DLL must be same as Inorder of the given Binary Tree. The first node of Inorder traversal (left most node in BT) must be head node of the DLL. " }, { "code": null, "e": 31992, "s": 31367, "text": "Below three different solutions have been discussed for this problem. Convert a given Binary Tree to Doubly Linked List | Set 1 Convert a given Binary Tree to Doubly Linked List | Set 2 Convert a given Binary Tree to Doubly Linked List | Set 3In the following implementation, we traverse the tree in inorder fashion. We add nodes at the beginning of current linked list and update head of the list using pointer to head pointer. Since we insert at the beginning, we need to process leaves in reverse order. For reverse order, we first traverse the right subtree before the left subtree. i.e. do a reverse inorder traversal. " }, { "code": null, "e": 31996, "s": 31992, "text": "C++" }, { "code": null, "e": 32001, "s": 31996, "text": "Java" }, { "code": null, "e": 32009, "s": 32001, "text": "Python3" }, { "code": null, "e": 32012, "s": 32009, "text": "C#" }, { "code": null, "e": 32023, "s": 32012, "text": "Javascript" }, { "code": "// C++ program to convert a given Binary Tree to Doubly Linked List#include <bits/stdc++.h> // Structure for tree and linked liststruct Node { int data; Node *left, *right;}; // Utility function for allocating node for Binary// Tree.Node* newNode(int data){ Node* node = new Node; node->data = data; node->left = node->right = NULL; return node;} // A simple recursive function to convert a given// Binary tree to Doubly Linked List// root --> Root of Binary Tree// head --> Pointer to head node of created doubly linked listvoid BToDLL(Node* root, Node*& head){ // Base cases if (root == NULL) return; // Recursively convert right subtree BToDLL(root->right, head); // insert root into DLL root->right = head; // Change left pointer of previous head if (head != NULL) head->left = root; // Change head of Doubly linked list head = root; // Recursively convert left subtree BToDLL(root->left, head);} // Utility function for printing double linked list.void printList(Node* head){ printf(\"Extracted Double Linked list is:\\n\"); while (head) { printf(\"%d \", head->data); head = head->right; }} // Driver program to test above functionint main(){ /* Constructing below tree 5 / \\ 3 6 / \\ \\ 1 4 8 / \\ / \\ 0 2 7 9 */ Node* root = newNode(5); root->left = newNode(3); root->right = newNode(6); root->left->left = newNode(1); root->left->right = newNode(4); root->right->right = newNode(8); root->left->left->left = newNode(0); root->left->left->right = newNode(2); root->right->right->left = newNode(7); root->right->right->right = newNode(9); Node* head = NULL; BToDLL(root, head); printList(head); return 0;}", "e": 33856, "s": 32023, "text": null }, { "code": "// Java program to convert a given Binary Tree to Doubly Linked List /* Structure for tree and Linked List */class Node { int data; Node left, right; public Node(int data) { this.data = data; left = right = null; }} class BinaryTree { // root --> Root of Binary Tree Node root; // head --> Pointer to head node of created doubly linked list Node head; // A simple recursive function to convert a given // Binary tree to Doubly Linked List void BToDLL(Node root) { // Base cases if (root == null) return; // Recursively convert right subtree BToDLL(root.right); // insert root into DLL root.right = head; // Change left pointer of previous head if (head != null) head.left = root; // Change head of Doubly linked list head = root; // Recursively convert left subtree BToDLL(root.left); } // Utility function for printing double linked list. void printList(Node head) { System.out.println(\"Extracted Double Linked List is : \"); while (head != null) { System.out.print(head.data + \" \"); head = head.right; } } // Driver program to test the above functions public static void main(String[] args) { /* Constructing below tree 5 / \\ 3 6 / \\ \\ 1 4 8 / \\ / \\ 0 2 7 9 */ BinaryTree tree = new BinaryTree(); tree.root = new Node(5); tree.root.left = new Node(3); tree.root.right = new Node(6); tree.root.left.right = new Node(4); tree.root.left.left = new Node(1); tree.root.right.right = new Node(8); tree.root.left.left.right = new Node(2); tree.root.left.left.left = new Node(0); tree.root.right.right.left = new Node(7); tree.root.right.right.right = new Node(9); tree.BToDLL(tree.root); tree.printList(tree.head); }} // This code has been contributed by Mayank Jaiswal(mayank_24)", "e": 35975, "s": 33856, "text": null }, { "code": "# Python3 program to convert a given Binary Tree to Doubly Linked Listclass Node: def __init__(self, data): self.data = data self.left = self.right = None class BinaryTree: # A simple recursive function to convert a given # Binary tree to Doubly Linked List # root --> Root of Binary Tree # head --> Pointer to head node of created doubly linked list root, head = None, None def BToDll(self, root: Node): if root is None: return # Recursively convert right subtree self.BToDll(root.right) # Insert root into doubly linked list root.right = self.head # Change left pointer of previous head if self.head is not None: self.head.left = root # Change head of doubly linked list self.head = root # Recursively convert left subtree self.BToDll(root.left) @staticmethod def print_list(head: Node): print('Extracted Double Linked list is:') while head is not None: print(head.data, end = ' ') head = head.right # Driver program to test above functionif __name__ == '__main__': \"\"\" Constructing below tree 5 // \\\\ 3 6 // \\\\ \\\\ 1 4 8 // \\\\ // \\\\ 0 2 7 9 \"\"\" tree = BinaryTree() tree.root = Node(5) tree.root.left = Node(3) tree.root.right = Node(6) tree.root.left.left = Node(1) tree.root.left.right = Node(4) tree.root.right.right = Node(8) tree.root.left.left.left = Node(0) tree.root.left.left.right = Node(2) tree.root.right.right.left = Node(7) tree.root.right.right.right = Node(9) tree.BToDll(tree.root) tree.print_list(tree.head) # This code is contributed by Rajat Srivastava", "e": 37738, "s": 35975, "text": null }, { "code": "// C# program to convert a given Binary Tree to Doubly Linked Listusing System; /* Structure for tree and Linked List */public class Node { public int data; public Node left, right; public Node(int data) { this.data = data; left = right = null; }} class GFG { // root --> Root of Binary Tree public Node root; // head --> Pointer to head node of created doubly linked list public Node head; // A simple recursive function to convert a given // Binary tree to Doubly Linked List public virtual void BToDLL(Node root) { // Base cases if (root == null) return; // Recursively convert right subtree BToDLL(root.right); // insert root into DLL root.right = head; // Change left pointer of previous head if (head != null) head.left = root; // Change head of Doubly linked list head = root; // Recursively convert left subtree BToDLL(root.left); } // Utility function for printing double linked list. public virtual void printList(Node head) { Console.WriteLine(\"Extracted Double \" + \"Linked List is : \"); while (head != null) { Console.Write(head.data + \" \"); head = head.right; } } // Driver program to test above function public static void Main(string[] args) { /* Constructing below tree 5 / \\ 3 6 / \\ \\ 1 4 8 / \\ / \\ 0 2 7 9 */ GFG tree = new GFG(); tree.root = new Node(5); tree.root.left = new Node(3); tree.root.right = new Node(6); tree.root.left.right = new Node(4); tree.root.left.left = new Node(1); tree.root.right.right = new Node(8); tree.root.left.left.right = new Node(2); tree.root.left.left.left = new Node(0); tree.root.right.right.left = new Node(7); tree.root.right.right.right = new Node(9); tree.BToDLL(tree.root); tree.printList(tree.head); }} // This code is contributed by Shrikant13", "e": 39891, "s": 37738, "text": null }, { "code": "<script>// javascript program to convert a given// Binary Tree to Doubly Linked List /* Structure for tree and Linked List */class Node { constructor(data) { this.data = data; this.left = this.right = null; }} // root --> Root of Binary Tree var root; // head --> Pointer to head node of created doubly linked list var head; // A simple recursive function to convert a given // Binary tree to Doubly Linked List function BToDLL( root) { // Base cases if (root == null) return; // Recursively convert right subtree BToDLL(root.right); // insert root into DLL root.right = head; // Change left pointer of previous head if (head != null) head.left = root; // Change head of Doubly linked list head = root; // Recursively convert left subtree BToDLL(root.left); } // Utility function for printing var linked list. function printList( head) { document.write(\"Extracted Double Linked List is :<br/> \"); while (head != null) { document.write(head.data + \" \"); head = head.right; } } // Driver program to test the above functions /* Constructing below tree 5 / \\ 3 6 / \\ \\ 1 4 8 / \\ / \\ 0 2 7 9 */ root = new Node(5); root.left = new Node(3); root.right = new Node(6); root.left.right = new Node(4); root.left.left = new Node(1); root.right.right = new Node(8); root.left.left.right = new Node(2); root.left.left.left = new Node(0); root.right.right.left = new Node(7); root.right.right.right = new Node(9); BToDLL(root); printList(head); // This code contributed by umadevi9616</script>", "e": 41793, "s": 39891, "text": null }, { "code": null, "e": 41803, "s": 41793, "text": "Output : " }, { "code": null, "e": 41856, "s": 41803, "text": "Extracted Double Linked list is:\n0 1 2 3 4 5 6 7 8 9" }, { "code": null, "e": 41942, "s": 41856, "text": "Time Complexity: O(n), as the solution does a single traversal of given Binary Tree. " }, { "code": null, "e": 42798, "s": 41942, "text": "YouTubeGeeksforGeeks501K subscribersConvert a given Binary Tree to Doubly Linked List | Set 4 | 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 / 5:05•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=lxeWqcTsmg0\" 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": 42968, "s": 42798, "text": "This article is contributed by Aditya Goel. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. " }, { "code": null, "e": 42980, "s": 42968, "text": "shrikanth13" }, { "code": null, "e": 42991, "s": 42980, "text": "rajatsri94" }, { "code": null, "e": 43004, "s": 42991, "text": "mesajidiqbal" }, { "code": null, "e": 43016, "s": 43004, "text": "umadevi9616" }, { "code": null, "e": 43023, "s": 43016, "text": "Amazon" }, { "code": null, "e": 43042, "s": 43023, "text": "doubly linked list" }, { "code": null, "e": 43056, "s": 43042, "text": "Goldman Sachs" }, { "code": null, "e": 43066, "s": 43056, "text": "Microsoft" }, { "code": null, "e": 43078, "s": 43066, "text": "Linked List" }, { "code": null, "e": 43083, "s": 43078, "text": "Tree" }, { "code": null, "e": 43090, "s": 43083, "text": "Amazon" }, { "code": null, "e": 43100, "s": 43090, "text": "Microsoft" }, { "code": null, "e": 43114, "s": 43100, "text": "Goldman Sachs" }, { "code": null, "e": 43126, "s": 43114, "text": "Linked List" }, { "code": null, "e": 43131, "s": 43126, "text": "Tree" }, { "code": null, "e": 43229, "s": 43131, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 43238, "s": 43229, "text": "Comments" }, { "code": null, "e": 43251, "s": 43238, "text": "Old Comments" }, { "code": null, "e": 43286, "s": 43251, "text": "Linked List | Set 1 (Introduction)" }, { "code": null, "e": 43325, "s": 43286, "text": "Linked List | Set 2 (Inserting a node)" }, { "code": null, "e": 43373, "s": 43325, "text": "Stack Data Structure (Introduction and Program)" }, { "code": null, "e": 43411, "s": 43373, "text": "Linked List | Set 3 (Deleting a node)" }, { "code": null, "e": 43430, "s": 43411, "text": "LinkedList in Java" }, { "code": null, "e": 43480, "s": 43430, "text": "Tree Traversals (Inorder, Preorder and Postorder)" }, { "code": null, "e": 43515, "s": 43480, "text": "Binary Tree | Set 1 (Introduction)" }, { "code": null, "e": 43549, "s": 43515, "text": "Level Order Binary Tree Traversal" }, { "code": null, "e": 43578, "s": 43549, "text": "AVL Tree | Set 1 (Insertion)" } ]
Difference between require-dev and require in PHP? - GeeksforGeeks
05 Nov, 2018 Before going to understand the difference between require and require_dev first understand what is require and require_dev. require: These are must packages for the code to run. It defines the actual dependency as well as package version.require_dev: It defines the packages necessary for developing the project and not needed in production environment. Note: The require and require_dev are important parameters available in composer.json. What is composer?Composer is dependency/parameter manager in php. It can be used to install keep a track of and update project dependency. Composer also takes care of autoload of dependencies that application relies on letting easily use the dependency inside the project without worrying about including them at the top of any given file. Dependency for project are listed within a “composer.json” file which typically located in the project root. This file holds the information about required version of packages for production and development. This file can be edited manually using any text editor or automatically through the command line via command such as “composer require ” or “composer require_dev .To start using composer in the project first need to create composer.json file. It can be either created manually or simply run composer init. After run composer init in the terminal it will ask some basic information about the project such as package name, description (it is optional), Author and source other information like minimum stability, license and required package.The require key in the composer.json specifies composers which packages the project depends on require takes an object that maps package namesExample: { "require": { // name of package. "composer/composer:" "1.2.*" }} In the above example “composer/composer” specifies vendor name and project name separated by slash (‘/’) and “1.2.*” specifies the version name.To install the dependency need to run the composer install command and then it will find the defined package that method for supplied version constraints and download it into vendor directory. It convention to put third party code into directory named vendor. The installed command also created a composer.lock file. Difference Between require and require_dev: require:It define actual dependency as well as package version.The require lists the package require by this package.The package will not be installed unless those requirements can be met. It define actual dependency as well as package version. The require lists the package require by this package. The package will not be installed unless those requirements can be met. require_dev:It define the packages necessary for developing project.The require_dev lists packages required for developing this package, or running tests, etc.The dev requirements of the root package are installed by default. Both install or update support the “–no-dev” option that prevents dev dependencies from being installed. It define the packages necessary for developing project. The require_dev lists packages required for developing this package, or running tests, etc. The dev requirements of the root package are installed by default. Both install or update support the “–no-dev” option that prevents dev dependencies from being installed. PHP-packages Picked PHP Web Technologies PHP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments How to convert array to string in PHP ? PHP | Converting string to Date and DateTime How to pass JavaScript variables to PHP ? How to fetch data from localserver database and display on HTML table using PHP ? How to run JavaScript from PHP? Roadmap to Become a Web Developer in 2022 Installation of Node.js on Linux How to fetch data from an API in ReactJS ? Top 10 Projects For Beginners To Practice HTML and CSS Skills How to insert spaces/tabs in text using HTML/CSS?
[ { "code": null, "e": 24552, "s": 24524, "text": "\n05 Nov, 2018" }, { "code": null, "e": 24676, "s": 24552, "text": "Before going to understand the difference between require and require_dev first understand what is require and require_dev." }, { "code": null, "e": 24906, "s": 24676, "text": "require: These are must packages for the code to run. It defines the actual dependency as well as package version.require_dev: It defines the packages necessary for developing the project and not needed in production environment." }, { "code": null, "e": 24993, "s": 24906, "text": "Note: The require and require_dev are important parameters available in composer.json." }, { "code": null, "e": 26232, "s": 24993, "text": "What is composer?Composer is dependency/parameter manager in php. It can be used to install keep a track of and update project dependency. Composer also takes care of autoload of dependencies that application relies on letting easily use the dependency inside the project without worrying about including them at the top of any given file. Dependency for project are listed within a “composer.json” file which typically located in the project root. This file holds the information about required version of packages for production and development. This file can be edited manually using any text editor or automatically through the command line via command such as “composer require ” or “composer require_dev .To start using composer in the project first need to create composer.json file. It can be either created manually or simply run composer init. After run composer init in the terminal it will ask some basic information about the project such as package name, description (it is optional), Author and source other information like minimum stability, license and required package.The require key in the composer.json specifies composers which packages the project depends on require takes an object that maps package namesExample:" }, { "code": "{ \"require\": { // name of package. \"composer/composer:\" \"1.2.*\" }}", "e": 26321, "s": 26232, "text": null }, { "code": null, "e": 26782, "s": 26321, "text": "In the above example “composer/composer” specifies vendor name and project name separated by slash (‘/’) and “1.2.*” specifies the version name.To install the dependency need to run the composer install command and then it will find the defined package that method for supplied version constraints and download it into vendor directory. It convention to put third party code into directory named vendor. The installed command also created a composer.lock file." }, { "code": null, "e": 26826, "s": 26782, "text": "Difference Between require and require_dev:" }, { "code": null, "e": 27015, "s": 26826, "text": "require:It define actual dependency as well as package version.The require lists the package require by this package.The package will not be installed unless those requirements can be met." }, { "code": null, "e": 27071, "s": 27015, "text": "It define actual dependency as well as package version." }, { "code": null, "e": 27126, "s": 27071, "text": "The require lists the package require by this package." }, { "code": null, "e": 27198, "s": 27126, "text": "The package will not be installed unless those requirements can be met." }, { "code": null, "e": 27529, "s": 27198, "text": "require_dev:It define the packages necessary for developing project.The require_dev lists packages required for developing this package, or running tests, etc.The dev requirements of the root package are installed by default. Both install or update support the “–no-dev” option that prevents dev dependencies from being installed." }, { "code": null, "e": 27586, "s": 27529, "text": "It define the packages necessary for developing project." }, { "code": null, "e": 27678, "s": 27586, "text": "The require_dev lists packages required for developing this package, or running tests, etc." }, { "code": null, "e": 27850, "s": 27678, "text": "The dev requirements of the root package are installed by default. Both install or update support the “–no-dev” option that prevents dev dependencies from being installed." }, { "code": null, "e": 27863, "s": 27850, "text": "PHP-packages" }, { "code": null, "e": 27870, "s": 27863, "text": "Picked" }, { "code": null, "e": 27874, "s": 27870, "text": "PHP" }, { "code": null, "e": 27891, "s": 27874, "text": "Web Technologies" }, { "code": null, "e": 27895, "s": 27891, "text": "PHP" }, { "code": null, "e": 27993, "s": 27895, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28002, "s": 27993, "text": "Comments" }, { "code": null, "e": 28015, "s": 28002, "text": "Old Comments" }, { "code": null, "e": 28055, "s": 28015, "text": "How to convert array to string in PHP ?" }, { "code": null, "e": 28100, "s": 28055, "text": "PHP | Converting string to Date and DateTime" }, { "code": null, "e": 28142, "s": 28100, "text": "How to pass JavaScript variables to PHP ?" }, { "code": null, "e": 28224, "s": 28142, "text": "How to fetch data from localserver database and display on HTML table using PHP ?" }, { "code": null, "e": 28256, "s": 28224, "text": "How to run JavaScript from PHP?" }, { "code": null, "e": 28298, "s": 28256, "text": "Roadmap to Become a Web Developer in 2022" }, { "code": null, "e": 28331, "s": 28298, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 28374, "s": 28331, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 28436, "s": 28374, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" } ]
What is Pre-Request Script in Postman?
The Pre-Request Script is used to run a JavaScript prior to the execution of a request. By incorporating a Pre-Request Script for a Collection, request or a folder, we can execute precondition steps like defining a variable, Parameters, Headers, Response, or logging console output. We can include a Pre-Request Script to set the order of execution of requests within a Collection. A Pre-Request Script can also handle a scenario in which a value yielded from the request one has to be fed to the next request or the value yielded from the request one has to be processed before moving to the next request. A Pre-Request can also be utilized to set a value from the Response field to a variable linked to a script in the Tests tab. These scripts are defined in the Pre-request Script tab in Postman. Add the below JavaScript in the Pre-Request Script tab − console.log("This is a Postman Tutorial in Tutorialspoint") Select a GET request and enter an endpoint then click on Send. Postman Console Output: Step1 − Click on the three dots beside a Collection in the sidebar. Then click on Edit. Step2 − EDIT COLLECTION pop-up comes up. Click on the Pre-Request Scripts tab to add a pre-condition script. Then click on Update.
[ { "code": null, "e": 1345, "s": 1062, "text": "The Pre-Request Script is used to run a JavaScript prior to the execution of a request. By incorporating a Pre-Request Script for a Collection, request or a folder, we can execute precondition steps like defining a variable, Parameters, Headers, Response, or logging console output." }, { "code": null, "e": 1669, "s": 1345, "text": "We can include a Pre-Request Script to set the order of execution of requests within a Collection. A Pre-Request Script can also handle a scenario in which a value yielded from the request one has to be fed to the next request or the value yielded from the request one has to be processed before moving to the next request." }, { "code": null, "e": 1862, "s": 1669, "text": "A Pre-Request can also be utilized to set a value from the Response field to a variable linked to a script in the Tests tab. These scripts are defined in the Pre-request Script tab in Postman." }, { "code": null, "e": 1919, "s": 1862, "text": "Add the below JavaScript in the Pre-Request Script tab −" }, { "code": null, "e": 1979, "s": 1919, "text": "console.log(\"This is a Postman Tutorial in Tutorialspoint\")" }, { "code": null, "e": 2042, "s": 1979, "text": "Select a GET request and enter an endpoint then click on Send." }, { "code": null, "e": 2066, "s": 2042, "text": "Postman Console Output:" }, { "code": null, "e": 2154, "s": 2066, "text": "Step1 − Click on the three dots beside a Collection in the sidebar. Then click on Edit." }, { "code": null, "e": 2285, "s": 2154, "text": "Step2 − EDIT COLLECTION pop-up comes up. Click on the Pre-Request Scripts tab to add a pre-condition script. Then click on Update." } ]
How to Align Navbar Items to Center using Bootstrap 4 ? - GeeksforGeeks
20 Mar, 2020 In Bootstrap the items can be easily assigned to the left and right as it provides classes for the right and left. By default, left was set, but when it comes to aligning items to the center you have to align it by yourself as there are no in-built classes for doing this. There are basically two ways by which you can align items to the center which are as follows: Using CSS Using Bootstrap Using CSS: In this method, we will use a user-defined class to align items to the center. Then, we will use CSS to align items to the center. We have defined the class navbar-centre. Example:<!DOCTYPE html><html> <head> <title>Align nav bar item into center</title> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous" /> <link rel="stylesheet" type="text/css" href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" /> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css" /> <style> .navbar-nav.navbar-center { position: absolute; left: 50%; transform: translatex(-50%); } </style></head> <body> <!--NAVBAR STARTING--> <nav class="navbar navbar-expand-sm navbar-light bg-light"> <div class="container"> <a class="navbar-brand text-success" href="#"> Geeksforgeeks </a> <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarSupportedContent"> <ul class=" nav navbar-nav navbar-center"> <li class="nav-item active"> <a class="nav-link" href="#"> Home <span class="sr-only"> (current) </span> </a> </li> <li class="nav-item"> <a class="nav-link" href="#"> About </a> </li> <li class="nav-item"> <a class="nav-link" href="#"> About </a> </li> </ul> </div> </div> </nav></body> </html> <!DOCTYPE html><html> <head> <title>Align nav bar item into center</title> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous" /> <link rel="stylesheet" type="text/css" href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" /> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css" /> <style> .navbar-nav.navbar-center { position: absolute; left: 50%; transform: translatex(-50%); } </style></head> <body> <!--NAVBAR STARTING--> <nav class="navbar navbar-expand-sm navbar-light bg-light"> <div class="container"> <a class="navbar-brand text-success" href="#"> Geeksforgeeks </a> <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarSupportedContent"> <ul class=" nav navbar-nav navbar-center"> <li class="nav-item active"> <a class="nav-link" href="#"> Home <span class="sr-only"> (current) </span> </a> </li> <li class="nav-item"> <a class="nav-link" href="#"> About </a> </li> <li class="nav-item"> <a class="nav-link" href="#"> About </a> </li> </ul> </div> </div> </nav></body> </html> Output: By using Bootstrap: This method is a quick tricky that can save you from writing extra CSS. In this, we simply add another div tag above the div tag having class collapse navbar-collapse. This new div tag will also have the same collapse navbar-collapse class. Example:<!DOCTYPE html><html> <head> <title>Align nav bar item into center</title> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous" /> <link rel="stylesheet" type="text/css" href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" /> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css" /> </head> <body> <nav class="navbar navbar-expand-sm navbar-light bg-light"> <div class="container"> <a class="navbar-brand text-success" href="#"> Geeksforgeeks </a> <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse"></div> <div class="collapse navbar-collapse" id="navbarSupportedContent"> <ul class="navbar-nav mr-auto"> <li class="nav-item active"> <a class="nav-link" href="#"> Home <span class="sr-only"> (current) </span> </a> </li> <li class="nav-item"> <a class="nav-link" href="#"> About </a> </li> <li class="nav-item"> <a class="nav-link" href="#"> Contact </a> </li> </ul> </div> </div> </nav></body> </html> <!DOCTYPE html><html> <head> <title>Align nav bar item into center</title> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous" /> <link rel="stylesheet" type="text/css" href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" /> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css" /> </head> <body> <nav class="navbar navbar-expand-sm navbar-light bg-light"> <div class="container"> <a class="navbar-brand text-success" href="#"> Geeksforgeeks </a> <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse"></div> <div class="collapse navbar-collapse" id="navbarSupportedContent"> <ul class="navbar-nav mr-auto"> <li class="nav-item active"> <a class="nav-link" href="#"> Home <span class="sr-only"> (current) </span> </a> </li> <li class="nav-item"> <a class="nav-link" href="#"> About </a> </li> <li class="nav-item"> <a class="nav-link" href="#"> Contact </a> </li> </ul> </div> </div> </nav></body> </html> Output: Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course. Bootstrap-4 Bootstrap-Misc CSS-Misc HTML-Misc Bootstrap CSS HTML Web Technologies Web technologies Questions HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Show Images on Click using HTML ? How to set Bootstrap Timepicker using datetimepicker library ? How to Use Bootstrap with React? How to keep gap between columns using Bootstrap? Tailwind CSS vs Bootstrap How to insert spaces/tabs in text using HTML/CSS? Top 10 Projects For Beginners To Practice HTML and CSS Skills How to create footer to stay at the bottom of a Web page? How to update Node.js and NPM to next version ? CSS to put icon inside an input element in a form
[ { "code": null, "e": 26299, "s": 26271, "text": "\n20 Mar, 2020" }, { "code": null, "e": 26572, "s": 26299, "text": "In Bootstrap the items can be easily assigned to the left and right as it provides classes for the right and left. By default, left was set, but when it comes to aligning items to the center you have to align it by yourself as there are no in-built classes for doing this." }, { "code": null, "e": 26666, "s": 26572, "text": "There are basically two ways by which you can align items to the center which are as follows:" }, { "code": null, "e": 26676, "s": 26666, "text": "Using CSS" }, { "code": null, "e": 26692, "s": 26676, "text": "Using Bootstrap" }, { "code": null, "e": 26875, "s": 26692, "text": "Using CSS: In this method, we will use a user-defined class to align items to the center. Then, we will use CSS to align items to the center. We have defined the class navbar-centre." }, { "code": null, "e": 29203, "s": 26875, "text": "Example:<!DOCTYPE html><html> <head> <title>Align nav bar item into center</title> <link rel=\"stylesheet\" href=\"https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css\" integrity=\"sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T\" crossorigin=\"anonymous\" /> <link rel=\"stylesheet\" type=\"text/css\" href=\"https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css\" /> <link rel=\"stylesheet\" href=\"https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css\" /> <style> .navbar-nav.navbar-center { position: absolute; left: 50%; transform: translatex(-50%); } </style></head> <body> <!--NAVBAR STARTING--> <nav class=\"navbar navbar-expand-sm navbar-light bg-light\"> <div class=\"container\"> <a class=\"navbar-brand text-success\" href=\"#\"> Geeksforgeeks </a> <button class=\"navbar-toggler\" type=\"button\" data-toggle=\"collapse\" data-target=\"#navbarSupportedContent\" aria-controls=\"navbarSupportedContent\" aria-expanded=\"false\" aria-label=\"Toggle navigation\"> <span class=\"navbar-toggler-icon\"></span> </button> <div class=\"collapse navbar-collapse\" id=\"navbarSupportedContent\"> <ul class=\" nav navbar-nav navbar-center\"> <li class=\"nav-item active\"> <a class=\"nav-link\" href=\"#\"> Home <span class=\"sr-only\"> (current) </span> </a> </li> <li class=\"nav-item\"> <a class=\"nav-link\" href=\"#\"> About </a> </li> <li class=\"nav-item\"> <a class=\"nav-link\" href=\"#\"> About </a> </li> </ul> </div> </div> </nav></body> </html>" }, { "code": "<!DOCTYPE html><html> <head> <title>Align nav bar item into center</title> <link rel=\"stylesheet\" href=\"https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css\" integrity=\"sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T\" crossorigin=\"anonymous\" /> <link rel=\"stylesheet\" type=\"text/css\" href=\"https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css\" /> <link rel=\"stylesheet\" href=\"https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css\" /> <style> .navbar-nav.navbar-center { position: absolute; left: 50%; transform: translatex(-50%); } </style></head> <body> <!--NAVBAR STARTING--> <nav class=\"navbar navbar-expand-sm navbar-light bg-light\"> <div class=\"container\"> <a class=\"navbar-brand text-success\" href=\"#\"> Geeksforgeeks </a> <button class=\"navbar-toggler\" type=\"button\" data-toggle=\"collapse\" data-target=\"#navbarSupportedContent\" aria-controls=\"navbarSupportedContent\" aria-expanded=\"false\" aria-label=\"Toggle navigation\"> <span class=\"navbar-toggler-icon\"></span> </button> <div class=\"collapse navbar-collapse\" id=\"navbarSupportedContent\"> <ul class=\" nav navbar-nav navbar-center\"> <li class=\"nav-item active\"> <a class=\"nav-link\" href=\"#\"> Home <span class=\"sr-only\"> (current) </span> </a> </li> <li class=\"nav-item\"> <a class=\"nav-link\" href=\"#\"> About </a> </li> <li class=\"nav-item\"> <a class=\"nav-link\" href=\"#\"> About </a> </li> </ul> </div> </div> </nav></body> </html>", "e": 31523, "s": 29203, "text": null }, { "code": null, "e": 31531, "s": 31523, "text": "Output:" }, { "code": null, "e": 31792, "s": 31531, "text": "By using Bootstrap: This method is a quick tricky that can save you from writing extra CSS. In this, we simply add another div tag above the div tag having class collapse navbar-collapse. This new div tag will also have the same collapse navbar-collapse class." }, { "code": null, "e": 33988, "s": 31792, "text": "Example:<!DOCTYPE html><html> <head> <title>Align nav bar item into center</title> <link rel=\"stylesheet\" href=\"https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css\" integrity=\"sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T\" crossorigin=\"anonymous\" /> <link rel=\"stylesheet\" type=\"text/css\" href=\"https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css\" /> <link rel=\"stylesheet\" href=\"https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css\" /> </head> <body> <nav class=\"navbar navbar-expand-sm navbar-light bg-light\"> <div class=\"container\"> <a class=\"navbar-brand text-success\" href=\"#\"> Geeksforgeeks </a> <button class=\"navbar-toggler\" type=\"button\" data-toggle=\"collapse\" data-target=\"#navbarSupportedContent\" aria-controls=\"navbarSupportedContent\" aria-expanded=\"false\" aria-label=\"Toggle navigation\"> <span class=\"navbar-toggler-icon\"></span> </button> <div class=\"collapse navbar-collapse\"></div> <div class=\"collapse navbar-collapse\" id=\"navbarSupportedContent\"> <ul class=\"navbar-nav mr-auto\"> <li class=\"nav-item active\"> <a class=\"nav-link\" href=\"#\"> Home <span class=\"sr-only\"> (current) </span> </a> </li> <li class=\"nav-item\"> <a class=\"nav-link\" href=\"#\"> About </a> </li> <li class=\"nav-item\"> <a class=\"nav-link\" href=\"#\"> Contact </a> </li> </ul> </div> </div> </nav></body> </html>" }, { "code": "<!DOCTYPE html><html> <head> <title>Align nav bar item into center</title> <link rel=\"stylesheet\" href=\"https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css\" integrity=\"sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T\" crossorigin=\"anonymous\" /> <link rel=\"stylesheet\" type=\"text/css\" href=\"https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css\" /> <link rel=\"stylesheet\" href=\"https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css\" /> </head> <body> <nav class=\"navbar navbar-expand-sm navbar-light bg-light\"> <div class=\"container\"> <a class=\"navbar-brand text-success\" href=\"#\"> Geeksforgeeks </a> <button class=\"navbar-toggler\" type=\"button\" data-toggle=\"collapse\" data-target=\"#navbarSupportedContent\" aria-controls=\"navbarSupportedContent\" aria-expanded=\"false\" aria-label=\"Toggle navigation\"> <span class=\"navbar-toggler-icon\"></span> </button> <div class=\"collapse navbar-collapse\"></div> <div class=\"collapse navbar-collapse\" id=\"navbarSupportedContent\"> <ul class=\"navbar-nav mr-auto\"> <li class=\"nav-item active\"> <a class=\"nav-link\" href=\"#\"> Home <span class=\"sr-only\"> (current) </span> </a> </li> <li class=\"nav-item\"> <a class=\"nav-link\" href=\"#\"> About </a> </li> <li class=\"nav-item\"> <a class=\"nav-link\" href=\"#\"> Contact </a> </li> </ul> </div> </div> </nav></body> </html>", "e": 36176, "s": 33988, "text": null }, { "code": null, "e": 36184, "s": 36176, "text": "Output:" }, { "code": null, "e": 36321, "s": 36184, "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": 36333, "s": 36321, "text": "Bootstrap-4" }, { "code": null, "e": 36348, "s": 36333, "text": "Bootstrap-Misc" }, { "code": null, "e": 36357, "s": 36348, "text": "CSS-Misc" }, { "code": null, "e": 36367, "s": 36357, "text": "HTML-Misc" }, { "code": null, "e": 36377, "s": 36367, "text": "Bootstrap" }, { "code": null, "e": 36381, "s": 36377, "text": "CSS" }, { "code": null, "e": 36386, "s": 36381, "text": "HTML" }, { "code": null, "e": 36403, "s": 36386, "text": "Web Technologies" }, { "code": null, "e": 36430, "s": 36403, "text": "Web technologies Questions" }, { "code": null, "e": 36435, "s": 36430, "text": "HTML" }, { "code": null, "e": 36533, "s": 36435, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 36574, "s": 36533, "text": "How to Show Images on Click using HTML ?" }, { "code": null, "e": 36637, "s": 36574, "text": "How to set Bootstrap Timepicker using datetimepicker library ?" }, { "code": null, "e": 36670, "s": 36637, "text": "How to Use Bootstrap with React?" }, { "code": null, "e": 36719, "s": 36670, "text": "How to keep gap between columns using Bootstrap?" }, { "code": null, "e": 36745, "s": 36719, "text": "Tailwind CSS vs Bootstrap" }, { "code": null, "e": 36795, "s": 36745, "text": "How to insert spaces/tabs in text using HTML/CSS?" }, { "code": null, "e": 36857, "s": 36795, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 36915, "s": 36857, "text": "How to create footer to stay at the bottom of a Web page?" }, { "code": null, "e": 36963, "s": 36915, "text": "How to update Node.js and NPM to next version ?" } ]
Foldable Binary Tree | Practice | GeeksforGeeks
Given a binary tree, check if the tree can be folded or not. A tree can be folded if left and right subtrees of the tree are structure wise same. An empty tree is considered as foldable. Consider the below trees: (a) and (b) can be folded. (c) and (d) cannot be folded. Example 1: Input: 10 / \ 7 15 / \ / \ N 9 11 N Output:Yes Example 2: Input: 10 / \ 7 15 / \ / \ 5 N 11 N Output: No Your Task: The task is to complete the function isFoldable() that takes root of the tree as input and returns true or false depending upon whether the tree is foldable or not. Expected Time Complexity: O(N). Expected Auxiliary Space: O(Height of the Tree). Constraints: 0 <= n <= 103 1 <= data of node <= 104 0 singhdipranjan673 days ago //very simple solution boolean IsFoldable(Node root) { if(root==null) return true; return DFS(root.left, root.right); } boolean DFS(Node root1, Node root2) { if(root1==null && root2==null) return true; if((root1==null && root2!=null) || (root2==null && root1!=null)) return false; return (DFS(root1.left, root2.right) && DFS(root1.right, root2.left)); } } 0 amankumar2783 weeks ago Java Solution: class Tree{ boolean check(Node root1,Node root2){ if(root1==null&&root2==null){ return true; } if(root1==null||root2==null){ return false; } return check(root1.left,root2.right)&&check(root1.right,root2.left); } //Function to check whether a binary tree is foldable or not. boolean IsFoldable(Node node) { if(node==null){ return true; } return check(node.left,node.right);} } 0 anujsonijnv171 month ago //very simple and easy recursive c++ code bool helper(Node* t,Node* s){ if(t==NULL&&s==NULL)return 1; if(t==NULL||s==NULL)return 0; return helper(t->left,s->right) && helper(t->right,s->left);} bool IsFoldable(Node* root){ if (root==NULL)return true; return helper(root->left,root->right);} 0 gujjulassr1 month ago 0.2/1.4 boolean IsFoldable(Node node) { // your code if(node==null){ return true; } Deque<Node> deq=new LinkedList<Node>(); Deque<Node> out=new LinkedList<Node>(); out.addLast(node); while(!out.isEmpty()){ int count=out.size(); for(int i=0;i<count;i++){ Node curr=out.removeFirst(); deq.addLast(curr.left); if(curr.left!=null){ out.addLast(curr.left); } if(curr.right!=null){ out.addLast(curr.right); } deq.addLast(curr.right); } if(!match(deq)){ return false; } deq.clear(); } return true;} public boolean match(Deque<Node> deq){ while(!deq.isEmpty()){ Node front=deq.removeFirst(); if(deq.isEmpty()){ return true; } Node back=deq.removeLast(); if(back!=null && front==null){ return false; } if(back==null && front!=null){ return false; } } return true;}} 0 forcer This comment was deleted. +1 ishrivastava252 months ago //Easy Solution bool helper(Node* root1,Node* root2){ if(root1==NULL && root2==NULL) return true; if(root1==NULL || root2==NULL) return false; return helper(root1->left,root2->right) && helper(root1->right,root2->left);} bool IsFoldable(Node* root){ if(root==NULL || (root->left==NULL && root->right==NULL)) { return true; } if(root->left==NULL || root->right==NULL) return false; return helper(root->left,root->right);} 0 krishnarathi3412 months ago c++ solution We have to simultaneously check for left and right sub-tree Nodes so, we would iterate over the tree using postorder and recusively check for right and left tree has foldable structure or not During, iteration if there arises a case where subtrees i.e. t1 (root→left) and t2 (root→right) t1=NULL && t2≠NULL We would return false else true; if(t1==NULL) return t1==t2; The above condition checks for all possiblilites related to T1 is NULL or not and T2 is NULL or not. bool checkLeftandRight(Node *t1,Node *t2){ if(t1==NULL) return t1==t2; if(t1!=NULL && t2!=NULL){ bool l = checkLeftandRight(t1->left,t2->right); bool r = checkLeftandRight(t1->right,t2->left); return (l && r); } return false; } //Function to check whether a binary tree is foldable or not. bool IsFoldable(Node* root) { // Your code goes here if(root==NULL) return true; return checkLeftandRight(root->left,root->right); } 0 siddhant073 months ago Iterative Solution using deque O(N) time and O(N) space bool IsFoldable(Node* root) { if(root == NULL){ return true; } deque<Node*> dq; dq.push_back(root); while(dq.empty() == false){ int count = dq.size(); deque<Node*> d; for(int i = 0; i < count; i++){ Node* f = dq[i]; Node* b = dq[count - i - 1]; if(f->left != NULL){ if(b->right != NULL){ d.push_back(f->left); } else{ return false; } } if(f->right != NULL){ if(b->left != NULL){ d.push_back(f->right); } else{ return false; } } } dq = d; } return true; } 0 vishnu12653 months ago Java Solution : class Tree { //Function to check whether a binary tree is foldable or not. boolean IsFoldable(Node node) { if(node==null) return true; return foldable(node.left,node.right); } boolean foldable(Node root1,Node root2){ if(root1==null && root2==null) return true; else if(root1==null || root2==null) return false; else return foldable(root1.left,root2.right) && foldable(root1.right,root2.left); } } +1 kronizerdeltac3 months ago JAVA SOLUTION boolean IsFoldable_(Node root1, Node root2) { if(root1 == null && root2 == null) return true; if(root1 == null || root2 == null) return false; return IsFoldable_(root1.left, root2.right) && IsFoldable_(root1.right, root2.left); } boolean IsFoldable(Node root) { if(root == null) return true; return IsFoldable_(root, root);} } boolean IsFoldable(Node root) { if(root == null) return true; return IsFoldable_(root, root);} 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": 508, "s": 238, "text": "Given a binary tree, check if the tree can be folded or not. A tree can be folded if left and right subtrees of the tree are structure wise same. An empty tree is considered as foldable.\nConsider the below trees:\n(a) and (b) can be folded.\n(c) and (d) cannot be folded." }, { "code": null, "e": 519, "s": 508, "text": "Example 1:" }, { "code": null, "e": 596, "s": 519, "text": "Input:\n 10\n / \\\n 7 15\n / \\ / \\\nN 9 11 N\nOutput:Yes\n" }, { "code": null, "e": 607, "s": 596, "text": "Example 2:" }, { "code": null, "e": 686, "s": 607, "text": "Input:\n 10\n / \\\n 7 15\n / \\ / \\\n5 N 11 N\nOutput: No\n\n" }, { "code": null, "e": 862, "s": 686, "text": "Your Task:\nThe task is to complete the function isFoldable() that takes root of the tree as input and returns true or false depending upon whether the tree is foldable or not." }, { "code": null, "e": 943, "s": 862, "text": "Expected Time Complexity: O(N).\nExpected Auxiliary Space: O(Height of the Tree)." }, { "code": null, "e": 995, "s": 943, "text": "Constraints:\n0 <= n <= 103\n1 <= data of node <= 104" }, { "code": null, "e": 997, "s": 995, "text": "0" }, { "code": null, "e": 1024, "s": 997, "text": "singhdipranjan673 days ago" }, { "code": null, "e": 1453, "s": 1024, "text": "//very simple solution\nboolean IsFoldable(Node root) \n\t{ \n\t if(root==null)\n\t return true;\n\t return DFS(root.left, root.right);\n\t} \n\n boolean DFS(Node root1, Node root2)\n {\n if(root1==null && root2==null)\n return true;\n if((root1==null && root2!=null) || (root2==null && root1!=null))\n return false;\n return (DFS(root1.left, root2.right) && DFS(root1.right, root2.left));\n }\n}" }, { "code": null, "e": 1455, "s": 1453, "text": "0" }, { "code": null, "e": 1479, "s": 1455, "text": "amankumar2783 weeks ago" }, { "code": null, "e": 1494, "s": 1479, "text": "Java Solution:" }, { "code": null, "e": 1929, "s": 1496, "text": "class Tree{ boolean check(Node root1,Node root2){ if(root1==null&&root2==null){ return true; } if(root1==null||root2==null){ return false; } return check(root1.left,root2.right)&&check(root1.right,root2.left); } //Function to check whether a binary tree is foldable or not. boolean IsFoldable(Node node) { if(node==null){ return true; } return check(node.left,node.right);} }" }, { "code": null, "e": 1931, "s": 1929, "text": "0" }, { "code": null, "e": 1956, "s": 1931, "text": "anujsonijnv171 month ago" }, { "code": null, "e": 1998, "s": 1956, "text": "//very simple and easy recursive c++ code" }, { "code": null, "e": 2164, "s": 2000, "text": "bool helper(Node* t,Node* s){ if(t==NULL&&s==NULL)return 1; if(t==NULL||s==NULL)return 0; return helper(t->left,s->right) && helper(t->right,s->left);}" }, { "code": null, "e": 2261, "s": 2164, "text": "bool IsFoldable(Node* root){ if (root==NULL)return true; return helper(root->left,root->right);}" }, { "code": null, "e": 2263, "s": 2261, "text": "0" }, { "code": null, "e": 2285, "s": 2263, "text": "gujjulassr1 month ago" }, { "code": null, "e": 2293, "s": 2285, "text": "0.2/1.4" }, { "code": null, "e": 2823, "s": 2295, "text": " boolean IsFoldable(Node node) { // your code if(node==null){ return true; } Deque<Node> deq=new LinkedList<Node>(); Deque<Node> out=new LinkedList<Node>(); out.addLast(node); while(!out.isEmpty()){ int count=out.size(); for(int i=0;i<count;i++){ Node curr=out.removeFirst(); deq.addLast(curr.left); if(curr.left!=null){ out.addLast(curr.left); } if(curr.right!=null){ out.addLast(curr.right); } deq.addLast(curr.right); }" }, { "code": null, "e": 3281, "s": 2823, "text": " if(!match(deq)){ return false; } deq.clear(); } return true;} public boolean match(Deque<Node> deq){ while(!deq.isEmpty()){ Node front=deq.removeFirst(); if(deq.isEmpty()){ return true; } Node back=deq.removeLast(); if(back!=null && front==null){ return false; } if(back==null && front!=null){ return false; } } return true;}}" }, { "code": null, "e": 3283, "s": 3281, "text": "0" }, { "code": null, "e": 3290, "s": 3283, "text": "forcer" }, { "code": null, "e": 3316, "s": 3290, "text": "This comment was deleted." }, { "code": null, "e": 3319, "s": 3316, "text": "+1" }, { "code": null, "e": 3346, "s": 3319, "text": "ishrivastava252 months ago" }, { "code": null, "e": 3363, "s": 3346, "text": "//Easy Solution " }, { "code": null, "e": 3576, "s": 3365, "text": "bool helper(Node* root1,Node* root2){ if(root1==NULL && root2==NULL) return true; if(root1==NULL || root2==NULL) return false; return helper(root1->left,root2->right) && helper(root1->right,root2->left);}" }, { "code": null, "e": 3792, "s": 3576, "text": "bool IsFoldable(Node* root){ if(root==NULL || (root->left==NULL && root->right==NULL)) { return true; } if(root->left==NULL || root->right==NULL) return false; return helper(root->left,root->right);}" }, { "code": null, "e": 3794, "s": 3792, "text": "0" }, { "code": null, "e": 3822, "s": 3794, "text": "krishnarathi3412 months ago" }, { "code": null, "e": 3835, "s": 3822, "text": "c++ solution" }, { "code": null, "e": 3902, "s": 3835, "text": "We have to simultaneously check for left and right sub-tree Nodes " }, { "code": null, "e": 4029, "s": 3902, "text": "so, we would iterate over the tree using postorder and recusively check for right and left tree has foldable structure or not " }, { "code": null, "e": 4180, "s": 4029, "text": "During, iteration if there arises a case where subtrees i.e. t1 (root→left) and t2 (root→right) t1=NULL && t2≠NULL We would return false else true;" }, { "code": null, "e": 4208, "s": 4180, "text": "if(t1==NULL) return t1==t2;" }, { "code": null, "e": 4309, "s": 4208, "text": "The above condition checks for all possiblilites related to T1 is NULL or not and T2 is NULL or not." }, { "code": null, "e": 4787, "s": 4309, "text": "bool checkLeftandRight(Node *t1,Node *t2){\n if(t1==NULL) return t1==t2;\n if(t1!=NULL && t2!=NULL){\n bool l = checkLeftandRight(t1->left,t2->right);\n bool r = checkLeftandRight(t1->right,t2->left);\n return (l && r);\n }\n return false;\n}\n\n//Function to check whether a binary tree is foldable or not.\nbool IsFoldable(Node* root)\n{\n // Your code goes here\n if(root==NULL) return true;\n return checkLeftandRight(root->left,root->right);\n}\n" }, { "code": null, "e": 4789, "s": 4787, "text": "0" }, { "code": null, "e": 4812, "s": 4789, "text": "siddhant073 months ago" }, { "code": null, "e": 4868, "s": 4812, "text": "Iterative Solution using deque O(N) time and O(N) space" }, { "code": null, "e": 5656, "s": 4868, "text": "bool IsFoldable(Node* root)\n{\n if(root == NULL){\n return true;\n }\n deque<Node*> dq;\n dq.push_back(root);\n while(dq.empty() == false){\n int count = dq.size();\n deque<Node*> d;\n for(int i = 0; i < count; i++){\n Node* f = dq[i];\n Node* b = dq[count - i - 1];\n if(f->left != NULL){\n if(b->right != NULL){\n d.push_back(f->left);\n }\n else{\n return false;\n }\n }\n if(f->right != NULL){\n if(b->left != NULL){\n d.push_back(f->right);\n }\n else{\n return false;\n }\n }\n }\n dq = d;\n }\n return true;\n}" }, { "code": null, "e": 5660, "s": 5658, "text": "0" }, { "code": null, "e": 5683, "s": 5660, "text": "vishnu12653 months ago" }, { "code": null, "e": 5699, "s": 5683, "text": "Java Solution :" }, { "code": null, "e": 6140, "s": 5699, "text": "class Tree\n{\n //Function to check whether a binary tree is foldable or not.\n boolean IsFoldable(Node node) \n\t{ \n\t if(node==null) return true;\n\t\treturn foldable(node.left,node.right);\n\t} \n\t\n\tboolean foldable(Node root1,Node root2){\n\t if(root1==null && root2==null) return true;\n\t else if(root1==null || root2==null) return false;\n\t else return foldable(root1.left,root2.right) && foldable(root1.right,root2.left);\n\t}\n\t\n\t\n}" }, { "code": null, "e": 6143, "s": 6140, "text": "+1" }, { "code": null, "e": 6170, "s": 6143, "text": "kronizerdeltac3 months ago" }, { "code": null, "e": 6185, "s": 6170, "text": "JAVA SOLUTION " }, { "code": null, "e": 6478, "s": 6187, "text": "boolean IsFoldable_(Node root1, Node root2) { if(root1 == null && root2 == null) return true; if(root1 == null || root2 == null) return false; return IsFoldable_(root1.left, root2.right) && IsFoldable_(root1.right, root2.left);" }, { "code": null, "e": 6591, "s": 6478, "text": " } boolean IsFoldable(Node root) { if(root == null) return true; return IsFoldable_(root, root);}" }, { "code": null, "e": 6704, "s": 6591, "text": " } boolean IsFoldable(Node root) { if(root == null) return true; return IsFoldable_(root, root);}" }, { "code": null, "e": 6850, "s": 6704, "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": 6886, "s": 6850, "text": " Login to access your submissions. " }, { "code": null, "e": 6896, "s": 6886, "text": "\nProblem\n" }, { "code": null, "e": 6906, "s": 6896, "text": "\nContest\n" }, { "code": null, "e": 6969, "s": 6906, "text": "Reset the IDE using the second button on the top right corner." }, { "code": null, "e": 7117, "s": 6969, "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": 7325, "s": 7117, "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": 7431, "s": 7325, "text": "You can access the hints to get an idea about what is expected of you as well as the final solution code." } ]
Joining 4 Tables in SQL - GeeksforGeeks
01 Sep, 2021 The purpose of this article is to make a simple program to Join two tables using Join and Where clause in SQL. Below is the implementation for the same using MySQL. The prerequisites of this topic are MySQL and the installment of Apache Server on your computer. Introduction :In SQL, a query is a request with some instruction such that inserting, reading, deleting, and updating, etc. record from the database. This data can be used for various purposes like Training a model, finding the patterns in the data, etc. Here, we will discuss the approach for Joining 4 Tables in SQL and will implement using SQL query for each table for better understanding. Approach :Here, we will discuss the approach and steps to implement Joining 4 Tables in SQL. So, let’s start by creating a Database. Step-1: Create a database –Here first, we will create the database using SQL query as follows. CREATE DATABASE geeksforgeeks; Step-2: Use the database –Now, we will use the database using SQL query as follows. USE geeksforgeeks; Step-3: Creating table1 –Create a table 1, name as s_marks using SQL query as follows. CREATE TABLE s_marks ( studentid int(10) PRIMARY KEY, subjectid VARCHAR(10), professorid int(10) ); Step-4: Creating table2 – Create a table2 for the professor details as p_details using SQL query as follows. CREATE TABLE p_details ( pid int(10) PRIMARY KEY, pname VARCHAR(50), pemail VARCHAR(50) ); Step-5: Creating table3 – Create a table for subjects as subjects using SQL query as follows. CREATE TABLE subjects ( subjectid VARCHAR(10) PRIMARY KEY, total_marks INT(5) ); Step-6: Creating table4 – Create a table for the subject marks details using SQL query as follows. CREATE TABLE marks_details ( total_marks INT(5) PRIMARY KEY, theory INT(5), practical INT(5) ); Output :The output of tables as follows. Step-7: Inserting data :Insert some data in the above-created tables using SQL query as follows. Insert into s_marks – INSERT INTO `s_marks` (`studentid`, `subjectid`, `professorid`) VALUES ('1', 'KCS101', '1'); INSERT INTO `s_marks` (`studentid`, `subjectid`, `professorid`) VALUES ('2', 'KCS102', '2'); Insert into p_details – INSERT INTO `p_details` (`pid`, `pname`, `pemail`) VALUES ('1', 'Devesh', 'geeks@abc.com'); INSERT INTO `p_details` (`pid`, `pname`, `pemail`) VALUES ('2', 'Aditya', 'for@abc.com'); Insert into subjects – INSERT INTO `subjects` (`subjectid`, `total_marks`) VALUES ('KCS101', '100'); INSERT INTO `subjects` (`subjectid`, `total_marks`) VALUES ('KCS102', '150'); Insert into marks_details – INSERT INTO `marks_details` (`total_marks`, `theory`, `practical`) VALUES ('100', '70', '30'); INSERT INTO `marks_details` (`total_marks`, `theory`, `practical`) VALUES ('150', '100', '50'); Step-8: Verifying and joining tables –Run the query to find out the ID, professor name of a student whose subject’s practical marks are 50 as follows. SELECT s_marks.studentid, p_details.pname FROM s_marks JOIN subjects ON s_marks.subjectid = subjects.subjectid JOIN marks_details ON subjects.total_marks = marks_details.total_marks JOIN p_details ON p_details.pid = s_marks.professorid WHERE marks_details.practical = '50'; Output : rajeev0719singh DBMS-SQL Picked SQL SQL Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Update Multiple Columns in Single Update Statement in SQL? How to Create a Table With Multiple Foreign Keys in SQL? What is Temporary Table in SQL? SQL | Subquery SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter SQL Query to Convert VARCHAR to INT SQL using Python How to Write a SQL Query For a Specific Date Range and Date Time? How to Select Data Between Two Dates and Times in SQL Server? SQL Query to Compare Two Dates
[ { "code": null, "e": 25537, "s": 25509, "text": "\n01 Sep, 2021" }, { "code": null, "e": 25799, "s": 25537, "text": "The purpose of this article is to make a simple program to Join two tables using Join and Where clause in SQL. Below is the implementation for the same using MySQL. The prerequisites of this topic are MySQL and the installment of Apache Server on your computer." }, { "code": null, "e": 26194, "s": 25799, "text": "Introduction :In SQL, a query is a request with some instruction such that inserting, reading, deleting, and updating, etc. record from the database. This data can be used for various purposes like Training a model, finding the patterns in the data, etc. Here, we will discuss the approach for Joining 4 Tables in SQL and will implement using SQL query for each table for better understanding. " }, { "code": null, "e": 26327, "s": 26194, "text": "Approach :Here, we will discuss the approach and steps to implement Joining 4 Tables in SQL. So, let’s start by creating a Database." }, { "code": null, "e": 26422, "s": 26327, "text": "Step-1: Create a database –Here first, we will create the database using SQL query as follows." }, { "code": null, "e": 26453, "s": 26422, "text": "CREATE DATABASE geeksforgeeks;" }, { "code": null, "e": 26537, "s": 26453, "text": "Step-2: Use the database –Now, we will use the database using SQL query as follows." }, { "code": null, "e": 26556, "s": 26537, "text": "USE geeksforgeeks;" }, { "code": null, "e": 26643, "s": 26556, "text": "Step-3: Creating table1 –Create a table 1, name as s_marks using SQL query as follows." }, { "code": null, "e": 26746, "s": 26643, "text": "CREATE TABLE s_marks \n(\nstudentid int(10) PRIMARY KEY, \nsubjectid VARCHAR(10), \nprofessorid int(10)\n);" }, { "code": null, "e": 26855, "s": 26746, "text": "Step-4: Creating table2 – Create a table2 for the professor details as p_details using SQL query as follows." }, { "code": null, "e": 26949, "s": 26855, "text": "CREATE TABLE p_details \n(\npid int(10) PRIMARY KEY, \npname VARCHAR(50), \npemail VARCHAR(50)\n);" }, { "code": null, "e": 27043, "s": 26949, "text": "Step-5: Creating table3 – Create a table for subjects as subjects using SQL query as follows." }, { "code": null, "e": 27127, "s": 27043, "text": "CREATE TABLE subjects \n(\nsubjectid VARCHAR(10) PRIMARY KEY, \ntotal_marks INT(5)\n);" }, { "code": null, "e": 27227, "s": 27127, "text": "Step-6: Creating table4 – Create a table for the subject marks details using SQL query as follows. " }, { "code": null, "e": 27325, "s": 27227, "text": "CREATE TABLE marks_details \n(\ntotal_marks INT(5) PRIMARY KEY, \ntheory INT(5),\npractical INT(5)\n);" }, { "code": null, "e": 27366, "s": 27325, "text": "Output :The output of tables as follows." }, { "code": null, "e": 27464, "s": 27366, "text": "Step-7: Inserting data :Insert some data in the above-created tables using SQL query as follows. " }, { "code": null, "e": 27487, "s": 27464, "text": "Insert into s_marks – " }, { "code": null, "e": 27673, "s": 27487, "text": "INSERT INTO `s_marks` (`studentid`, `subjectid`, `professorid`) VALUES ('1', 'KCS101', '1');\nINSERT INTO `s_marks` (`studentid`, `subjectid`, `professorid`) VALUES ('2', 'KCS102', '2');" }, { "code": null, "e": 27697, "s": 27673, "text": "Insert into p_details –" }, { "code": null, "e": 27879, "s": 27697, "text": "INSERT INTO `p_details` (`pid`, `pname`, `pemail`) VALUES ('1', 'Devesh', 'geeks@abc.com');\nINSERT INTO `p_details` (`pid`, `pname`, `pemail`) VALUES ('2', 'Aditya', 'for@abc.com');" }, { "code": null, "e": 27902, "s": 27879, "text": "Insert into subjects –" }, { "code": null, "e": 28058, "s": 27902, "text": "INSERT INTO `subjects` (`subjectid`, `total_marks`) VALUES ('KCS101', '100');\nINSERT INTO `subjects` (`subjectid`, `total_marks`) VALUES ('KCS102', '150');" }, { "code": null, "e": 28087, "s": 28058, "text": "Insert into marks_details – " }, { "code": null, "e": 28278, "s": 28087, "text": "INSERT INTO `marks_details` (`total_marks`, `theory`, `practical`) VALUES ('100', '70', '30');\nINSERT INTO `marks_details` (`total_marks`, `theory`, `practical`) VALUES ('150', '100', '50');" }, { "code": null, "e": 28429, "s": 28278, "text": "Step-8: Verifying and joining tables –Run the query to find out the ID, professor name of a student whose subject’s practical marks are 50 as follows." }, { "code": null, "e": 28705, "s": 28429, "text": "SELECT s_marks.studentid, p_details.pname FROM s_marks \nJOIN subjects ON s_marks.subjectid = subjects.subjectid \nJOIN marks_details ON subjects.total_marks = marks_details.total_marks\nJOIN p_details ON p_details.pid = s_marks.professorid\nWHERE marks_details.practical = '50';" }, { "code": null, "e": 28714, "s": 28705, "text": "Output :" }, { "code": null, "e": 28730, "s": 28714, "text": "rajeev0719singh" }, { "code": null, "e": 28739, "s": 28730, "text": "DBMS-SQL" }, { "code": null, "e": 28746, "s": 28739, "text": "Picked" }, { "code": null, "e": 28750, "s": 28746, "text": "SQL" }, { "code": null, "e": 28754, "s": 28750, "text": "SQL" }, { "code": null, "e": 28852, "s": 28754, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28918, "s": 28852, "text": "How to Update Multiple Columns in Single Update Statement in SQL?" }, { "code": null, "e": 28975, "s": 28918, "text": "How to Create a Table With Multiple Foreign Keys in SQL?" }, { "code": null, "e": 29007, "s": 28975, "text": "What is Temporary Table in SQL?" }, { "code": null, "e": 29022, "s": 29007, "text": "SQL | Subquery" }, { "code": null, "e": 29100, "s": 29022, "text": "SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter" }, { "code": null, "e": 29136, "s": 29100, "text": "SQL Query to Convert VARCHAR to INT" }, { "code": null, "e": 29153, "s": 29136, "text": "SQL using Python" }, { "code": null, "e": 29219, "s": 29153, "text": "How to Write a SQL Query For a Specific Date Range and Date Time?" }, { "code": null, "e": 29281, "s": 29219, "text": "How to Select Data Between Two Dates and Times in SQL Server?" } ]
Find the sum of first N odd Fibonacci numbers - GeeksforGeeks
23 Jul, 2021 Given a number, N. Find the sum of first N odd Fibonacci numbers.Note: The answer can be very large so print the answer modulo 10^9+7. Examples: Input : N = 3 Output : 5 Explanation : 1 + 1 + 3 Input : 6 Output : 44 Explanation : 1 + 1 + 3 + 5 + 13 + 21 Approach :Odd Fibonacci series is: 1, 1, 3, 5, 13, 21, 55, 89...... Prefix sum of odd Fibonacci series is: 1, 2, 5, 10, 23, 44, 99, 188..... The formula for the sum of first N odd Fibonacci numbers is: a(n) = a(n-1) + 4*a(n-2) – 4*a(n-3) + a(n-4) – a(n-5) for n>5 Below is the implementation of the above approach: C++ Java Python3 C# PHP Javascript // CPP program to Find the sum of// first N odd Fibonacci numbers#include <bits/stdc++.h>using namespace std; #define mod 1000000007 // Function to calculate sum of first// N odd Fibonacci numberslong long sumOddFibonacci(int n){ long long Sum[n + 1]; // base values Sum[0] = 0; Sum[1] = 1; Sum[2] = 2; Sum[3] = 5; Sum[4] = 10; Sum[5] = 23; for (int i = 6; i <= n; i++) { Sum[i] = ((Sum[i - 1] + (4 * Sum[i - 2]) % mod - (4 * Sum[i - 3]) % mod + mod) % mod + (Sum[i - 4] - Sum[i - 5] + mod) % mod) % mod; } return Sum[n];} // Driver codeint main(){ long long n = 6; cout << sumOddFibonacci(n); return 0;} // Java program to Find the sum of// first N odd Fibonacci numbers import java.io.*; class GFG { static int mod =1000000007; // Function to calculate sum of first// N odd Fibonacci numbersstatic int sumOddFibonacci(int n){ int Sum[]=new int[n + 1]; // base values Sum[0] = 0; Sum[1] = 1; Sum[2] = 2; Sum[3] = 5; Sum[4] = 10; Sum[5] = 23; for (int i = 6; i <= n; i++) { Sum[i] = ((Sum[i - 1] + (4 * Sum[i - 2]) % mod - (4 * Sum[i - 3]) % mod + mod) % mod + (Sum[i - 4] - Sum[i - 5] + mod) % mod) % mod; } return Sum[n];} // Driver code public static void main (String[] args) { int n = 6; System.out.println(sumOddFibonacci(n)); }//This Code is Contributed by Sachin } # Python3 program to Find the sum of# first N odd Fibonacci numbersmod = 1000000007 ; # Function to calculate sum of# first N odd Fibonacci numbersdef sumOddFibonacci(n): Sum=[0]*(n + 1); # base values Sum[0] = 0; Sum[1] = 1; Sum[2] = 2; Sum[3] = 5; Sum[4] = 10; Sum[5] = 23; for i in range(6,n+1): Sum[i] = ((Sum[i - 1] + (4 * Sum[i - 2]) % mod - (4 * Sum[i - 3]) % mod + mod) % mod + (Sum[i - 4] - Sum[i - 5] + mod) % mod) % mod; return Sum[n]; # Driver coden = 6;print(sumOddFibonacci(n)); # This code is contributed by mits // C# program to Find the sum of// first N odd Fibonacci numbers using System; public class GFG{ static int mod =1000000007;// Function to calculate sum of first// N odd Fibonacci numbersstatic int sumOddFibonacci(int n){ int []Sum=new int[n + 1]; // base values Sum[0] = 0; Sum[1] = 1; Sum[2] = 2; Sum[3] = 5; Sum[4] = 10; Sum[5] = 23; for (int i = 6; i <= n; i++) { Sum[i] = ((Sum[i - 1] + (4 * Sum[i - 2]) % mod - (4 * Sum[i - 3]) % mod + mod) % mod + (Sum[i - 4] - Sum[i - 5] + mod) % mod) % mod; } return Sum[n];} // Driver code static public void Main (){ int n = 6; Console.WriteLine(sumOddFibonacci(n)); }//This Code is Contributed by Sachin } <?php// PHP program to Find the sum of// first N odd Fibonacci numbers$mod = 1000000007 ; // Function to calculate sum of// first N odd Fibonacci numbersfunction sumOddFibonacci($n){ global $mod; $Sum[$n + 1] = array(); // base values $Sum[0] = 0; $Sum[1] = 1; $Sum[2] = 2; $Sum[3] = 5; $Sum[4] = 10; $Sum[5] = 23; for ($i = 6; $i <= $n; $i++) { $Sum[$i] = (($Sum[$i - 1] + (4 * $Sum[$i - 2]) % $mod - (4 * $Sum[$i - 3]) % $mod + $mod) % $mod + ($Sum[$i - 4] - $Sum[$i - 5] + $mod) % $mod) % $mod; } return $Sum[$n];} // Driver code$n = 6;echo sumOddFibonacci($n); // This code is contributed by jit_t?> <script>// javascript program to Find the sum of// first N odd Fibonacci numbers var mod = 1000000007; // Function to calculate sum of first // N odd Fibonacci numbers function sumOddFibonacci(n) { var Sum = Array(n + 1).fill(0); // base values Sum[0] = 0; Sum[1] = 1; Sum[2] = 2; Sum[3] = 5; Sum[4] = 10; Sum[5] = 23; for (i = 6; i <= n; i++) { Sum[i] = ((Sum[i - 1] + (4 * Sum[i - 2]) % mod - (4 * Sum[i - 3]) % mod + mod) % mod + (Sum[i - 4] - Sum[i - 5] + mod) % mod) % mod; } return Sum[n]; } // Driver code var n = 6; document.write(sumOddFibonacci(n)); // This code contributed by umadevi9616</script> 44 jit_t Sach_Code Mithun Kumar nidhi_biet Akanksha_Rai umadevi9616 manikarora059 Fibonacci Competitive Programming Dynamic Programming Mathematical Dynamic Programming Mathematical Fibonacci Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Multistage Graph (Shortest Path) Breadth First Traversal ( BFS ) on a 2D array Difference between Backtracking and Branch-N-Bound technique 5 Best Languages for Competitive Programming Most important type of Algorithms 0-1 Knapsack Problem | DP-10 Program for Fibonacci numbers Largest Sum Contiguous Subarray Longest Common Subsequence | DP-4 Bellman–Ford Algorithm | DP-23
[ { "code": null, "e": 26443, "s": 26415, "text": "\n23 Jul, 2021" }, { "code": null, "e": 26579, "s": 26443, "text": "Given a number, N. Find the sum of first N odd Fibonacci numbers.Note: The answer can be very large so print the answer modulo 10^9+7. " }, { "code": null, "e": 26591, "s": 26579, "text": "Examples: " }, { "code": null, "e": 26701, "s": 26591, "text": "Input : N = 3\nOutput : 5\nExplanation : 1 + 1 + 3\n\nInput : 6\nOutput : 44\nExplanation : 1 + 1 + 3 + 5 + 13 + 21" }, { "code": null, "e": 26738, "s": 26701, "text": "Approach :Odd Fibonacci series is: " }, { "code": null, "e": 26771, "s": 26738, "text": "1, 1, 3, 5, 13, 21, 55, 89......" }, { "code": null, "e": 26812, "s": 26771, "text": "Prefix sum of odd Fibonacci series is: " }, { "code": null, "e": 26846, "s": 26812, "text": "1, 2, 5, 10, 23, 44, 99, 188....." }, { "code": null, "e": 26909, "s": 26846, "text": "The formula for the sum of first N odd Fibonacci numbers is: " }, { "code": null, "e": 26973, "s": 26909, "text": "a(n) = a(n-1) + 4*a(n-2) – 4*a(n-3) + a(n-4) – a(n-5) for n>5 " }, { "code": null, "e": 27025, "s": 26973, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 27029, "s": 27025, "text": "C++" }, { "code": null, "e": 27034, "s": 27029, "text": "Java" }, { "code": null, "e": 27042, "s": 27034, "text": "Python3" }, { "code": null, "e": 27045, "s": 27042, "text": "C#" }, { "code": null, "e": 27049, "s": 27045, "text": "PHP" }, { "code": null, "e": 27060, "s": 27049, "text": "Javascript" }, { "code": "// CPP program to Find the sum of// first N odd Fibonacci numbers#include <bits/stdc++.h>using namespace std; #define mod 1000000007 // Function to calculate sum of first// N odd Fibonacci numberslong long sumOddFibonacci(int n){ long long Sum[n + 1]; // base values Sum[0] = 0; Sum[1] = 1; Sum[2] = 2; Sum[3] = 5; Sum[4] = 10; Sum[5] = 23; for (int i = 6; i <= n; i++) { Sum[i] = ((Sum[i - 1] + (4 * Sum[i - 2]) % mod - (4 * Sum[i - 3]) % mod + mod) % mod + (Sum[i - 4] - Sum[i - 5] + mod) % mod) % mod; } return Sum[n];} // Driver codeint main(){ long long n = 6; cout << sumOddFibonacci(n); return 0;}", "e": 27753, "s": 27060, "text": null }, { "code": "// Java program to Find the sum of// first N odd Fibonacci numbers import java.io.*; class GFG { static int mod =1000000007; // Function to calculate sum of first// N odd Fibonacci numbersstatic int sumOddFibonacci(int n){ int Sum[]=new int[n + 1]; // base values Sum[0] = 0; Sum[1] = 1; Sum[2] = 2; Sum[3] = 5; Sum[4] = 10; Sum[5] = 23; for (int i = 6; i <= n; i++) { Sum[i] = ((Sum[i - 1] + (4 * Sum[i - 2]) % mod - (4 * Sum[i - 3]) % mod + mod) % mod + (Sum[i - 4] - Sum[i - 5] + mod) % mod) % mod; } return Sum[n];} // Driver code public static void main (String[] args) { int n = 6; System.out.println(sumOddFibonacci(n)); }//This Code is Contributed by Sachin }", "e": 28520, "s": 27753, "text": null }, { "code": "# Python3 program to Find the sum of# first N odd Fibonacci numbersmod = 1000000007 ; # Function to calculate sum of# first N odd Fibonacci numbersdef sumOddFibonacci(n): Sum=[0]*(n + 1); # base values Sum[0] = 0; Sum[1] = 1; Sum[2] = 2; Sum[3] = 5; Sum[4] = 10; Sum[5] = 23; for i in range(6,n+1): Sum[i] = ((Sum[i - 1] + (4 * Sum[i - 2]) % mod - (4 * Sum[i - 3]) % mod + mod) % mod + (Sum[i - 4] - Sum[i - 5] + mod) % mod) % mod; return Sum[n]; # Driver coden = 6;print(sumOddFibonacci(n)); # This code is contributed by mits", "e": 29165, "s": 28520, "text": null }, { "code": "// C# program to Find the sum of// first N odd Fibonacci numbers using System; public class GFG{ static int mod =1000000007;// Function to calculate sum of first// N odd Fibonacci numbersstatic int sumOddFibonacci(int n){ int []Sum=new int[n + 1]; // base values Sum[0] = 0; Sum[1] = 1; Sum[2] = 2; Sum[3] = 5; Sum[4] = 10; Sum[5] = 23; for (int i = 6; i <= n; i++) { Sum[i] = ((Sum[i - 1] + (4 * Sum[i - 2]) % mod - (4 * Sum[i - 3]) % mod + mod) % mod + (Sum[i - 4] - Sum[i - 5] + mod) % mod) % mod; } return Sum[n];} // Driver code static public void Main (){ int n = 6; Console.WriteLine(sumOddFibonacci(n)); }//This Code is Contributed by Sachin }", "e": 29925, "s": 29165, "text": null }, { "code": "<?php// PHP program to Find the sum of// first N odd Fibonacci numbers$mod = 1000000007 ; // Function to calculate sum of// first N odd Fibonacci numbersfunction sumOddFibonacci($n){ global $mod; $Sum[$n + 1] = array(); // base values $Sum[0] = 0; $Sum[1] = 1; $Sum[2] = 2; $Sum[3] = 5; $Sum[4] = 10; $Sum[5] = 23; for ($i = 6; $i <= $n; $i++) { $Sum[$i] = (($Sum[$i - 1] + (4 * $Sum[$i - 2]) % $mod - (4 * $Sum[$i - 3]) % $mod + $mod) % $mod + ($Sum[$i - 4] - $Sum[$i - 5] + $mod) % $mod) % $mod; } return $Sum[$n];} // Driver code$n = 6;echo sumOddFibonacci($n); // This code is contributed by jit_t?>", "e": 30654, "s": 29925, "text": null }, { "code": "<script>// javascript program to Find the sum of// first N odd Fibonacci numbers var mod = 1000000007; // Function to calculate sum of first // N odd Fibonacci numbers function sumOddFibonacci(n) { var Sum = Array(n + 1).fill(0); // base values Sum[0] = 0; Sum[1] = 1; Sum[2] = 2; Sum[3] = 5; Sum[4] = 10; Sum[5] = 23; for (i = 6; i <= n; i++) { Sum[i] = ((Sum[i - 1] + (4 * Sum[i - 2]) % mod - (4 * Sum[i - 3]) % mod + mod) % mod + (Sum[i - 4] - Sum[i - 5] + mod) % mod) % mod; } return Sum[n]; } // Driver code var n = 6; document.write(sumOddFibonacci(n)); // This code contributed by umadevi9616</script>", "e": 31416, "s": 30654, "text": null }, { "code": null, "e": 31419, "s": 31416, "text": "44" }, { "code": null, "e": 31427, "s": 31421, "text": "jit_t" }, { "code": null, "e": 31437, "s": 31427, "text": "Sach_Code" }, { "code": null, "e": 31450, "s": 31437, "text": "Mithun Kumar" }, { "code": null, "e": 31461, "s": 31450, "text": "nidhi_biet" }, { "code": null, "e": 31474, "s": 31461, "text": "Akanksha_Rai" }, { "code": null, "e": 31486, "s": 31474, "text": "umadevi9616" }, { "code": null, "e": 31500, "s": 31486, "text": "manikarora059" }, { "code": null, "e": 31510, "s": 31500, "text": "Fibonacci" }, { "code": null, "e": 31534, "s": 31510, "text": "Competitive Programming" }, { "code": null, "e": 31554, "s": 31534, "text": "Dynamic Programming" }, { "code": null, "e": 31567, "s": 31554, "text": "Mathematical" }, { "code": null, "e": 31587, "s": 31567, "text": "Dynamic Programming" }, { "code": null, "e": 31600, "s": 31587, "text": "Mathematical" }, { "code": null, "e": 31610, "s": 31600, "text": "Fibonacci" }, { "code": null, "e": 31708, "s": 31610, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 31741, "s": 31708, "text": "Multistage Graph (Shortest Path)" }, { "code": null, "e": 31787, "s": 31741, "text": "Breadth First Traversal ( BFS ) on a 2D array" }, { "code": null, "e": 31848, "s": 31787, "text": "Difference between Backtracking and Branch-N-Bound technique" }, { "code": null, "e": 31893, "s": 31848, "text": "5 Best Languages for Competitive Programming" }, { "code": null, "e": 31927, "s": 31893, "text": "Most important type of Algorithms" }, { "code": null, "e": 31956, "s": 31927, "text": "0-1 Knapsack Problem | DP-10" }, { "code": null, "e": 31986, "s": 31956, "text": "Program for Fibonacci numbers" }, { "code": null, "e": 32018, "s": 31986, "text": "Largest Sum Contiguous Subarray" }, { "code": null, "e": 32052, "s": 32018, "text": "Longest Common Subsequence | DP-4" } ]
Dagger 2 Android Example using Retrofit - GeeksforGeeks
21 Dec, 2020 Dagger 2 Android implementation is easier and it is based on Dependency Injection Architecture. Dependency Injection is a design pattern, which is a concept of Object-Oriented Programming, where we don’t create an object of another class inside a class using the new keyword (for Java). Instead, we supply the needed object from the outside. It is a fully static, compile-time dependency injection framework for both Java and Android. It is an adaptation of an earlier version created by Square and now maintained by Google. Note that we are going to implement this project using the Java language. Dependency Provider: Dependencies are the objects that we need to instantiate inside a class. We cannot instantiate a class inside a class. The person who will provide us the objects that are called dependencies is called Dependency Provider. dagger2 is the class that you want to make a Dependency Provider, It needs to annotate it with the @Module annotation. Dependency Consumer: Dependency consumer is a class where we need to instantiate the objects. Dagger will provide the dependency, and for this, we just need to annotate the object declaration with @Inject. Component: The connection between our dependency provider and dependency consumer is provided via an interface by annotating it with @Component. And the rest of the thing will be done by Dagger. 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: Before going to the coding section first you have to do some pre-task Before going to the coding section first you have to do some pre-task. Go to the app > res > values > colors.xml section and set the colors for your app. XML <?xml version="1.0" encoding="utf-8"?><resources> <color name="colorPrimary">#0F9D58</color> <color name="colorPrimaryDark">#0F9D58</color> <color name="colorAccent">#FF4081</color></resources> Go to the Gradle Scripts > build.gradle (Module: app) section and import the following dependencies and click the “Sync Now” on the above pop up. // these two lines are added for retrofit implementation ‘com.squareup.retrofit2:retrofit:2.7.2’ implementation ‘com.squareup.retrofit2:converter-gson:2.7.2’ // these two lines are added for dagger implementation ‘com.google.dagger:dagger:2.13’ annotationProcessor ‘com.google.dagger:dagger-compiler:2.13’ Go to the app > manifests > AndroidManifests.xml section and allow “Internet Permission“. Below is the code for the AndroidManifests.xml file. <!– the internet permission , then only api calls can be retrieved –> <uses-permission android:name=”android.permission.INTERNET” /> Step 3: Designing the UI Below is the code for the activity_main.xml file. This will be under the app > src > main > res > layout folder. Depends upon different resolutions, sometimes we may need to have it under layout > hdpi or layout > xhdpi folders, etc. XML <?xml version="1.0" encoding="utf-8"?><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity"> <ListView android:id="@+id/listViewCountries" android:layout_width="match_parent" android:layout_height="match_parent" android:background="@color/colorPrimaryDark"/> </RelativeLayout> Step 4: Working with the Java file App Module.java file: In Retrofit(Retrofit is a REST Client for Java and Android), we need the context object. To supply the objects, so here we will create this module that will give us the Context. Java import android.app.Application;import javax.inject.Singleton;import dagger.Module;import dagger.Provides; @Moduleclass AppModule { private Application mApplication; AppModule(Application mApplication) { this.mApplication = mApplication; } @Provides @Singleton Application provideApplication() { return mApplication; }} With the dagger, we need to annotate @Singleton when we want a single instance only. API Module.java: For Retrofit, we need a bunch of things. Cache, Gson, OkHttpClient, and the Retrofit itself. So we will define the providers for these objects here in this module. Gson: It is a Java library that can be used to convert Java Objects into their JSON representation. Okhttp: works with Retrofit, which is a brilliant API for REST. Java import android.app.Application;import com.google.gson.FieldNamingPolicy;import com.google.gson.Gson;import com.google.gson.GsonBuilder;import javax.inject.Singleton;import dagger.Module;import dagger.Provides;import okhttp3.Cache;import okhttp3.OkHttpClient;import retrofit2.Retrofit;import retrofit2.converter.gson.GsonConverterFactory; @Moduleclass ApiModule { String mBaseUrl; ApiModule(String mBaseUrl) { this.mBaseUrl = mBaseUrl; } @Provides @Singleton Cache provideHttpCache(Application application) { int cacheSize = 10 * 1024 * 1024; Cache cache = new Cache(application.getCacheDir(), cacheSize); return cache; } @Provides @Singleton Gson provideGson() { GsonBuilder gsonBuilder = new GsonBuilder(); gsonBuilder.setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES); return gsonBuilder.create(); } @Provides @Singleton OkHttpClient provideOkhttpClient(Cache cache) { OkHttpClient.Builder client = new OkHttpClient.Builder(); client.cache(cache); return client.build(); } @Provides @Singleton Retrofit provideRetrofit(Gson gson, OkHttpClient okHttpClient) { return new Retrofit.Builder() .addConverterFactory(GsonConverterFactory.create(gson)) .baseUrl(mBaseUrl) .client(okHttpClient) .build(); }} Building Component: ApiComponent.java Java import javax.inject.Singleton;import dagger.Component; @Singleton@Component(modules = {AppModule.class, ApiModule.class})public interface ApiComponent { void inject(MainActivity activity);} We will inject in the MainActivity. We also define all the modules using the @Component annotation as we can see in the code. MyApplication.java file: Java import android.app.Application; public class MyApplication extends Application { private ApiComponent mApiComponent; @Override public void onCreate() { super.onCreate(); // https://restcountries.eu/rest/v2/all -> It will list all the country details mApiComponent = DaggerApiComponent.builder() .appModule(new AppModule(this)) .apiModule(new ApiModule("https://restcountries.eu/rest/v2/")) .build(); } public ApiComponent getNetComponent() { return mApiComponent; }} MainActivity.java file: Java import android.os.Bundle;import android.widget.ArrayAdapter;import android.widget.ListView;import android.widget.Toast;import androidx.appcompat.app.AppCompatActivity;import java.util.List;import javax.inject.Inject;import retrofit2.Call;import retrofit2.Callback;import retrofit2.Response;import retrofit2.Retrofit; public class MainActivity extends AppCompatActivity { // injecting retrofit @Inject Retrofit retrofit; ListView listView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // injecting here ((MyApplication) getApplication()).getNetComponent().inject(this); listView = (ListView) findViewById(R.id.listViewCountries); getCountries(); } private void getCountries() { Api api = retrofit.create(Api.class); // Call<List<Country>> call = RetrofitClient.getInstance().getMyApi().getCountries(); Call<List<Country>> call = api.getCountries(); call.enqueue(new Callback<List<Country>>() { @Override public void onResponse(Call<List<Country>> call, Response<List<Country>> response) { List<Country> countryList = response.body(); // Creating an String array for the ListView String[] countries = new String[countryList.size()]; // looping through all the countries and inserting // the names inside the string array for (int i = 0; i < countryList.size(); i++) { countries[i] = countryList.get(i).getName(); } // displaying the string array into listview listView.setAdapter(new ArrayAdapter<String>(getApplicationContext(), android.R.layout.simple_list_item_1, countries)); } @Override public void onFailure(Call<List<Country>> call, Throwable t) { Toast.makeText(getApplicationContext(), t.getMessage(), Toast.LENGTH_SHORT).show(); } }); }} Example Request: https://restcountries.eu/rest/v2/all will provide the output as shown in the image. We will take the country name from that Example Response: The output of the above REST API URL As we are taking country names only we will get as a list like Afghanistan,.....India etc., On executing the above code, we can able to get the output as shown below. You can find the source code: https://github.com/raj123raj/dagger-retrofit android Android Java Java Android Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Retrofit with Kotlin Coroutine in Android Android Listview in Java with Example How to Read Data from SQLite Database in Android? Flutter - Custom Bottom Navigation Bar How to Change the Background Color After Clicking the Button in Android? Arrays in Java Split() String method in Java with examples For-each loop in Java Arrays.sort() in Java with examples Initialize an ArrayList in Java
[ { "code": null, "e": 25036, "s": 25008, "text": "\n21 Dec, 2020" }, { "code": null, "e": 25636, "s": 25036, "text": "Dagger 2 Android implementation is easier and it is based on Dependency Injection Architecture. Dependency Injection is a design pattern, which is a concept of Object-Oriented Programming, where we don’t create an object of another class inside a class using the new keyword (for Java). Instead, we supply the needed object from the outside. It is a fully static, compile-time dependency injection framework for both Java and Android. It is an adaptation of an earlier version created by Square and now maintained by Google. Note that we are going to implement this project using the Java language. " }, { "code": null, "e": 25998, "s": 25636, "text": "Dependency Provider: Dependencies are the objects that we need to instantiate inside a class. We cannot instantiate a class inside a class. The person who will provide us the objects that are called dependencies is called Dependency Provider. dagger2 is the class that you want to make a Dependency Provider, It needs to annotate it with the @Module annotation." }, { "code": null, "e": 26204, "s": 25998, "text": "Dependency Consumer: Dependency consumer is a class where we need to instantiate the objects. Dagger will provide the dependency, and for this, we just need to annotate the object declaration with @Inject." }, { "code": null, "e": 26399, "s": 26204, "text": "Component: The connection between our dependency provider and dependency consumer is provided via an interface by annotating it with @Component. And the rest of the thing will be done by Dagger." }, { "code": null, "e": 26428, "s": 26399, "text": "Step 1: Create a New Project" }, { "code": null, "e": 26590, "s": 26428, "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": 26668, "s": 26590, "text": "Step 2: Before going to the coding section first you have to do some pre-task" }, { "code": null, "e": 26822, "s": 26668, "text": "Before going to the coding section first you have to do some pre-task. Go to the app > res > values > colors.xml section and set the colors for your app." }, { "code": null, "e": 26826, "s": 26822, "text": "XML" }, { "code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><resources> <color name=\"colorPrimary\">#0F9D58</color> <color name=\"colorPrimaryDark\">#0F9D58</color> <color name=\"colorAccent\">#FF4081</color></resources>", "e": 27029, "s": 26826, "text": null }, { "code": null, "e": 27175, "s": 27029, "text": "Go to the Gradle Scripts > build.gradle (Module: app) section and import the following dependencies and click the “Sync Now” on the above pop up." }, { "code": null, "e": 27217, "s": 27175, "text": "// these two lines are added for retrofit" }, { "code": null, "e": 27272, "s": 27217, "text": "implementation ‘com.squareup.retrofit2:retrofit:2.7.2’" }, { "code": null, "e": 27333, "s": 27272, "text": "implementation ‘com.squareup.retrofit2:converter-gson:2.7.2’" }, { "code": null, "e": 27373, "s": 27333, "text": "// these two lines are added for dagger" }, { "code": null, "e": 27420, "s": 27373, "text": "implementation ‘com.google.dagger:dagger:2.13’" }, { "code": null, "e": 27481, "s": 27420, "text": "annotationProcessor ‘com.google.dagger:dagger-compiler:2.13’" }, { "code": null, "e": 27624, "s": 27481, "text": "Go to the app > manifests > AndroidManifests.xml section and allow “Internet Permission“. Below is the code for the AndroidManifests.xml file." }, { "code": null, "e": 27694, "s": 27624, "text": "<!– the internet permission , then only api calls can be retrieved –>" }, { "code": null, "e": 27757, "s": 27694, "text": "<uses-permission android:name=”android.permission.INTERNET” />" }, { "code": null, "e": 27782, "s": 27757, "text": "Step 3: Designing the UI" }, { "code": null, "e": 28016, "s": 27782, "text": "Below is the code for the activity_main.xml file. This will be under the app > src > main > res > layout folder. Depends upon different resolutions, sometimes we may need to have it under layout > hdpi or layout > xhdpi folders, etc." }, { "code": null, "e": 28020, "s": 28016, "text": "XML" }, { "code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><RelativeLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:app=\"http://schemas.android.com/apk/res-auto\" xmlns:tools=\"http://schemas.android.com/tools\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" tools:context=\".MainActivity\"> <ListView android:id=\"@+id/listViewCountries\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" android:background=\"@color/colorPrimaryDark\"/> </RelativeLayout>", "e": 28573, "s": 28020, "text": null }, { "code": null, "e": 28608, "s": 28573, "text": "Step 4: Working with the Java file" }, { "code": null, "e": 28630, "s": 28608, "text": "App Module.java file:" }, { "code": null, "e": 28808, "s": 28630, "text": "In Retrofit(Retrofit is a REST Client for Java and Android), we need the context object. To supply the objects, so here we will create this module that will give us the Context." }, { "code": null, "e": 28813, "s": 28808, "text": "Java" }, { "code": "import android.app.Application;import javax.inject.Singleton;import dagger.Module;import dagger.Provides; @Moduleclass AppModule { private Application mApplication; AppModule(Application mApplication) { this.mApplication = mApplication; } @Provides @Singleton Application provideApplication() { return mApplication; }}", "e": 29172, "s": 28813, "text": null }, { "code": null, "e": 29257, "s": 29172, "text": "With the dagger, we need to annotate @Singleton when we want a single instance only." }, { "code": null, "e": 29274, "s": 29257, "text": "API Module.java:" }, { "code": null, "e": 29438, "s": 29274, "text": "For Retrofit, we need a bunch of things. Cache, Gson, OkHttpClient, and the Retrofit itself. So we will define the providers for these objects here in this module." }, { "code": null, "e": 29538, "s": 29438, "text": "Gson: It is a Java library that can be used to convert Java Objects into their JSON representation." }, { "code": null, "e": 29602, "s": 29538, "text": "Okhttp: works with Retrofit, which is a brilliant API for REST." }, { "code": null, "e": 29607, "s": 29602, "text": "Java" }, { "code": "import android.app.Application;import com.google.gson.FieldNamingPolicy;import com.google.gson.Gson;import com.google.gson.GsonBuilder;import javax.inject.Singleton;import dagger.Module;import dagger.Provides;import okhttp3.Cache;import okhttp3.OkHttpClient;import retrofit2.Retrofit;import retrofit2.converter.gson.GsonConverterFactory; @Moduleclass ApiModule { String mBaseUrl; ApiModule(String mBaseUrl) { this.mBaseUrl = mBaseUrl; } @Provides @Singleton Cache provideHttpCache(Application application) { int cacheSize = 10 * 1024 * 1024; Cache cache = new Cache(application.getCacheDir(), cacheSize); return cache; } @Provides @Singleton Gson provideGson() { GsonBuilder gsonBuilder = new GsonBuilder(); gsonBuilder.setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES); return gsonBuilder.create(); } @Provides @Singleton OkHttpClient provideOkhttpClient(Cache cache) { OkHttpClient.Builder client = new OkHttpClient.Builder(); client.cache(cache); return client.build(); } @Provides @Singleton Retrofit provideRetrofit(Gson gson, OkHttpClient okHttpClient) { return new Retrofit.Builder() .addConverterFactory(GsonConverterFactory.create(gson)) .baseUrl(mBaseUrl) .client(okHttpClient) .build(); }}", "e": 31035, "s": 29607, "text": null }, { "code": null, "e": 31073, "s": 31035, "text": "Building Component: ApiComponent.java" }, { "code": null, "e": 31078, "s": 31073, "text": "Java" }, { "code": "import javax.inject.Singleton;import dagger.Component; @Singleton@Component(modules = {AppModule.class, ApiModule.class})public interface ApiComponent { void inject(MainActivity activity);}", "e": 31272, "s": 31078, "text": null }, { "code": null, "e": 31398, "s": 31272, "text": "We will inject in the MainActivity. We also define all the modules using the @Component annotation as we can see in the code." }, { "code": null, "e": 31423, "s": 31398, "text": "MyApplication.java file:" }, { "code": null, "e": 31428, "s": 31423, "text": "Java" }, { "code": "import android.app.Application; public class MyApplication extends Application { private ApiComponent mApiComponent; @Override public void onCreate() { super.onCreate(); // https://restcountries.eu/rest/v2/all -> It will list all the country details mApiComponent = DaggerApiComponent.builder() .appModule(new AppModule(this)) .apiModule(new ApiModule(\"https://restcountries.eu/rest/v2/\")) .build(); } public ApiComponent getNetComponent() { return mApiComponent; }}", "e": 31993, "s": 31428, "text": null }, { "code": null, "e": 32017, "s": 31993, "text": "MainActivity.java file:" }, { "code": null, "e": 32022, "s": 32017, "text": "Java" }, { "code": "import android.os.Bundle;import android.widget.ArrayAdapter;import android.widget.ListView;import android.widget.Toast;import androidx.appcompat.app.AppCompatActivity;import java.util.List;import javax.inject.Inject;import retrofit2.Call;import retrofit2.Callback;import retrofit2.Response;import retrofit2.Retrofit; public class MainActivity extends AppCompatActivity { // injecting retrofit @Inject Retrofit retrofit; ListView listView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // injecting here ((MyApplication) getApplication()).getNetComponent().inject(this); listView = (ListView) findViewById(R.id.listViewCountries); getCountries(); } private void getCountries() { Api api = retrofit.create(Api.class); // Call<List<Country>> call = RetrofitClient.getInstance().getMyApi().getCountries(); Call<List<Country>> call = api.getCountries(); call.enqueue(new Callback<List<Country>>() { @Override public void onResponse(Call<List<Country>> call, Response<List<Country>> response) { List<Country> countryList = response.body(); // Creating an String array for the ListView String[] countries = new String[countryList.size()]; // looping through all the countries and inserting // the names inside the string array for (int i = 0; i < countryList.size(); i++) { countries[i] = countryList.get(i).getName(); } // displaying the string array into listview listView.setAdapter(new ArrayAdapter<String>(getApplicationContext(), android.R.layout.simple_list_item_1, countries)); } @Override public void onFailure(Call<List<Country>> call, Throwable t) { Toast.makeText(getApplicationContext(), t.getMessage(), Toast.LENGTH_SHORT).show(); } }); }}", "e": 34140, "s": 32022, "text": null }, { "code": null, "e": 34157, "s": 34140, "text": "Example Request:" }, { "code": null, "e": 34281, "s": 34157, "text": "https://restcountries.eu/rest/v2/all will provide the output as shown in the image. We will take the country name from that" }, { "code": null, "e": 34299, "s": 34281, "text": "Example Response:" }, { "code": null, "e": 34336, "s": 34299, "text": "The output of the above REST API URL" }, { "code": null, "e": 34503, "s": 34336, "text": "As we are taking country names only we will get as a list like Afghanistan,.....India etc., On executing the above code, we can able to get the output as shown below." }, { "code": null, "e": 34578, "s": 34503, "text": "You can find the source code: https://github.com/raj123raj/dagger-retrofit" }, { "code": null, "e": 34586, "s": 34578, "text": "android" }, { "code": null, "e": 34594, "s": 34586, "text": "Android" }, { "code": null, "e": 34599, "s": 34594, "text": "Java" }, { "code": null, "e": 34604, "s": 34599, "text": "Java" }, { "code": null, "e": 34612, "s": 34604, "text": "Android" }, { "code": null, "e": 34710, "s": 34612, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 34719, "s": 34710, "text": "Comments" }, { "code": null, "e": 34732, "s": 34719, "text": "Old Comments" }, { "code": null, "e": 34774, "s": 34732, "text": "Retrofit with Kotlin Coroutine in Android" }, { "code": null, "e": 34812, "s": 34774, "text": "Android Listview in Java with Example" }, { "code": null, "e": 34862, "s": 34812, "text": "How to Read Data from SQLite Database in Android?" }, { "code": null, "e": 34901, "s": 34862, "text": "Flutter - Custom Bottom Navigation Bar" }, { "code": null, "e": 34974, "s": 34901, "text": "How to Change the Background Color After Clicking the Button in Android?" }, { "code": null, "e": 34989, "s": 34974, "text": "Arrays in Java" }, { "code": null, "e": 35033, "s": 34989, "text": "Split() String method in Java with examples" }, { "code": null, "e": 35055, "s": 35033, "text": "For-each loop in Java" }, { "code": null, "e": 35091, "s": 35055, "text": "Arrays.sort() in Java with examples" } ]
Number with even sum of digits - GeeksforGeeks
06 Apr, 2021 A positive integer is considered a good number if sum of its digits is even. Find n-th smallest good number. Examples : Input : n = 1 Output : 2 First good number is smallest positive number with sum of digits even which is 2. Input : n = 10 Output : 20 A simple solution is to start from 1 and traverse through all natural numbers. For every number x, check if sum of digits is even. If even increment count of good numbers. Finally return the n-th Good number.An efficient solution is based on a pattern in the answer. Let us list down first 20 good numbers. The first 20 good numbers are: 2, 4, 6, 8, 11, 13, 15, 17, 19, 20, 22, 24, 26, 28, 31, 33, 35, 37, 39, 40. Observe that if last digit of n is from 0 to 4 the answer is 2*n and if last digit of n is from 5 to 9 the answer is 2*n + 1. C++ Java Python 3 C# PHP Javascript // C++ program to find n-th// Good number.#include <bits/stdc++.h>using namespace std; // Function to find kth good number.long long int findKthGoodNo(long long int n){ // Find the last digit of n. int lastDig = n % 10; // If last digit is between // 0 to 4 then return 2 * n. if (lastDig >= 0 && lastDig <= 4) return n << 1; // If last digit is between // 5 to 9 then return 2*n + 1. else return (n << 1) + 1;} // Driver codeint main(){ long long int n = 10; cout << findKthGoodNo(n); return 0;} // Java program to find n-th// Good number.class GFG{ // Function to find kth good number. static int findKthGoodNo(int n) { // Find the last digit of n. int lastDig = n % 10; // If last digit is between // 0 to 4 then return 2*n. if (lastDig >= 0 && lastDig <= 4) return n << 1; // If last digit is between // 5 to 9 then return 2*n + 1. else return (n << 1) + 1; } // Driver code public static void main(String[] args) { int n = 10; System.out.println(findKthGoodNo(n)); }} // This code is contributed by// Smitha Dinesh Semwal # Python 3 program to find# n-th Good number. # Function to find kth# good number.def findKthGoodNo(n): # Find the last digit of n. lastDig = n % 10 # If last digit is between # 0 to 4 then return 2 * n. if (lastDig >= 0 and lastDig <= 4) : return n << 1 # If last digit is between # 5 to 9 then return 2 * n + 1. else: return (n << 1) + 1 # Driver coden = 10print(findKthGoodNo(n)) # This code is contributed by# Smitha Dinesh Semwal // C# program to find n-th// Good number.using System; class GFG{ // Function to find kth // good number public static int findKthGoodNo(int n) { // Find the last digit of n. int lastDig = n % 10; // If last digit is between // 0 to 4 then return 2*n. if (lastDig >= 0 && lastDig <= 4) return n << 1; // If last digit is between // 5 to 9 then return 2*n + 1. else return (n << 1) + 1; } // Driver code static public void Main (string []args) { int n = 10; Console.WriteLine(findKthGoodNo(n)); }} // This code is contributed by Ajit. <?php// PHP program to find n-th// Good number. // Function to find kth// good number.function findKthGoodNo($n){ // Find the last digit of n. $lastDig = $n % 10; // If last digit is between // 0 to 4 then return 2*n. if ($lastDig >= 0 && $lastDig <= 4) return $n << 1; // If last digit is between // 5 to 9 then return 2*n + 1. else return ($n << 1) + 1;} // Driver code$n = 10;echo(findKthGoodNo($n)); // This code is contributed by Ajit.?> <script> // JavaScript program to find n-th// Good number. // Function to find kth good number. function findKthGoodNo(n) { // Find the last digit of n. let lastDig = n % 10; // If last digit is between // 0 to 4 then return 2*n. if (lastDig >= 0 && lastDig <= 4) return n << 1; // If last digit is between // 5 to 9 then return 2*n + 1. else return (n << 1) + 1; } // Driver code let n = 10; document.write(findKthGoodNo(n)); // This code is contributed by souravghosh0416.</script> 20 Time Complexity: O(1) Auxiliary Space: O(1) Smitha Dinesh Semwal jit_t souravghosh0416 number-digits series Mathematical Mathematical series Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Program to print prime numbers from 1 to N. Modular multiplicative inverse Fizz Buzz Implementation Generate all permutation of a set in Python How to check if a given point lies inside or outside a polygon? Check if a number is Palindrome Segment Tree | Set 1 (Sum of given range) Merge two sorted arrays with O(1) extra space Program to multiply two matrices Singular Value Decomposition (SVD)
[ { "code": null, "e": 26047, "s": 26019, "text": "\n06 Apr, 2021" }, { "code": null, "e": 26169, "s": 26047, "text": "A positive integer is considered a good number if sum of its digits is even. Find n-th smallest good number. Examples : " }, { "code": null, "e": 26305, "s": 26169, "text": "Input : n = 1\nOutput : 2\nFirst good number is smallest positive\nnumber with sum of digits even which is 2.\n\nInput : n = 10\nOutput : 20" }, { "code": null, "e": 26849, "s": 26307, "text": "A simple solution is to start from 1 and traverse through all natural numbers. For every number x, check if sum of digits is even. If even increment count of good numbers. Finally return the n-th Good number.An efficient solution is based on a pattern in the answer. Let us list down first 20 good numbers. The first 20 good numbers are: 2, 4, 6, 8, 11, 13, 15, 17, 19, 20, 22, 24, 26, 28, 31, 33, 35, 37, 39, 40. Observe that if last digit of n is from 0 to 4 the answer is 2*n and if last digit of n is from 5 to 9 the answer is 2*n + 1. " }, { "code": null, "e": 26853, "s": 26849, "text": "C++" }, { "code": null, "e": 26858, "s": 26853, "text": "Java" }, { "code": null, "e": 26867, "s": 26858, "text": "Python 3" }, { "code": null, "e": 26870, "s": 26867, "text": "C#" }, { "code": null, "e": 26874, "s": 26870, "text": "PHP" }, { "code": null, "e": 26885, "s": 26874, "text": "Javascript" }, { "code": "// C++ program to find n-th// Good number.#include <bits/stdc++.h>using namespace std; // Function to find kth good number.long long int findKthGoodNo(long long int n){ // Find the last digit of n. int lastDig = n % 10; // If last digit is between // 0 to 4 then return 2 * n. if (lastDig >= 0 && lastDig <= 4) return n << 1; // If last digit is between // 5 to 9 then return 2*n + 1. else return (n << 1) + 1;} // Driver codeint main(){ long long int n = 10; cout << findKthGoodNo(n); return 0;}", "e": 27431, "s": 26885, "text": null }, { "code": "// Java program to find n-th// Good number.class GFG{ // Function to find kth good number. static int findKthGoodNo(int n) { // Find the last digit of n. int lastDig = n % 10; // If last digit is between // 0 to 4 then return 2*n. if (lastDig >= 0 && lastDig <= 4) return n << 1; // If last digit is between // 5 to 9 then return 2*n + 1. else return (n << 1) + 1; } // Driver code public static void main(String[] args) { int n = 10; System.out.println(findKthGoodNo(n)); }} // This code is contributed by// Smitha Dinesh Semwal", "e": 28103, "s": 27431, "text": null }, { "code": "# Python 3 program to find# n-th Good number. # Function to find kth# good number.def findKthGoodNo(n): # Find the last digit of n. lastDig = n % 10 # If last digit is between # 0 to 4 then return 2 * n. if (lastDig >= 0 and lastDig <= 4) : return n << 1 # If last digit is between # 5 to 9 then return 2 * n + 1. else: return (n << 1) + 1 # Driver coden = 10print(findKthGoodNo(n)) # This code is contributed by# Smitha Dinesh Semwal", "e": 28580, "s": 28103, "text": null }, { "code": "// C# program to find n-th// Good number.using System; class GFG{ // Function to find kth // good number public static int findKthGoodNo(int n) { // Find the last digit of n. int lastDig = n % 10; // If last digit is between // 0 to 4 then return 2*n. if (lastDig >= 0 && lastDig <= 4) return n << 1; // If last digit is between // 5 to 9 then return 2*n + 1. else return (n << 1) + 1; } // Driver code static public void Main (string []args) { int n = 10; Console.WriteLine(findKthGoodNo(n)); }} // This code is contributed by Ajit.", "e": 29254, "s": 28580, "text": null }, { "code": "<?php// PHP program to find n-th// Good number. // Function to find kth// good number.function findKthGoodNo($n){ // Find the last digit of n. $lastDig = $n % 10; // If last digit is between // 0 to 4 then return 2*n. if ($lastDig >= 0 && $lastDig <= 4) return $n << 1; // If last digit is between // 5 to 9 then return 2*n + 1. else return ($n << 1) + 1;} // Driver code$n = 10;echo(findKthGoodNo($n)); // This code is contributed by Ajit.?>", "e": 29737, "s": 29254, "text": null }, { "code": "<script> // JavaScript program to find n-th// Good number. // Function to find kth good number. function findKthGoodNo(n) { // Find the last digit of n. let lastDig = n % 10; // If last digit is between // 0 to 4 then return 2*n. if (lastDig >= 0 && lastDig <= 4) return n << 1; // If last digit is between // 5 to 9 then return 2*n + 1. else return (n << 1) + 1; } // Driver code let n = 10; document.write(findKthGoodNo(n)); // This code is contributed by souravghosh0416.</script>", "e": 30343, "s": 29737, "text": null }, { "code": null, "e": 30346, "s": 30343, "text": "20" }, { "code": null, "e": 30393, "s": 30348, "text": "Time Complexity: O(1) Auxiliary Space: O(1) " }, { "code": null, "e": 30414, "s": 30393, "text": "Smitha Dinesh Semwal" }, { "code": null, "e": 30420, "s": 30414, "text": "jit_t" }, { "code": null, "e": 30436, "s": 30420, "text": "souravghosh0416" }, { "code": null, "e": 30450, "s": 30436, "text": "number-digits" }, { "code": null, "e": 30457, "s": 30450, "text": "series" }, { "code": null, "e": 30470, "s": 30457, "text": "Mathematical" }, { "code": null, "e": 30483, "s": 30470, "text": "Mathematical" }, { "code": null, "e": 30490, "s": 30483, "text": "series" }, { "code": null, "e": 30588, "s": 30490, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30632, "s": 30588, "text": "Program to print prime numbers from 1 to N." }, { "code": null, "e": 30663, "s": 30632, "text": "Modular multiplicative inverse" }, { "code": null, "e": 30688, "s": 30663, "text": "Fizz Buzz Implementation" }, { "code": null, "e": 30732, "s": 30688, "text": "Generate all permutation of a set in Python" }, { "code": null, "e": 30796, "s": 30732, "text": "How to check if a given point lies inside or outside a polygon?" }, { "code": null, "e": 30828, "s": 30796, "text": "Check if a number is Palindrome" }, { "code": null, "e": 30870, "s": 30828, "text": "Segment Tree | Set 1 (Sum of given range)" }, { "code": null, "e": 30916, "s": 30870, "text": "Merge two sorted arrays with O(1) extra space" }, { "code": null, "e": 30949, "s": 30916, "text": "Program to multiply two matrices" } ]
5 Simple Ways to Tokenize Text in Python | by Frank Andrade | Towards Data Science
Tokenization is a common task a data scientist comes across when working with text data. It consists of splitting an entire text into small units, also known as tokens. Most Natural Language Processing (NLP) projects have tokenization as the first step because it’s the foundation for developing good models and helps better understand the text we have. Although tokenization in Python could be as simple as writing .split(), that method might not be the most efficient in some projects. That’s why, in this article, I’ll show 5 ways that will help you tokenize small texts, a large corpus or even text written in a language other than English. Table of Contents1. Simple tokenization with .split2. Tokenization with NLTK3. Convert a corpus to a vector of token counts with Count Vectorizer (sklearn)4. Tokenize text in different languages with spaCy5. Tokenization with Gensim Note: Tokenization is one of the many tasks a data scientist do when cleaning and preparing data. In the article below, I wrote a guide to help you with these tedious tasks. The code of both articles is available on my Github. towardsdatascience.com As we mentioned before, this is the simplest method to perform tokenization in Python. If you type .split(), the text will be separated at each blank space. For this and the following examples, we’ll be using a text narrated by Steve Jobs in the “Think Different” Apple commercial. text = “””Here’s to the crazy ones, the misfits, the rebels, the troublemakers, the round pegs in the square holes. The ones who see things differently — they’re not fond of rules. You can quote them, disagree with them, glorify or vilify them, but the only thing you can’t do is ignore them because they change things. They push the human race forward, and while some may see them as the crazy ones, we see genius, because the ones who are crazy enough to thinkthat they can change the world, are the ones who do.”””text.split() If we write the code above, we’ll obtain the following output. ['Here’s', 'to', 'the', 'crazy', 'ones,', 'the', 'misfits,', 'the', 'rebels,', 'the', 'troublemakers,', 'the', 'round', 'pegs', 'in', 'the', 'square', 'holes.', 'The', 'ones', 'who', 'see', 'things', 'differently', '—', 'they’re', 'not', 'fond', 'of', 'rules.', 'You', 'can', 'quote', 'them,', 'disagree', 'with', 'them,', 'glorify', 'or', 'vilify', 'them,', 'but', 'the', 'only', 'thing', 'you', 'can’t', 'do', 'is', 'ignore', 'them', 'because', 'they', 'change', 'things.', 'They', 'push', 'the', 'human', 'race', 'forward,', 'and', 'while', 'some', 'may', 'see', 'them', 'as', 'the', 'crazy', 'ones,', 'we', 'see', 'genius,', 'because', 'the', 'ones', 'who', 'are', 'crazy', 'enough', 'to', 'think', 'that', 'they', 'can', 'change', 'the', 'world,', 'are', 'the', 'ones', 'who', 'do.'] As you can see above, the split() method doesn’t consider punctuation symbols as a separate token. This might change your project results. medium.com NLTK stands for Natural Language Toolkit. This is a suite of libraries and programs for statistical natural language processing for English written in Python. NLTK contains a module called tokenize with a word_tokenize() method that will help us split a text into tokens. Once you installed NLTK, write the following code to tokenize text. from nltk.tokenize import word_tokenizeword_tokenize(text) In this case, the default output is slightly different from the .split method showed above. ['Here', '’', 's', 'to', 'the', 'crazy', 'ones', ',', 'the', 'misfits', ',', 'the', 'rebels', ',', 'the', 'troublemakers', ',', ...] In this case, the apostrophe (‘) in “here’s” and the comma (,) in “ones,” were considered as tokens. The previous methods become less useful when dealing with a large corpus because you’ll need to represent the tokens differently. Count Vectorizer will help us convert a collection of text documents to a vector of token counts. In the end, we’ll get a vector representation of the text data. For this example, I’ll add a quote from Bill Gates to the previous text to build a dataframe that will be an example of a corpus. import pandas as pdtexts = ["""Here’s to the crazy ones, the misfits, the rebels, the troublemakers, the round pegs in the square holes. The ones who see things differently — they’re not fond of rules. You can quote them, disagree with them, glorify or vilify them, but the only thing you can’t do is ignore them because they change things. They push the human race forward, and while some may see them as the crazy ones, we see genius, because the ones who are crazy enough to think that they can change the world, are the ones who do.""" , 'I choose a lazy person to do a hard job. Because a lazy person will find an easy way to do it.']df = pd.DataFrame({'author': ['jobs', 'gates'], 'text':texts}) Now we’ll use Count Vectorizer to transform these texts within the df dataframe in a vector of token counts. If you run that code, you’ll get a frame that counts the number of times a word was mention in both texts. This becomes extremely useful when the dataframe contains a large corpus because it provides a matrix with words encoded as integers values, which are used as inputs in machine learning algorithms. Count Vectorizer can have different parameters like stop_words that we defined above. However, keep in mind that the default regexp used by Count Vectorizer selects tokens of 2 or more alphanumeric characters (punctuation is completely ignored and always treated as a token separator) When you need to tokenize text written in a language other than English, you can use spaCy. This is a library for advanced natural language processing, written in Python and Cython, that supports tokenization for more than 65 languages. Let’s tokenize the same Steve Jobs text but now translated in Spanish. In this case, we imported Spanish from spacy.lang.es but if you’re working with text in English, just import English from spacy.lang.en Check the list of languages available here. If you run this code, you’ll get the following output. ['Por', 'los', 'locos', '.', 'Los', 'marginados', '.', 'Los', 'rebeldes', '.', 'Los', 'problematicos', '.', '\n', 'Los', 'inadaptados', '.', 'Los', 'que', 'ven', 'las', 'cosas', 'de', 'una', 'manera', 'distinta', '.', 'A', 'los', 'que', 'no', 'les', 'gustan', '\n', 'las', 'reglas', '.', 'Y', 'a', 'los', 'que', 'no', 'respetan', 'el', '“', 'status', 'quo', '”', '.', 'Puedes', 'citarlos', ',', 'discrepar', 'de', 'ellos', ',', '\n', 'ensalzarlos', 'o', 'vilipendiarlos', '.', 'Pero', 'lo', 'que', 'no', 'puedes', 'hacer', 'es', 'ignorarlos', '...', 'Porque', 'ellos', '\n', 'cambian', 'las', 'cosas', ',', 'empujan', 'hacia', 'adelante', 'la', 'raza', 'humana', 'y', ',', 'aunque', 'algunos', 'puedan', '\n', 'considerarlos', 'locos', ',', 'nosotros', 'vemos', 'en', 'ellos', 'a', 'genios', '.', 'Porque', 'las', 'personas', 'que', 'están', '\n', 'lo', 'bastante', 'locas', 'como', 'para', 'creer', 'que', 'pueden', 'cambiar', 'el', 'mundo', ',', 'son', 'las', 'que', 'lo', 'logran', '.'] As you can see spaCy, considers punctuation symbols as a separate token (even the new lines\n were included). If you know a bit about Spanish, you might’ve noticed that the tokenization is similar to English, so you might be wondering, “why do I need a tokenizer for each language?” Although for languages like Spanish and English, tokenization will be as simple as separating by whitespace, for non-romance languages such as Chinese and Japanese, the orthography might have no spaces to delimit “words” or “tokens.” In such cases, a library like spaCy will come in handy. Here you check more about the importance of tokenization in different languages. Gensim is a library for unsupervised topic modeling and natural language processing and also contains a tokenizer. Once you install Gensim, tokenizing text will be as simple as writing the following code. from gensim.utils import tokenizelist(tokenize(text)) The output to this code is this. ['Here', 's', 'to', 'the', 'crazy', 'ones', 'the', 'misfits', 'the', 'rebels', 'the', 'troublemakers', 'the', 'round', 'pegs', 'in', 'the', 'square', 'holes', 'The', 'ones', 'who', 'see', 'things', 'differently', 'they', 're', 'not', 'fond', 'of', 'rules', 'You', 'can', 'quote', 'them', 'disagree', 'with', 'them', 'glorify', 'or', 'vilify', 'them', 'but', 'the', 'only', 'thing', 'you', 'can', 't', 'do', 'is', 'ignore', 'them', 'because', 'they', 'change', 'things', 'They', 'push', 'the', 'human', 'race', 'forward', 'and', 'while', 'some', 'may', 'see', 'them', 'as', 'the', 'crazy', 'ones', 'we', 'see', 'genius', 'because', 'the', 'ones', 'who', 'are', 'crazy', 'enough', 'to', 'think', 'that', 'they', 'can', 'change', 'the', 'world', 'are', 'the', 'ones', 'who', 'do'] As you can see, Gensim splits every time it encounters a punctuation symbol e.g. Here, s , can, t Tokenization presents different challenges, but now you know 5 different ways to deal with them. The .split method is a simple tokenizer that separates text by white spaces. NLTK and Gensim do a similar job, but with different punctuation rules. Other great options are spaCy, which offers a multilingual tokenizer and sklearn that helps tokenize a large corpus. Join my email list with 3k+ people to get my Python for Data Science Cheat Sheet I use in all my tutorials (Free PDF) If you enjoy reading stories like these and want to support me as a writer, consider signing up to become a Medium member. It’s $5 a month, giving you unlimited access to stories on Medium. If you sign up using my link, I’ll earn a small commission with no extra cost to you.
[ { "code": null, "e": 526, "s": 172, "text": "Tokenization is a common task a data scientist comes across when working with text data. It consists of splitting an entire text into small units, also known as tokens. Most Natural Language Processing (NLP) projects have tokenization as the first step because it’s the foundation for developing good models and helps better understand the text we have." }, { "code": null, "e": 817, "s": 526, "text": "Although tokenization in Python could be as simple as writing .split(), that method might not be the most efficient in some projects. That’s why, in this article, I’ll show 5 ways that will help you tokenize small texts, a large corpus or even text written in a language other than English." }, { "code": null, "e": 1050, "s": 817, "text": "Table of Contents1. Simple tokenization with .split2. Tokenization with NLTK3. Convert a corpus to a vector of token counts with Count Vectorizer (sklearn)4. Tokenize text in different languages with spaCy5. Tokenization with Gensim" }, { "code": null, "e": 1277, "s": 1050, "text": "Note: Tokenization is one of the many tasks a data scientist do when cleaning and preparing data. In the article below, I wrote a guide to help you with these tedious tasks. The code of both articles is available on my Github." }, { "code": null, "e": 1300, "s": 1277, "text": "towardsdatascience.com" }, { "code": null, "e": 1457, "s": 1300, "text": "As we mentioned before, this is the simplest method to perform tokenization in Python. If you type .split(), the text will be separated at each blank space." }, { "code": null, "e": 1582, "s": 1457, "text": "For this and the following examples, we’ll be using a text narrated by Steve Jobs in the “Think Different” Apple commercial." }, { "code": null, "e": 2112, "s": 1582, "text": "text = “””Here’s to the crazy ones, the misfits, the rebels, the troublemakers, the round pegs in the square holes. The ones who see things differently — they’re not fond of rules. You can quote them, disagree with them, glorify or vilify them, but the only thing you can’t do is ignore them because they change things. They push the human race forward, and while some may see them as the crazy ones, we see genius, because the ones who are crazy enough to thinkthat they can change the world, are the ones who do.”””text.split()" }, { "code": null, "e": 2175, "s": 2112, "text": "If we write the code above, we’ll obtain the following output." }, { "code": null, "e": 2964, "s": 2175, "text": "['Here’s', 'to', 'the', 'crazy', 'ones,', 'the', 'misfits,', 'the', 'rebels,', 'the', 'troublemakers,', 'the', 'round', 'pegs', 'in', 'the', 'square', 'holes.', 'The', 'ones', 'who', 'see', 'things', 'differently', '—', 'they’re', 'not', 'fond', 'of', 'rules.', 'You', 'can', 'quote', 'them,', 'disagree', 'with', 'them,', 'glorify', 'or', 'vilify', 'them,', 'but', 'the', 'only', 'thing', 'you', 'can’t', 'do', 'is', 'ignore', 'them', 'because', 'they', 'change', 'things.', 'They', 'push', 'the', 'human', 'race', 'forward,', 'and', 'while', 'some', 'may', 'see', 'them', 'as', 'the', 'crazy', 'ones,', 'we', 'see', 'genius,', 'because', 'the', 'ones', 'who', 'are', 'crazy', 'enough', 'to', 'think', 'that', 'they', 'can', 'change', 'the', 'world,', 'are', 'the', 'ones', 'who', 'do.']" }, { "code": null, "e": 3103, "s": 2964, "text": "As you can see above, the split() method doesn’t consider punctuation symbols as a separate token. This might change your project results." }, { "code": null, "e": 3114, "s": 3103, "text": "medium.com" }, { "code": null, "e": 3273, "s": 3114, "text": "NLTK stands for Natural Language Toolkit. This is a suite of libraries and programs for statistical natural language processing for English written in Python." }, { "code": null, "e": 3454, "s": 3273, "text": "NLTK contains a module called tokenize with a word_tokenize() method that will help us split a text into tokens. Once you installed NLTK, write the following code to tokenize text." }, { "code": null, "e": 3513, "s": 3454, "text": "from nltk.tokenize import word_tokenizeword_tokenize(text)" }, { "code": null, "e": 3605, "s": 3513, "text": "In this case, the default output is slightly different from the .split method showed above." }, { "code": null, "e": 3738, "s": 3605, "text": "['Here', '’', 's', 'to', 'the', 'crazy', 'ones', ',', 'the', 'misfits', ',', 'the', 'rebels', ',', 'the', 'troublemakers', ',', ...]" }, { "code": null, "e": 3839, "s": 3738, "text": "In this case, the apostrophe (‘) in “here’s” and the comma (,) in “ones,” were considered as tokens." }, { "code": null, "e": 4131, "s": 3839, "text": "The previous methods become less useful when dealing with a large corpus because you’ll need to represent the tokens differently. Count Vectorizer will help us convert a collection of text documents to a vector of token counts. In the end, we’ll get a vector representation of the text data." }, { "code": null, "e": 4261, "s": 4131, "text": "For this example, I’ll add a quote from Bill Gates to the previous text to build a dataframe that will be an example of a corpus." }, { "code": null, "e": 4963, "s": 4261, "text": "import pandas as pdtexts = [\"\"\"Here’s to the crazy ones, the misfits, the rebels, the troublemakers, the round pegs in the square holes. The ones who see things differently — they’re not fond of rules. You can quote them, disagree with them, glorify or vilify them, but the only thing you can’t do is ignore them because they change things. They push the human race forward, and while some may see them as the crazy ones, we see genius, because the ones who are crazy enough to think that they can change the world, are the ones who do.\"\"\" , 'I choose a lazy person to do a hard job. Because a lazy person will find an easy way to do it.']df = pd.DataFrame({'author': ['jobs', 'gates'], 'text':texts})" }, { "code": null, "e": 5072, "s": 4963, "text": "Now we’ll use Count Vectorizer to transform these texts within the df dataframe in a vector of token counts." }, { "code": null, "e": 5179, "s": 5072, "text": "If you run that code, you’ll get a frame that counts the number of times a word was mention in both texts." }, { "code": null, "e": 5377, "s": 5179, "text": "This becomes extremely useful when the dataframe contains a large corpus because it provides a matrix with words encoded as integers values, which are used as inputs in machine learning algorithms." }, { "code": null, "e": 5662, "s": 5377, "text": "Count Vectorizer can have different parameters like stop_words that we defined above. However, keep in mind that the default regexp used by Count Vectorizer selects tokens of 2 or more alphanumeric characters (punctuation is completely ignored and always treated as a token separator)" }, { "code": null, "e": 5899, "s": 5662, "text": "When you need to tokenize text written in a language other than English, you can use spaCy. This is a library for advanced natural language processing, written in Python and Cython, that supports tokenization for more than 65 languages." }, { "code": null, "e": 5970, "s": 5899, "text": "Let’s tokenize the same Steve Jobs text but now translated in Spanish." }, { "code": null, "e": 6150, "s": 5970, "text": "In this case, we imported Spanish from spacy.lang.es but if you’re working with text in English, just import English from spacy.lang.en Check the list of languages available here." }, { "code": null, "e": 6205, "s": 6150, "text": "If you run this code, you’ll get the following output." }, { "code": null, "e": 7196, "s": 6205, "text": "['Por', 'los', 'locos', '.', 'Los', 'marginados', '.', 'Los', 'rebeldes', '.', 'Los', 'problematicos', '.', '\\n', 'Los', 'inadaptados', '.', 'Los', 'que', 'ven', 'las', 'cosas', 'de', 'una', 'manera', 'distinta', '.', 'A', 'los', 'que', 'no', 'les', 'gustan', '\\n', 'las', 'reglas', '.', 'Y', 'a', 'los', 'que', 'no', 'respetan', 'el', '“', 'status', 'quo', '”', '.', 'Puedes', 'citarlos', ',', 'discrepar', 'de', 'ellos', ',', '\\n', 'ensalzarlos', 'o', 'vilipendiarlos', '.', 'Pero', 'lo', 'que', 'no', 'puedes', 'hacer', 'es', 'ignorarlos', '...', 'Porque', 'ellos', '\\n', 'cambian', 'las', 'cosas', ',', 'empujan', 'hacia', 'adelante', 'la', 'raza', 'humana', 'y', ',', 'aunque', 'algunos', 'puedan', '\\n', 'considerarlos', 'locos', ',', 'nosotros', 'vemos', 'en', 'ellos', 'a', 'genios', '.', 'Porque', 'las', 'personas', 'que', 'están', '\\n', 'lo', 'bastante', 'locas', 'como', 'para', 'creer', 'que', 'pueden', 'cambiar', 'el', 'mundo', ',', 'son', 'las', 'que', 'lo', 'logran', '.']" }, { "code": null, "e": 7306, "s": 7196, "text": "As you can see spaCy, considers punctuation symbols as a separate token (even the new lines\\n were included)." }, { "code": null, "e": 7479, "s": 7306, "text": "If you know a bit about Spanish, you might’ve noticed that the tokenization is similar to English, so you might be wondering, “why do I need a tokenizer for each language?”" }, { "code": null, "e": 7850, "s": 7479, "text": "Although for languages like Spanish and English, tokenization will be as simple as separating by whitespace, for non-romance languages such as Chinese and Japanese, the orthography might have no spaces to delimit “words” or “tokens.” In such cases, a library like spaCy will come in handy. Here you check more about the importance of tokenization in different languages." }, { "code": null, "e": 8055, "s": 7850, "text": "Gensim is a library for unsupervised topic modeling and natural language processing and also contains a tokenizer. Once you install Gensim, tokenizing text will be as simple as writing the following code." }, { "code": null, "e": 8109, "s": 8055, "text": "from gensim.utils import tokenizelist(tokenize(text))" }, { "code": null, "e": 8142, "s": 8109, "text": "The output to this code is this." }, { "code": null, "e": 8920, "s": 8142, "text": "['Here', 's', 'to', 'the', 'crazy', 'ones', 'the', 'misfits', 'the', 'rebels', 'the', 'troublemakers', 'the', 'round', 'pegs', 'in', 'the', 'square', 'holes', 'The', 'ones', 'who', 'see', 'things', 'differently', 'they', 're', 'not', 'fond', 'of', 'rules', 'You', 'can', 'quote', 'them', 'disagree', 'with', 'them', 'glorify', 'or', 'vilify', 'them', 'but', 'the', 'only', 'thing', 'you', 'can', 't', 'do', 'is', 'ignore', 'them', 'because', 'they', 'change', 'things', 'They', 'push', 'the', 'human', 'race', 'forward', 'and', 'while', 'some', 'may', 'see', 'them', 'as', 'the', 'crazy', 'ones', 'we', 'see', 'genius', 'because', 'the', 'ones', 'who', 'are', 'crazy', 'enough', 'to', 'think', 'that', 'they', 'can', 'change', 'the', 'world', 'are', 'the', 'ones', 'who', 'do']" }, { "code": null, "e": 9018, "s": 8920, "text": "As you can see, Gensim splits every time it encounters a punctuation symbol e.g. Here, s , can, t" }, { "code": null, "e": 9381, "s": 9018, "text": "Tokenization presents different challenges, but now you know 5 different ways to deal with them. The .split method is a simple tokenizer that separates text by white spaces. NLTK and Gensim do a similar job, but with different punctuation rules. Other great options are spaCy, which offers a multilingual tokenizer and sklearn that helps tokenize a large corpus." }, { "code": null, "e": 9499, "s": 9381, "text": "Join my email list with 3k+ people to get my Python for Data Science Cheat Sheet I use in all my tutorials (Free PDF)" } ]
Controlling the Web Browser with Python - GeeksforGeeks
23 Sep, 2021 In this article, we are going to see how to control the web browser with Python using selenium. Selenium is an open-source tool that automates web browsers. It provides a single interface that lets you write test scripts in programming languages like Ruby, Java, NodeJS, PHP, Perl, Python, and C#, etc. pip install selenium For automation please download the latest Google Chrome along with chromedriver from here. Here we will automate the authorization at “https://auth.geeksforgeeks.org” and extract the Name, Email, Institute name from the logged-in profile. First, we need to initiate the web driver using selenium and send a get request to the url and Identify the HTML document and find the input tags and button tags that accept username/email, password, and sign-in button. To send the user given email and password to the input tags respectively: driver.find_element_by_name('user').send_keys(email) driver.find_element_by_name('pass').send_keys(password) Identify the button tag and click on it using the CSS selector via selenium webdriver: driver.find_element_by_css_selector(‘button.btn.btn-green.signin-button’).click() Scraping Basic Information from GFG Profile After clicking on Sign in, a new page should be loaded containing the Name, Institute Name, and Email id. Identify the tags containing the above data and select them. container = driver.find_elements_by_css_selector(‘div.mdl-cell.mdl-cell–9-col.mdl-cell–12-col-phone.textBold’) Get the text from each of these tags from the returned list of selected css selectors: name = container[0].text try: institution = container[1].find_element_by_css_selector('a').text except: institution = container[1].text email_id = container[2].text Finally, print the output: print({"Name": name, "Institution": institution, "Email ID": email}) Click on the Practice tab and wait for few seconds to load the page. driver.find_elements_by_css_selector('a.mdl-navigation__link')[1].click() Find the container containing all the information and select the grids using CSS selector from the container having information. container = driver.find_element_by_css_selector(‘div.mdl-cell.mdl-cell–7-col.mdl-cell–12-col-phone.whiteBgColor.mdl-shadow–2dp.userMainDiv’) grids = container.find_elements_by_css_selector(‘div.mdl-grid’) Iterate each of the selected grids and extract the text from it and add it to a set/list for output. res = set() for grid in grids: res.add(grid.text.replace('\n',':')) Python3 # Import the required modulesfrom selenium import webdriverimport time # Main Functionif __name__ == '__main__': # Provide the email and password email = 'example@example.com' password = 'password' options = webdriver.ChromeOptions() options.add_argument("--start-maximized") options.add_argument('--log-level=3') # Provide the path of chromedriver present on your system. driver = webdriver.Chrome(executable_path="C:/chromedriver/chromedriver.exe", chrome_options=options) driver.set_window_size(1920,1080) # Send a get request to the url driver.get('https://auth.geeksforgeeks.org/') time.sleep(5) # Finds the input box by name in DOM tree to send both # the provided email and password in it. driver.find_element_by_name('user').send_keys(email) driver.find_element_by_name('pass').send_keys(password) # Find the signin button and click on it. driver.find_element_by_css_selector( 'button.btn.btn-green.signin-button').click() time.sleep(5) # Returns the list of elements # having the following css selector. container = driver.find_elements_by_css_selector( 'div.mdl-cell.mdl-cell--9-col.mdl-cell--12-col-phone.textBold') # Extracts the text from name, # institution, email_id css selector. name = container[0].text try: institution = container[1].find_element_by_css_selector('a').text except: institution = container[1].text email_id = container[2].text # Output Example 1 print("Basic Info") print({"Name": name, "Institution": institution, "Email ID": email}) # Clicks on Practice Tab driver.find_elements_by_css_selector( 'a.mdl-navigation__link')[1].click() time.sleep(5) # Selected the Container containing information container = driver.find_element_by_css_selector( 'div.mdl-cell.mdl-cell--7-col.mdl-cell--12-col-phone.\ whiteBgColor.mdl-shadow--2dp.userMainDiv') # Selected the tags from the container grids = container.find_elements_by_css_selector( 'div.mdl-grid') # Iterate each tag and append the text extracted from it. res = set() for grid in grids: res.add(grid.text.replace('\n',':')) # Output Example 2 print("Practice Info") print(res) # Quits the driver driver.close() driver.quit() Output: Blogathon-2021 Picked Python Selenium-Exercises Python-selenium Blogathon Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments How to Import JSON Data into SQL Server? How to Install Tkinter in Windows? SQL - Multiple Column Ordering How to pass data into table from a form using React Components How to Create a Table With Multiple Foreign Keys in SQL? Read JSON file using Python Adding new column to existing DataFrame in Pandas Python map() function How to get column names in Pandas dataframe
[ { "code": null, "e": 24421, "s": 24393, "text": "\n23 Sep, 2021" }, { "code": null, "e": 24724, "s": 24421, "text": "In this article, we are going to see how to control the web browser with Python using selenium. Selenium is an open-source tool that automates web browsers. It provides a single interface that lets you write test scripts in programming languages like Ruby, Java, NodeJS, PHP, Perl, Python, and C#, etc." }, { "code": null, "e": 24745, "s": 24724, "text": "pip install selenium" }, { "code": null, "e": 24836, "s": 24745, "text": "For automation please download the latest Google Chrome along with chromedriver from here." }, { "code": null, "e": 24984, "s": 24836, "text": "Here we will automate the authorization at “https://auth.geeksforgeeks.org” and extract the Name, Email, Institute name from the logged-in profile." }, { "code": null, "e": 25204, "s": 24984, "text": "First, we need to initiate the web driver using selenium and send a get request to the url and Identify the HTML document and find the input tags and button tags that accept username/email, password, and sign-in button." }, { "code": null, "e": 25278, "s": 25204, "text": "To send the user given email and password to the input tags respectively:" }, { "code": null, "e": 25387, "s": 25278, "text": "driver.find_element_by_name('user').send_keys(email)\ndriver.find_element_by_name('pass').send_keys(password)" }, { "code": null, "e": 25474, "s": 25387, "text": "Identify the button tag and click on it using the CSS selector via selenium webdriver:" }, { "code": null, "e": 25557, "s": 25474, "text": " driver.find_element_by_css_selector(‘button.btn.btn-green.signin-button’).click()" }, { "code": null, "e": 25601, "s": 25557, "text": "Scraping Basic Information from GFG Profile" }, { "code": null, "e": 25768, "s": 25601, "text": "After clicking on Sign in, a new page should be loaded containing the Name, Institute Name, and Email id. Identify the tags containing the above data and select them." }, { "code": null, "e": 25879, "s": 25768, "text": "container = driver.find_elements_by_css_selector(‘div.mdl-cell.mdl-cell–9-col.mdl-cell–12-col-phone.textBold’)" }, { "code": null, "e": 25966, "s": 25879, "text": "Get the text from each of these tags from the returned list of selected css selectors:" }, { "code": null, "e": 26139, "s": 25966, "text": "name = container[0].text\ntry:\n institution = container[1].find_element_by_css_selector('a').text\nexcept:\n institution = container[1].text\nemail_id = container[2].text" }, { "code": null, "e": 26166, "s": 26139, "text": "Finally, print the output:" }, { "code": null, "e": 26235, "s": 26166, "text": "print({\"Name\": name, \"Institution\": institution, \"Email ID\": email})" }, { "code": null, "e": 26304, "s": 26235, "text": "Click on the Practice tab and wait for few seconds to load the page." }, { "code": null, "e": 26378, "s": 26304, "text": "driver.find_elements_by_css_selector('a.mdl-navigation__link')[1].click()" }, { "code": null, "e": 26507, "s": 26378, "text": "Find the container containing all the information and select the grids using CSS selector from the container having information." }, { "code": null, "e": 26648, "s": 26507, "text": "container = driver.find_element_by_css_selector(‘div.mdl-cell.mdl-cell–7-col.mdl-cell–12-col-phone.whiteBgColor.mdl-shadow–2dp.userMainDiv’)" }, { "code": null, "e": 26712, "s": 26648, "text": "grids = container.find_elements_by_css_selector(‘div.mdl-grid’)" }, { "code": null, "e": 26813, "s": 26712, "text": "Iterate each of the selected grids and extract the text from it and add it to a set/list for output." }, { "code": null, "e": 26885, "s": 26813, "text": "res = set()\nfor grid in grids:\n res.add(grid.text.replace('\\n',':'))" }, { "code": null, "e": 26893, "s": 26885, "text": "Python3" }, { "code": "# Import the required modulesfrom selenium import webdriverimport time # Main Functionif __name__ == '__main__': # Provide the email and password email = 'example@example.com' password = 'password' options = webdriver.ChromeOptions() options.add_argument(\"--start-maximized\") options.add_argument('--log-level=3') # Provide the path of chromedriver present on your system. driver = webdriver.Chrome(executable_path=\"C:/chromedriver/chromedriver.exe\", chrome_options=options) driver.set_window_size(1920,1080) # Send a get request to the url driver.get('https://auth.geeksforgeeks.org/') time.sleep(5) # Finds the input box by name in DOM tree to send both # the provided email and password in it. driver.find_element_by_name('user').send_keys(email) driver.find_element_by_name('pass').send_keys(password) # Find the signin button and click on it. driver.find_element_by_css_selector( 'button.btn.btn-green.signin-button').click() time.sleep(5) # Returns the list of elements # having the following css selector. container = driver.find_elements_by_css_selector( 'div.mdl-cell.mdl-cell--9-col.mdl-cell--12-col-phone.textBold') # Extracts the text from name, # institution, email_id css selector. name = container[0].text try: institution = container[1].find_element_by_css_selector('a').text except: institution = container[1].text email_id = container[2].text # Output Example 1 print(\"Basic Info\") print({\"Name\": name, \"Institution\": institution, \"Email ID\": email}) # Clicks on Practice Tab driver.find_elements_by_css_selector( 'a.mdl-navigation__link')[1].click() time.sleep(5) # Selected the Container containing information container = driver.find_element_by_css_selector( 'div.mdl-cell.mdl-cell--7-col.mdl-cell--12-col-phone.\\ whiteBgColor.mdl-shadow--2dp.userMainDiv') # Selected the tags from the container grids = container.find_elements_by_css_selector( 'div.mdl-grid') # Iterate each tag and append the text extracted from it. res = set() for grid in grids: res.add(grid.text.replace('\\n',':')) # Output Example 2 print(\"Practice Info\") print(res) # Quits the driver driver.close() driver.quit()", "e": 29297, "s": 26893, "text": null }, { "code": null, "e": 29305, "s": 29297, "text": "Output:" }, { "code": null, "e": 29320, "s": 29305, "text": "Blogathon-2021" }, { "code": null, "e": 29327, "s": 29320, "text": "Picked" }, { "code": null, "e": 29353, "s": 29327, "text": "Python Selenium-Exercises" }, { "code": null, "e": 29369, "s": 29353, "text": "Python-selenium" }, { "code": null, "e": 29379, "s": 29369, "text": "Blogathon" }, { "code": null, "e": 29386, "s": 29379, "text": "Python" }, { "code": null, "e": 29484, "s": 29386, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29493, "s": 29484, "text": "Comments" }, { "code": null, "e": 29506, "s": 29493, "text": "Old Comments" }, { "code": null, "e": 29547, "s": 29506, "text": "How to Import JSON Data into SQL Server?" }, { "code": null, "e": 29582, "s": 29547, "text": "How to Install Tkinter in Windows?" }, { "code": null, "e": 29613, "s": 29582, "text": "SQL - Multiple Column Ordering" }, { "code": null, "e": 29676, "s": 29613, "text": "How to pass data into table from a form using React Components" }, { "code": null, "e": 29733, "s": 29676, "text": "How to Create a Table With Multiple Foreign Keys in SQL?" }, { "code": null, "e": 29761, "s": 29733, "text": "Read JSON file using Python" }, { "code": null, "e": 29811, "s": 29761, "text": "Adding new column to existing DataFrame in Pandas" }, { "code": null, "e": 29833, "s": 29811, "text": "Python map() function" } ]
Update a MySQL table with Java MySQL
For this, you need to use PreparedStatement in Java for update. Let us first create a table − mysql> create table DemoTable( Id int, FirstName varchar(40) ); Query OK, 0 rows affected (0.62 sec) Insert some records in the table using insert command − mysql> insert into DemoTable values(100,'Chris'); Query OK, 1 row affected (0.13 sec) mysql> insert into DemoTable values(111,'Mike'); Query OK, 1 row affected (0.18 sec) mysql> insert into DemoTable values(121,'Sam'); Query OK, 1 row affected (0.09 sec) Display all records from the table using select statement − mysql> select * from DemoTable; This will produce the following output − +------+-----------+ | Id | FirstName | +------+-----------+ | 100 | Chris | | 111 | Mike | | 121 | Sam | +------+-----------+ 3 rows in set (0.00 sec) The Java code is as follows to update − import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; public class UpdateFromJava { public static void main(String[] args) { Connection con = null; PreparedStatement ps = null; try { con = DriverManager.getConnection("jdbc :mysql ://localhost :3306/web?" + "useSSL=false", "root", "123456"); String query = "update DemoTable set FirstName=? where Id=? "; ps = con.prepareStatement(query); ps.setString(1, "Tom"); ps.setInt(2, 100); ps.executeUpdate(); System.out.println("Record is updated successfully......"); } catch (Exception e) { e.printStackTrace(); } } } Following the output of Java code − Record is updated successfully...... The screenshot of the output is as follows − Let us now check the FirstName column name value has been updated to ‘Tom’ or not with ID 100. Following is the query to check records and display them again − mysql> select * from DemoTable; This will produce the following output − +------+-----------+ | Id | FirstName | +------+-----------+ | 100 | Tom | | 111 | Mike | | 121 | Sam | +------+-----------+ 3 rows in set (0.00 sec) The snapshot of the output is as follows. The FirstName column updated successfully with Java-MySQL −
[ { "code": null, "e": 1156, "s": 1062, "text": "For this, you need to use PreparedStatement in Java for update. Let us first create a table −" }, { "code": null, "e": 1263, "s": 1156, "text": "mysql> create table DemoTable(\n Id int,\n FirstName varchar(40)\n);\nQuery OK, 0 rows affected (0.62 sec)" }, { "code": null, "e": 1319, "s": 1263, "text": "Insert some records in the table using insert command −" }, { "code": null, "e": 1574, "s": 1319, "text": "mysql> insert into DemoTable values(100,'Chris');\nQuery OK, 1 row affected (0.13 sec)\nmysql> insert into DemoTable values(111,'Mike');\nQuery OK, 1 row affected (0.18 sec)\nmysql> insert into DemoTable values(121,'Sam');\nQuery OK, 1 row affected (0.09 sec)" }, { "code": null, "e": 1634, "s": 1574, "text": "Display all records from the table using select statement −" }, { "code": null, "e": 1666, "s": 1634, "text": "mysql> select * from DemoTable;" }, { "code": null, "e": 1707, "s": 1666, "text": "This will produce the following output −" }, { "code": null, "e": 1879, "s": 1707, "text": "+------+-----------+\n| Id | FirstName |\n+------+-----------+\n| 100 | Chris |\n| 111 | Mike |\n| 121 | Sam |\n+------+-----------+\n3 rows in set (0.00 sec)" }, { "code": null, "e": 1919, "s": 1879, "text": "The Java code is as follows to update −" }, { "code": null, "e": 2645, "s": 1919, "text": "import java.sql.Connection;\nimport java.sql.DriverManager;\nimport java.sql.PreparedStatement;\npublic class UpdateFromJava {\n public static void main(String[] args) {\n Connection con = null;\n PreparedStatement ps = null;\n try {\n con = DriverManager.getConnection(\"jdbc :mysql ://localhost :3306/web?\" +\n \"useSSL=false\", \"root\", \"123456\");\n String query = \"update DemoTable set FirstName=? where Id=? \";\n ps = con.prepareStatement(query);\n ps.setString(1, \"Tom\");\n ps.setInt(2, 100);\n ps.executeUpdate();\n System.out.println(\"Record is updated successfully......\");\n } catch (Exception e) {\n e.printStackTrace();\n }\n }\n}" }, { "code": null, "e": 2681, "s": 2645, "text": "Following the output of Java code −" }, { "code": null, "e": 2718, "s": 2681, "text": "Record is updated successfully......" }, { "code": null, "e": 2763, "s": 2718, "text": "The screenshot of the output is as follows −" }, { "code": null, "e": 2858, "s": 2763, "text": "Let us now check the FirstName column name value has been updated to ‘Tom’ or not with ID 100." }, { "code": null, "e": 2923, "s": 2858, "text": "Following is the query to check records and display them again −" }, { "code": null, "e": 2955, "s": 2923, "text": "mysql> select * from DemoTable;" }, { "code": null, "e": 2996, "s": 2955, "text": "This will produce the following output −" }, { "code": null, "e": 3168, "s": 2996, "text": "+------+-----------+\n| Id | FirstName |\n+------+-----------+\n| 100 | Tom |\n| 111 | Mike |\n| 121 | Sam |\n+------+-----------+\n3 rows in set (0.00 sec)" }, { "code": null, "e": 3270, "s": 3168, "text": "The snapshot of the output is as follows. The FirstName column updated successfully with Java-MySQL −" } ]
Low-Cost Cell Biology Experiments for Data Scientists | by Paul Mooney | Towards Data Science
Introduction: Can “citizen scientists” do real science without costly laboratory equipment? In short: yes. In this blog post we point out an alternative and low-cost approach to solving biological questions that is suited to the aspiring amateur scientist. Specifically, we highlight the benefits of combining low-cost imaging equipment (FoldScope microscopes) and public image data (Kaggle Datasets) with free tools for performing computational data analysis (Kaggle Kernels). Furthermore, we provide a general framework for using these tools to tackle image classification problems in the biological sciences. We hope that these guidelines encourage more data scientists to publish cell biology datasets and to share what they learn. Part 1: Obtaining image data High-throughput and super-resolution microscopy methods have been invaluable to the study of cellular biology [1,2], but these technologies are prohibitively expensive for many or most research labs. The good news, however, is that innovative technologies like FoldScope microscopes can dramatically decrease research costs [3]. FoldScope microscopes are literally paper microscopes, made of a paper frame attached to a high-magnification objective lens (Figure 1). These multi-use microscopes have proven capable of imaging infectious agents such as Plasmodium falciparum and Schistosoma haematobium [3,4], and can be attached to the camera of a cellular phone. FoldScope microscopes currently retail for as little as $1.50 each, and their low cost has inspired an active community of citizen scientists. In this work we acquired new cell images using a FoldScope microscope. We opted to start with commercially prepared slides, sold by the Carolina Biological Supply Company, containing dividing Ascaris lumbricoides cells and hematoxylin staining. Images were acquired using a FoldScope microscope equipped with a 500x magnification lens and a 8-megapixel digital camera (iPhone 5). In this way, we generated a dataset of images of cells in different stages of cellular division with a very minimal investment. Part 2: Sharing image data A FoldScope microscope was used to acquire 90 images of dividing cells in hematoxylin stained Ascaris lumbricoides uterus (Figure 2). These images were shared as a public dataset on Kaggle along with some starter code demonstrating how to work with the data. A dataset of only 90 images is inevitably limited and does not present a suitable challenge for the computational environment. As such, we identified a relatively large dataset of labeled images of Jurkat cells in various different stages of cellular division [5] and added it to our Kaggle Dataset as well. With this supplemental dataset of approximately 32,000 cell images, we could sufficiently test the ability of the free Kaggle Kernels product for performing complex computational analyses. Part 3: Analyzing image data Deep learning algorithms are exciting in part because of their potential to automate biomedical research tasks [6,7]. For example, deep learning algorithms can be used to automate the time-consuming process of manually counting mitotic structures in breast histopathology images [8,9]. Differences in the rates of cellular division and differences in the amount of time spent in each stage of cellular division are both important differentiators between healthy cells and cancer cells [10,11]. Likewise, cancer cells often form erroneous mitotic structures during cellular division and these erroneous structures can contribute to further disease progression [12,13]. As such, the study of cellular division and and its machinery has led to the development of numerous anti-cancer drugs [14,15]. In this work we use the cell division dataset from Figure 2 to train a deep learning model that can be used to identify cell cycle stages in images of dividing cells (Figure 3). Here we present a simple approach that combines the Kaggle Kernel with the cell division dataset from Figure 2 in order to train a deep neural network to identify cell cycle stages. The free-of-charge Kaggle Kernel combines the data, the code, and the cloud-based computational environment in such a way that makes the work easy to reproduce. In fact, you can duplicate this work and you can run it in an identical cloud-based computational environment just by pressing the “Fork Kernel” button on the Kaggle website. (Additional discussion on research reproducibility and a set of recommended guidelines can be found here). By using a dataset of 32,266 images to train a deep neural network, we hope we’ve shown how well the free Kaggle Kernels environment can perform complex computational analyses that are relevant to the biomedical sciences. The ML model that was trained under this new approach gave results that were comparable to the original analysis (Figure 4). Interestingly, both models still have room for improvement in identifying some of the more rarely-observed cell cycle stages, but this could likely be corrected for by generating additional data. The code in Figure 4B is meant to be generalizable and should work well with diverse image types and image categories: the fastai.ImageDataBunch.from_folder() function can be used to load and process any compatible image, and the fastai.create_cnn() function can be used to automatically learn new model features. # Code to generate Figure 4A: https://github.com/theislab/deepflow# Code to generate Figure 4B: (below)from fastai import *from fastai.vision import *from fastai.callbacks.hooks import *import numpy as np; import pandas as pdimport matplotlib; import matplotlib.pyplot as pltimg_dir='../input/'; path=Path(img_dir)data=ImageDataBunch.from_folder(path, train=".",valid_pct=0.3, ds_tfms=get_transforms(do_flip=True,flip_vert=True,max_rotate=90,max_lighting=0.3),size=224,bs=64,num_workers=0).normalize(imagenet_stats)learn=create_cnn(data, models.resnet34, metrics=accuracy, model_dir="/tmp/model/")learn.fit_one_cycle(10)interp=ClassificationInterpretation.from_learner(learn)interp.plot_confusion_matrix(figsize=(10,10), dpi=60) This work describes a reusable framework that can be applied to cell biology datasets to solve image classification problems. The specific image classification problem discussed was the automatic identification of cell cycle stages during cellular division, and the approach was notable because of the low cost of the equipment and because of how easy it was to train the model (with free cloud computing and open-sourced ML algorithms). Data scientists and cell biologists who want to train their own image classification models can easily replicate this approach by creating a dataset of their own FoldScope images, organizing the training data into folders that correspond with each image label, and then attaching that same dataset to a kernel that contains the Fastai code described in Figure 4. We hope that future researchers take advantage of the dataset and the starter code that we have shared in order to quickly fork, modify, and improve upon our models. Conclusion: Since the first compound microscopes were built in the 1600s, medical imaging and laboratory equipment has been expensive to produce and to own. Analytical software is much newer but in many cases can be equally expensive. More recently, low-cost tools like the $1.50 FoldScope microscope and the $0.00 Kaggle Kernel have been developed that can perform many of these same functions at a fraction of the cost. This work describes a low-cost and reusable framework that can be applied to cell biology datasets to solve image classification problems. We hope that these guidelines will encourage more data scientists to explore and publish cell biology datasets and to share their results and findings. Works Cited: [1] Miller MA, Weissleder R. Imaging of anticancer drug action in single cells. Nature Reviews Cancer. 2017. Vol 17(7): p399–414. [2] Liu TL, Upadhyayula S, Milkie, et al. Observing the cell in its native state: Imaging subcellular dynamics in multicellular organisms. Science. 2018 Vol 360(6386). [3] Cybulski J, Clements J, Prakash M. Foldscope: Origami-Based Paper Microscope. PLoS One. 2014; Vol 9(6). [4] Ephraim R, Duah E, et al. Diagnosis of Schistosoma haematobium Infection with a Mobile Phone-Mounted Foldscope and a Reversed-Lens CellScope in Ghana. Am J Trop Med Hyg. 2015. Vol 92(6): p. 1253–1256. [5] Eulenberg P, Köhler N, et al. Reconstructing cell cycle and disease progression using deep learning. Nature Communications. 2017. Vol 8(1): p463. [6] Esteva A, Robicquet A, et al. A guide to deep learning in healthcare. Nature Medicine. 2019. Vol 25: p.24–29. [7] Topol, Eric J. High-performance medicine: the convergence of human and artificial intelligence. Nature Medicine. 2019. Vol 1: p44–56. [8] Li C, Wang X, Liu W, Latecki LJ. DeepMitosis: Mitosis detection via deep detection, verification and segmentation networks. Medical Image Analysis. 2018. Vol 45: [9] Saha M, Chakraborty C, Racoceanu D. Efficient deep learning model for mitosis detection using breast histopathology images. Computational Medical Imaging and Graphics. 2018. Vol 64: p29–40. [10] Sherr CJ. Cancer cell cycles. Science. 1996. Vol 274(5293): p1672–7. [11] Visconti R, Monica RD, Grieco D. Cell cycle checkpoint in cancer: a therapeutically targetable double-edged sword. J Exp Clin Cancer Res. 2016. Vol 35: p153. [12] Milunović-Jevtić A, Mooney P, et al. Centrosomal clustering contributes to chromosomal instability and cancer. Current Opinion in Biotechnology. 2016 Vol 40: p113–118. [13] Bakhoum SF, Cantley LC. The Multifaceted Role of Chromosomal Instability in Cancer and Its Microenvironment. Cell. 2018 Vol 174(6): p1347–1360. [14] Florian S, Mitchison TJ. Anti-Microtubule Drugs. Methods in Molecular Biology. 2016 Vol 1413: p403–411. [15] Steinmetz MO, Prota AE. Microtubule-Targeting Agents: Strategies To Hijack the Cytoskeleton. Trends in Cell Biology. 2018 Vol 28(10): p776–792. [16] The source for the images in Figure 3A, Figure 3B, and the Cover Photo can be found in each respective hyperlink.
[ { "code": null, "e": 186, "s": 172, "text": "Introduction:" }, { "code": null, "e": 264, "s": 186, "text": "Can “citizen scientists” do real science without costly laboratory equipment?" }, { "code": null, "e": 908, "s": 264, "text": "In short: yes. In this blog post we point out an alternative and low-cost approach to solving biological questions that is suited to the aspiring amateur scientist. Specifically, we highlight the benefits of combining low-cost imaging equipment (FoldScope microscopes) and public image data (Kaggle Datasets) with free tools for performing computational data analysis (Kaggle Kernels). Furthermore, we provide a general framework for using these tools to tackle image classification problems in the biological sciences. We hope that these guidelines encourage more data scientists to publish cell biology datasets and to share what they learn." }, { "code": null, "e": 937, "s": 908, "text": "Part 1: Obtaining image data" }, { "code": null, "e": 1743, "s": 937, "text": "High-throughput and super-resolution microscopy methods have been invaluable to the study of cellular biology [1,2], but these technologies are prohibitively expensive for many or most research labs. The good news, however, is that innovative technologies like FoldScope microscopes can dramatically decrease research costs [3]. FoldScope microscopes are literally paper microscopes, made of a paper frame attached to a high-magnification objective lens (Figure 1). These multi-use microscopes have proven capable of imaging infectious agents such as Plasmodium falciparum and Schistosoma haematobium [3,4], and can be attached to the camera of a cellular phone. FoldScope microscopes currently retail for as little as $1.50 each, and their low cost has inspired an active community of citizen scientists." }, { "code": null, "e": 2251, "s": 1743, "text": "In this work we acquired new cell images using a FoldScope microscope. We opted to start with commercially prepared slides, sold by the Carolina Biological Supply Company, containing dividing Ascaris lumbricoides cells and hematoxylin staining. Images were acquired using a FoldScope microscope equipped with a 500x magnification lens and a 8-megapixel digital camera (iPhone 5). In this way, we generated a dataset of images of cells in different stages of cellular division with a very minimal investment." }, { "code": null, "e": 2278, "s": 2251, "text": "Part 2: Sharing image data" }, { "code": null, "e": 3034, "s": 2278, "text": "A FoldScope microscope was used to acquire 90 images of dividing cells in hematoxylin stained Ascaris lumbricoides uterus (Figure 2). These images were shared as a public dataset on Kaggle along with some starter code demonstrating how to work with the data. A dataset of only 90 images is inevitably limited and does not present a suitable challenge for the computational environment. As such, we identified a relatively large dataset of labeled images of Jurkat cells in various different stages of cellular division [5] and added it to our Kaggle Dataset as well. With this supplemental dataset of approximately 32,000 cell images, we could sufficiently test the ability of the free Kaggle Kernels product for performing complex computational analyses." }, { "code": null, "e": 3063, "s": 3034, "text": "Part 3: Analyzing image data" }, { "code": null, "e": 4037, "s": 3063, "text": "Deep learning algorithms are exciting in part because of their potential to automate biomedical research tasks [6,7]. For example, deep learning algorithms can be used to automate the time-consuming process of manually counting mitotic structures in breast histopathology images [8,9]. Differences in the rates of cellular division and differences in the amount of time spent in each stage of cellular division are both important differentiators between healthy cells and cancer cells [10,11]. Likewise, cancer cells often form erroneous mitotic structures during cellular division and these erroneous structures can contribute to further disease progression [12,13]. As such, the study of cellular division and and its machinery has led to the development of numerous anti-cancer drugs [14,15]. In this work we use the cell division dataset from Figure 2 to train a deep learning model that can be used to identify cell cycle stages in images of dividing cells (Figure 3)." }, { "code": null, "e": 4884, "s": 4037, "text": "Here we present a simple approach that combines the Kaggle Kernel with the cell division dataset from Figure 2 in order to train a deep neural network to identify cell cycle stages. The free-of-charge Kaggle Kernel combines the data, the code, and the cloud-based computational environment in such a way that makes the work easy to reproduce. In fact, you can duplicate this work and you can run it in an identical cloud-based computational environment just by pressing the “Fork Kernel” button on the Kaggle website. (Additional discussion on research reproducibility and a set of recommended guidelines can be found here). By using a dataset of 32,266 images to train a deep neural network, we hope we’ve shown how well the free Kaggle Kernels environment can perform complex computational analyses that are relevant to the biomedical sciences." }, { "code": null, "e": 5519, "s": 4884, "text": "The ML model that was trained under this new approach gave results that were comparable to the original analysis (Figure 4). Interestingly, both models still have room for improvement in identifying some of the more rarely-observed cell cycle stages, but this could likely be corrected for by generating additional data. The code in Figure 4B is meant to be generalizable and should work well with diverse image types and image categories: the fastai.ImageDataBunch.from_folder() function can be used to load and process any compatible image, and the fastai.create_cnn() function can be used to automatically learn new model features." }, { "code": null, "e": 6278, "s": 5519, "text": "# Code to generate Figure 4A: https://github.com/theislab/deepflow# Code to generate Figure 4B: (below)from fastai import *from fastai.vision import *from fastai.callbacks.hooks import *import numpy as np; import pandas as pdimport matplotlib; import matplotlib.pyplot as pltimg_dir='../input/'; path=Path(img_dir)data=ImageDataBunch.from_folder(path, train=\".\",valid_pct=0.3, ds_tfms=get_transforms(do_flip=True,flip_vert=True,max_rotate=90,max_lighting=0.3),size=224,bs=64,num_workers=0).normalize(imagenet_stats)learn=create_cnn(data, models.resnet34, metrics=accuracy, model_dir=\"/tmp/model/\")learn.fit_one_cycle(10)interp=ClassificationInterpretation.from_learner(learn)interp.plot_confusion_matrix(figsize=(10,10), dpi=60)" }, { "code": null, "e": 7245, "s": 6278, "text": "This work describes a reusable framework that can be applied to cell biology datasets to solve image classification problems. The specific image classification problem discussed was the automatic identification of cell cycle stages during cellular division, and the approach was notable because of the low cost of the equipment and because of how easy it was to train the model (with free cloud computing and open-sourced ML algorithms). Data scientists and cell biologists who want to train their own image classification models can easily replicate this approach by creating a dataset of their own FoldScope images, organizing the training data into folders that correspond with each image label, and then attaching that same dataset to a kernel that contains the Fastai code described in Figure 4. We hope that future researchers take advantage of the dataset and the starter code that we have shared in order to quickly fork, modify, and improve upon our models." }, { "code": null, "e": 7257, "s": 7245, "text": "Conclusion:" }, { "code": null, "e": 7958, "s": 7257, "text": "Since the first compound microscopes were built in the 1600s, medical imaging and laboratory equipment has been expensive to produce and to own. Analytical software is much newer but in many cases can be equally expensive. More recently, low-cost tools like the $1.50 FoldScope microscope and the $0.00 Kaggle Kernel have been developed that can perform many of these same functions at a fraction of the cost. This work describes a low-cost and reusable framework that can be applied to cell biology datasets to solve image classification problems. We hope that these guidelines will encourage more data scientists to explore and publish cell biology datasets and to share their results and findings." }, { "code": null, "e": 7971, "s": 7958, "text": "Works Cited:" }, { "code": null, "e": 8101, "s": 7971, "text": "[1] Miller MA, Weissleder R. Imaging of anticancer drug action in single cells. Nature Reviews Cancer. 2017. Vol 17(7): p399–414." }, { "code": null, "e": 8269, "s": 8101, "text": "[2] Liu TL, Upadhyayula S, Milkie, et al. Observing the cell in its native state: Imaging subcellular dynamics in multicellular organisms. Science. 2018 Vol 360(6386)." }, { "code": null, "e": 8377, "s": 8269, "text": "[3] Cybulski J, Clements J, Prakash M. Foldscope: Origami-Based Paper Microscope. PLoS One. 2014; Vol 9(6)." }, { "code": null, "e": 8582, "s": 8377, "text": "[4] Ephraim R, Duah E, et al. Diagnosis of Schistosoma haematobium Infection with a Mobile Phone-Mounted Foldscope and a Reversed-Lens CellScope in Ghana. Am J Trop Med Hyg. 2015. Vol 92(6): p. 1253–1256." }, { "code": null, "e": 8733, "s": 8582, "text": "[5] Eulenberg P, Köhler N, et al. Reconstructing cell cycle and disease progression using deep learning. Nature Communications. 2017. Vol 8(1): p463." }, { "code": null, "e": 8847, "s": 8733, "text": "[6] Esteva A, Robicquet A, et al. A guide to deep learning in healthcare. Nature Medicine. 2019. Vol 25: p.24–29." }, { "code": null, "e": 8985, "s": 8847, "text": "[7] Topol, Eric J. High-performance medicine: the convergence of human and artificial intelligence. Nature Medicine. 2019. Vol 1: p44–56." }, { "code": null, "e": 9151, "s": 8985, "text": "[8] Li C, Wang X, Liu W, Latecki LJ. DeepMitosis: Mitosis detection via deep detection, verification and segmentation networks. Medical Image Analysis. 2018. Vol 45:" }, { "code": null, "e": 9345, "s": 9151, "text": "[9] Saha M, Chakraborty C, Racoceanu D. Efficient deep learning model for mitosis detection using breast histopathology images. Computational Medical Imaging and Graphics. 2018. Vol 64: p29–40." }, { "code": null, "e": 9419, "s": 9345, "text": "[10] Sherr CJ. Cancer cell cycles. Science. 1996. Vol 274(5293): p1672–7." }, { "code": null, "e": 9582, "s": 9419, "text": "[11] Visconti R, Monica RD, Grieco D. Cell cycle checkpoint in cancer: a therapeutically targetable double-edged sword. J Exp Clin Cancer Res. 2016. Vol 35: p153." }, { "code": null, "e": 9757, "s": 9582, "text": "[12] Milunović-Jevtić A, Mooney P, et al. Centrosomal clustering contributes to chromosomal instability and cancer. Current Opinion in Biotechnology. 2016 Vol 40: p113–118." }, { "code": null, "e": 9906, "s": 9757, "text": "[13] Bakhoum SF, Cantley LC. The Multifaceted Role of Chromosomal Instability in Cancer and Its Microenvironment. Cell. 2018 Vol 174(6): p1347–1360." }, { "code": null, "e": 10015, "s": 9906, "text": "[14] Florian S, Mitchison TJ. Anti-Microtubule Drugs. Methods in Molecular Biology. 2016 Vol 1413: p403–411." }, { "code": null, "e": 10164, "s": 10015, "text": "[15] Steinmetz MO, Prota AE. Microtubule-Targeting Agents: Strategies To Hijack the Cytoskeleton. Trends in Cell Biology. 2018 Vol 28(10): p776–792." } ]
Different ways to create Pandas Dataframe - GeeksforGeeks
24 Dec, 2021 Pandas DataFrame is a 2-dimensional labeled data structure with columns of potentially different types. It is generally the most commonly used pandas object. Pandas DataFrame can be created in multiple ways. Let’s discuss different ways to create a DataFrame one by one.Method #1: Creating Pandas DataFrame from lists of lists. Python3 # Import pandas libraryimport pandas as pd # initialize list of listsdata = [['tom', 10], ['nick', 15], ['juli', 14]] # Create the pandas DataFramedf = pd.DataFrame(data, columns = ['Name', 'Age']) # print dataframe.df Output: YouTubeGeeksforGeeks502K subscribersDifferent Ways to Create a 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 / 12:54•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=dEHJmn6p39M" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div> Method #2: Creating DataFrame from dict of narray/listsTo create DataFrame from dict of narray/list, all the narray must be of same length. If index is passed then the length index should be equal to the length of arrays. If no index is passed, then by default, index will be range(n) where n is the array length. Python3 # Python code demonstrate creating# DataFrame from dict narray / lists# By default addresses. import pandas as pd # initialize data of lists.data = {'Name':['Tom', 'nick', 'krish', 'jack'], 'Age':[20, 21, 19, 18]} # Create DataFramedf = pd.DataFrame(data) # Print the output.df Output: Method #3: Creates a indexes DataFrame using arrays. Python3 # Python code demonstrate creating# pandas DataFrame with indexed by # DataFrame using arrays.import pandas as pd # initialize data of lists.data = {'Name':['Tom', 'Jack', 'nick', 'juli'], 'marks':[99, 98, 95, 90]} # Creates pandas DataFrame.df = pd.DataFrame(data, index =['rank1', 'rank2', 'rank3', 'rank4']) # print the datadf Output: Method #4: Creating Dataframe from list of dictsPandas DataFrame can be created by passing lists of dictionaries as a input data. By default dictionary keys taken as columns. Python3 # Python code demonstrate how to create# Pandas DataFrame by lists of dicts.import pandas as pd # Initialize data to lists.data = [{'a': 1, 'b': 2, 'c':3}, {'a':10, 'b': 20, 'c': 30}] # Creates DataFrame.df = pd.DataFrame(data) # Print the datadf Output: Another example to create pandas DataFrame by passing lists of dictionaries and row indexes. Python3 # Python code demonstrate to create# Pandas DataFrame by passing lists of# Dictionaries and row indices.import pandas as pd # Initialize data of listsdata = [{'b': 2, 'c':3}, {'a': 10, 'b': 20, 'c': 30}] # Creates pandas DataFrame by passing# Lists of dictionaries and row index.df = pd.DataFrame(data, index =['first', 'second']) # Print the datadf Output: Another example to create pandas DataFrame from lists of dictionaries with both row index as well as column index. Python3 # Python code demonstrate to create a# Pandas DataFrame with lists of# dictionaries as well as# row and column indexes. import pandas as pd # Initialize lists data.data = [{'a': 1, 'b': 2}, {'a': 5, 'b': 10, 'c': 20}] # With two column indices, values same# as dictionary keysdf1 = pd.DataFrame(data, index =['first', 'second'], columns =['a', 'b']) # With two column indices with# one index with other namedf2 = pd.DataFrame(data, index =['first', 'second'], columns =['a', 'b1']) # print for first data frameprint (df1, "\n") # Print for second DataFrame.print (df2) Output: Method #5: Creating DataFrame using zip() function.Two lists can be merged by using list(zip()) function. Now, create the pandas DataFrame by calling pd.DataFrame() function. Python3 # Python program to demonstrate creating# pandas Datadaframe from lists using zip. import pandas as pd # List1Name = ['tom', 'krish', 'nick', 'juli'] # List2Age = [25, 30, 26, 22] # get the list of tuples from two lists.# and merge them by using zip().list_of_tuples = list(zip(Name, Age)) # Assign data to tuples.list_of_tuples # Converting lists of tuples into# pandas Dataframe.df = pd.DataFrame(list_of_tuples, columns = ['Name', 'Age']) # Print data.df Output: Method #6: Creating DataFrame from Dicts of series.To create DataFrame from Dicts of series, dictionary can be passed to form a DataFrame. The resultant index is the union of all the series of passed indexed. Python3 # Python code demonstrate creating# Pandas Dataframe from Dicts of series. import pandas as pd # Initialize data to Dicts of series.d = {'one' : pd.Series([10, 20, 30, 40], index =['a', 'b', 'c', 'd']), 'two' : pd.Series([10, 20, 30, 40], index =['a', 'b', 'c', 'd'])} # creates Dataframe.df = pd.DataFrame(d) # print the data.df Output: anikaseth98 rajeev0719singh chhabradhanvi simranarora5sos Picked Python pandas-dataFrame Python-pandas Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Enumerate() in Python How to Install PIP on Windows ? Iterate over a list in Python Create a Pandas DataFrame from Lists Reading and Writing to text files in Python *args and **kwargs in Python sum() function in Python How to drop one or multiple columns in Pandas Dataframe How To Convert Python Dictionary To JSON?
[ { "code": null, "e": 24902, "s": 24874, "text": "\n24 Dec, 2021" }, { "code": null, "e": 25231, "s": 24902, "text": "Pandas DataFrame is a 2-dimensional labeled data structure with columns of potentially different types. It is generally the most commonly used pandas object. Pandas DataFrame can be created in multiple ways. Let’s discuss different ways to create a DataFrame one by one.Method #1: Creating Pandas DataFrame from lists of lists. " }, { "code": null, "e": 25239, "s": 25231, "text": "Python3" }, { "code": "# Import pandas libraryimport pandas as pd # initialize list of listsdata = [['tom', 10], ['nick', 15], ['juli', 14]] # Create the pandas DataFramedf = pd.DataFrame(data, columns = ['Name', 'Age']) # print dataframe.df", "e": 25458, "s": 25239, "text": null }, { "code": null, "e": 25468, "s": 25458, "text": "Output: " }, { "code": null, "e": 26313, "s": 25470, "text": "YouTubeGeeksforGeeks502K subscribersDifferent Ways to Create a 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 / 12:54•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=dEHJmn6p39M\" 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": 26628, "s": 26313, "text": "Method #2: Creating DataFrame from dict of narray/listsTo create DataFrame from dict of narray/list, all the narray must be of same length. If index is passed then the length index should be equal to the length of arrays. If no index is passed, then by default, index will be range(n) where n is the array length. " }, { "code": null, "e": 26636, "s": 26628, "text": "Python3" }, { "code": "# Python code demonstrate creating# DataFrame from dict narray / lists# By default addresses. import pandas as pd # initialize data of lists.data = {'Name':['Tom', 'nick', 'krish', 'jack'], 'Age':[20, 21, 19, 18]} # Create DataFramedf = pd.DataFrame(data) # Print the output.df", "e": 26921, "s": 26636, "text": null }, { "code": null, "e": 26931, "s": 26921, "text": "Output: " }, { "code": null, "e": 26987, "s": 26931, "text": " Method #3: Creates a indexes DataFrame using arrays. " }, { "code": null, "e": 26995, "s": 26987, "text": "Python3" }, { "code": "# Python code demonstrate creating# pandas DataFrame with indexed by # DataFrame using arrays.import pandas as pd # initialize data of lists.data = {'Name':['Tom', 'Jack', 'nick', 'juli'], 'marks':[99, 98, 95, 90]} # Creates pandas DataFrame.df = pd.DataFrame(data, index =['rank1', 'rank2', 'rank3', 'rank4']) # print the datadf", "e": 27425, "s": 26995, "text": null }, { "code": null, "e": 27435, "s": 27425, "text": "Output: " }, { "code": null, "e": 27613, "s": 27435, "text": " Method #4: Creating Dataframe from list of dictsPandas DataFrame can be created by passing lists of dictionaries as a input data. By default dictionary keys taken as columns. " }, { "code": null, "e": 27621, "s": 27613, "text": "Python3" }, { "code": "# Python code demonstrate how to create# Pandas DataFrame by lists of dicts.import pandas as pd # Initialize data to lists.data = [{'a': 1, 'b': 2, 'c':3}, {'a':10, 'b': 20, 'c': 30}] # Creates DataFrame.df = pd.DataFrame(data) # Print the datadf", "e": 27875, "s": 27621, "text": null }, { "code": null, "e": 27885, "s": 27875, "text": "Output: " }, { "code": null, "e": 27979, "s": 27885, "text": "Another example to create pandas DataFrame by passing lists of dictionaries and row indexes. " }, { "code": null, "e": 27987, "s": 27979, "text": "Python3" }, { "code": "# Python code demonstrate to create# Pandas DataFrame by passing lists of# Dictionaries and row indices.import pandas as pd # Initialize data of listsdata = [{'b': 2, 'c':3}, {'a': 10, 'b': 20, 'c': 30}] # Creates pandas DataFrame by passing# Lists of dictionaries and row index.df = pd.DataFrame(data, index =['first', 'second']) # Print the datadf", "e": 28337, "s": 27987, "text": null }, { "code": null, "e": 28347, "s": 28337, "text": "Output: " }, { "code": null, "e": 28463, "s": 28347, "text": "Another example to create pandas DataFrame from lists of dictionaries with both row index as well as column index. " }, { "code": null, "e": 28471, "s": 28463, "text": "Python3" }, { "code": "# Python code demonstrate to create a# Pandas DataFrame with lists of# dictionaries as well as# row and column indexes. import pandas as pd # Initialize lists data.data = [{'a': 1, 'b': 2}, {'a': 5, 'b': 10, 'c': 20}] # With two column indices, values same# as dictionary keysdf1 = pd.DataFrame(data, index =['first', 'second'], columns =['a', 'b']) # With two column indices with# one index with other namedf2 = pd.DataFrame(data, index =['first', 'second'], columns =['a', 'b1']) # print for first data frameprint (df1, \"\\n\") # Print for second DataFrame.print (df2)", "e": 29153, "s": 28471, "text": null }, { "code": null, "e": 29163, "s": 29153, "text": "Output: " }, { "code": null, "e": 29341, "s": 29163, "text": " Method #5: Creating DataFrame using zip() function.Two lists can be merged by using list(zip()) function. Now, create the pandas DataFrame by calling pd.DataFrame() function. " }, { "code": null, "e": 29349, "s": 29341, "text": "Python3" }, { "code": "# Python program to demonstrate creating# pandas Datadaframe from lists using zip. import pandas as pd # List1Name = ['tom', 'krish', 'nick', 'juli'] # List2Age = [25, 30, 26, 22] # get the list of tuples from two lists.# and merge them by using zip().list_of_tuples = list(zip(Name, Age)) # Assign data to tuples.list_of_tuples # Converting lists of tuples into# pandas Dataframe.df = pd.DataFrame(list_of_tuples, columns = ['Name', 'Age']) # Print data.df", "e": 29839, "s": 29349, "text": null }, { "code": null, "e": 29849, "s": 29839, "text": "Output: " }, { "code": null, "e": 30060, "s": 29849, "text": " Method #6: Creating DataFrame from Dicts of series.To create DataFrame from Dicts of series, dictionary can be passed to form a DataFrame. The resultant index is the union of all the series of passed indexed. " }, { "code": null, "e": 30068, "s": 30060, "text": "Python3" }, { "code": "# Python code demonstrate creating# Pandas Dataframe from Dicts of series. import pandas as pd # Initialize data to Dicts of series.d = {'one' : pd.Series([10, 20, 30, 40], index =['a', 'b', 'c', 'd']), 'two' : pd.Series([10, 20, 30, 40], index =['a', 'b', 'c', 'd'])} # creates Dataframe.df = pd.DataFrame(d) # print the data.df", "e": 30448, "s": 30068, "text": null }, { "code": null, "e": 30458, "s": 30448, "text": "Output: " }, { "code": null, "e": 30472, "s": 30460, "text": "anikaseth98" }, { "code": null, "e": 30488, "s": 30472, "text": "rajeev0719singh" }, { "code": null, "e": 30502, "s": 30488, "text": "chhabradhanvi" }, { "code": null, "e": 30518, "s": 30502, "text": "simranarora5sos" }, { "code": null, "e": 30525, "s": 30518, "text": "Picked" }, { "code": null, "e": 30549, "s": 30525, "text": "Python pandas-dataFrame" }, { "code": null, "e": 30563, "s": 30549, "text": "Python-pandas" }, { "code": null, "e": 30570, "s": 30563, "text": "Python" }, { "code": null, "e": 30668, "s": 30570, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30686, "s": 30668, "text": "Python Dictionary" }, { "code": null, "e": 30708, "s": 30686, "text": "Enumerate() in Python" }, { "code": null, "e": 30740, "s": 30708, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 30770, "s": 30740, "text": "Iterate over a list in Python" }, { "code": null, "e": 30807, "s": 30770, "text": "Create a Pandas DataFrame from Lists" }, { "code": null, "e": 30851, "s": 30807, "text": "Reading and Writing to text files in Python" }, { "code": null, "e": 30880, "s": 30851, "text": "*args and **kwargs in Python" }, { "code": null, "e": 30905, "s": 30880, "text": "sum() function in Python" }, { "code": null, "e": 30961, "s": 30905, "text": "How to drop one or multiple columns in Pandas Dataframe" } ]
Anshuman's Favourite Number | Practice | GeeksforGeeks
You are given an integer input N and you have to find whether it is the sum or the difference of the integer 5. (5+5, 5+5+5, 5-5,5-5-5+5+5.....) Example 1: Input: N = 10 Output: YES Explanation: Because 10 can be written as a sum of 5+5. Example 2: Input: N = 9 Output: NO Explanation: 9 can not be written in the above form. Your Task: You don't need to read input or print anything. Your task is to complete the function isValid() which takes an integer N and returns "YES" or "NO". Expected Time Complexity: O(1) Expected Auxiliary Space: O(1) Constraints: -109<=N<=109 0 sonkambaleujjawal2 months ago One Line Answerer C++ return N%5==0 ? "YES" : "NO"; +2 aadeshabhigyan093 months ago class Solution{ public: string isValid(long long N){ // code here if(N%5 == 0) { return "YES"; } // No need to be confused by the pattern here as any number got on adding or subtracting // 5 will be a multiple of 5 return "NO"; }}; 0 amiransarimy3 months ago One Line Python Solutions class Solution: def isValid (self,N): return "YES" if N%5 == 0 else "NO" 0 poulamibera5193 months ago class Solution{ public: string isValid(long long N){ // code here if(N%5==0) return "YES"; else return "NO"; }}; 0 mayank20214 months ago #C++ class Solution{ public: string isValid(long long N){ string S= (N%5==0) ? "YES" : "NO"; return S; }}; 0 shruti038btmae206 months ago C++ SOLUTION:- // code here if(N%5==0) { return "YES"; } else return "NO"; 0 Anjali Jaiswal9 months ago Anjali Jaiswal string isValid(long long N){ // code here if(N%5==0) return "YES"; return "NO"; } 0 Akash Gupta10 months ago Akash Gupta Execution Time 0.01 if(N%5==0) { cout<<"YES"; } else { cout<<"NO"; } } 0 Manav Saxena11 months ago Manav Saxena class Solution{ public: string isValid(long long N){ string s1="YES"; string s2="NO"; if(N%5==0){ return s1; }else{ return s2; } }}; -1 Gurucharan Rajput1 year ago Gurucharan Rajput java solution return N%5==0 ?"YES":"NO"; 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": 383, "s": 238, "text": "You are given an integer input N and you have to find whether it is the sum or the difference of the integer 5. (5+5, 5+5+5, 5-5,5-5-5+5+5.....)" }, { "code": null, "e": 396, "s": 385, "text": "Example 1:" }, { "code": null, "e": 479, "s": 396, "text": "Input:\nN = 10\nOutput:\nYES\nExplanation:\nBecause 10 can be \nwritten as a sum of 5+5." }, { "code": null, "e": 494, "s": 483, "text": "Example 2:" }, { "code": null, "e": 571, "s": 494, "text": "Input:\nN = 9\nOutput:\nNO\nExplanation:\n9 can not be written\nin the above form." }, { "code": null, "e": 586, "s": 575, "text": "Your Task:" }, { "code": null, "e": 734, "s": 586, "text": "You don't need to read input or print anything. Your task is to complete the function isValid() which takes an integer N and returns \"YES\" or \"NO\"." }, { "code": null, "e": 798, "s": 736, "text": "Expected Time Complexity: O(1)\nExpected Auxiliary Space: O(1)" }, { "code": null, "e": 826, "s": 800, "text": "Constraints:\n-109<=N<=109" }, { "code": null, "e": 828, "s": 826, "text": "0" }, { "code": null, "e": 858, "s": 828, "text": "sonkambaleujjawal2 months ago" }, { "code": null, "e": 880, "s": 858, "text": "One Line Answerer C++" }, { "code": null, "e": 910, "s": 880, "text": "return N%5==0 ? \"YES\" : \"NO\";" }, { "code": null, "e": 913, "s": 910, "text": "+2" }, { "code": null, "e": 942, "s": 913, "text": "aadeshabhigyan093 months ago" }, { "code": null, "e": 1232, "s": 942, "text": "class Solution{ public: string isValid(long long N){ // code here if(N%5 == 0) { return \"YES\"; } // No need to be confused by the pattern here as any number got on adding or subtracting // 5 will be a multiple of 5 return \"NO\"; }};" }, { "code": null, "e": 1234, "s": 1232, "text": "0" }, { "code": null, "e": 1259, "s": 1234, "text": "amiransarimy3 months ago" }, { "code": null, "e": 1285, "s": 1259, "text": "One Line Python Solutions" }, { "code": null, "e": 1370, "s": 1287, "text": "class Solution:\n def isValid (self,N):\n return \"YES\" if N%5 == 0 else \"NO\"" }, { "code": null, "e": 1372, "s": 1370, "text": "0" }, { "code": null, "e": 1399, "s": 1372, "text": "poulamibera5193 months ago" }, { "code": null, "e": 1564, "s": 1399, "text": "class Solution{ public: string isValid(long long N){ // code here if(N%5==0) return \"YES\"; else return \"NO\"; }};" }, { "code": null, "e": 1566, "s": 1564, "text": "0" }, { "code": null, "e": 1589, "s": 1566, "text": "mayank20214 months ago" }, { "code": null, "e": 1594, "s": 1589, "text": "#C++" }, { "code": null, "e": 1732, "s": 1594, "text": "class Solution{ public: string isValid(long long N){ string S= (N%5==0) ? \"YES\" : \"NO\"; return S; }};" }, { "code": null, "e": 1734, "s": 1732, "text": "0" }, { "code": null, "e": 1763, "s": 1734, "text": "shruti038btmae206 months ago" }, { "code": null, "e": 1778, "s": 1763, "text": "C++ SOLUTION:-" }, { "code": null, "e": 1889, "s": 1778, "text": " // code here if(N%5==0) { return \"YES\"; } else return \"NO\";" }, { "code": null, "e": 1891, "s": 1889, "text": "0" }, { "code": null, "e": 1918, "s": 1891, "text": "Anjali Jaiswal9 months ago" }, { "code": null, "e": 1933, "s": 1918, "text": "Anjali Jaiswal" }, { "code": null, "e": 2048, "s": 1933, "text": " string isValid(long long N){ // code here if(N%5==0) return \"YES\"; return \"NO\"; }" }, { "code": null, "e": 2050, "s": 2048, "text": "0" }, { "code": null, "e": 2075, "s": 2050, "text": "Akash Gupta10 months ago" }, { "code": null, "e": 2087, "s": 2075, "text": "Akash Gupta" }, { "code": null, "e": 2107, "s": 2087, "text": "Execution Time 0.01" }, { "code": null, "e": 2221, "s": 2107, "text": " if(N%5==0) { cout<<\"YES\"; } else { cout<<\"NO\"; } }" }, { "code": null, "e": 2223, "s": 2221, "text": "0" }, { "code": null, "e": 2249, "s": 2223, "text": "Manav Saxena11 months ago" }, { "code": null, "e": 2262, "s": 2249, "text": "Manav Saxena" }, { "code": null, "e": 2467, "s": 2262, "text": "class Solution{ public: string isValid(long long N){ string s1=\"YES\"; string s2=\"NO\"; if(N%5==0){ return s1; }else{ return s2; } }};" }, { "code": null, "e": 2470, "s": 2467, "text": "-1" }, { "code": null, "e": 2498, "s": 2470, "text": "Gurucharan Rajput1 year ago" }, { "code": null, "e": 2516, "s": 2498, "text": "Gurucharan Rajput" }, { "code": null, "e": 2558, "s": 2516, "text": "java solution return N%5==0 ?\"YES\":\"NO\";" }, { "code": null, "e": 2704, "s": 2558, "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": 2740, "s": 2704, "text": " Login to access your submissions. " }, { "code": null, "e": 2750, "s": 2740, "text": "\nProblem\n" }, { "code": null, "e": 2760, "s": 2750, "text": "\nContest\n" }, { "code": null, "e": 2823, "s": 2760, "text": "Reset the IDE using the second button on the top right corner." }, { "code": null, "e": 2971, "s": 2823, "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": 3179, "s": 2971, "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": 3285, "s": 3179, "text": "You can access the hints to get an idea about what is expected of you as well as the final solution code." } ]
Count all possible N-length vowel permutations that can be generated based on the given conditions - GeeksforGeeks
21 Apr, 2021 Given an integer N, the task is to count the number of N-length strings consisting of lowercase vowels that can be generated based the following conditions: Each ‘a’ may only be followed by an ‘e’. Each ‘e’ may only be followed by an ‘a’ or an ‘i’. Each ‘i’ may not be followed by another ‘i’. Each ‘o’ may only be followed by an ‘i’ or a ‘u’. Each ‘u’ may only be followed by an ‘a’. Examples: Input: N = 1Output: 5Explanation: All strings that can be formed are: “a”, “e”, “i”, “o” and “u”. Input: N = 2Output: 10Explanation: All strings that can be formed are: “ae”, “ea”, “ei”, “ia”, “ie”, “io”, “iu”, “oi”, “ou” and “ua”. Approach: The idea to solve this problem is to visualize this as a Graph Problem. From the given rules a directed graph can be constructed, where an edge from u to v means that v can be immediately written after u in the resultant strings. The problem reduces to finding the number of N-length paths in the constructed directed graph. Follow the steps below to solve the problem: Let the vowels a, e, i, o, u be numbered as 0, 1, 2, 3, 4 respectively, and using the dependencies shown in the given graph, convert the graph into an adjacency list relation where the index signifies the vowel and the list at that index signifies an edge from that index to the characters given in the list. Initialize a 2D array dp[N + 1][5] where dp[N][char] denotes the number of directed paths of length N which end at a particular vertex char. Initialize dp[i][char] for all the characters as 1, since a string of length 1 will only consist of one vowel in the string. For all possible lengths, say i, traverse over the directed edges using variable u and perform the following steps:Update the value of dp[i + 1][u] as 0.Traverse the adjacency list of the node u and increment the value of dp[i][u] by dp[i][v], that stores the sum of all the values such that there is a directed edge from node u to node v. Update the value of dp[i + 1][u] as 0. Traverse the adjacency list of the node u and increment the value of dp[i][u] by dp[i][v], that stores the sum of all the values such that there is a directed edge from node u to node v. After completing the above steps, the sum of all the values dp[N][i], where i belongs to the range [0, 5), will give the total number of vowel permutations. Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ program for the above approach#include <bits/stdc++.h>using namespace std; // Function to find the number of// vowel permutations possibleint countVowelPermutation(int n){ // To avoid the large output value int MOD = (int)(1e9 + 7); // Initialize 2D dp array long dp[n + 1][5]; // Initialize dp[1][i] as 1 since // string of length 1 will consist // of only one vowel in the string for(int i = 0; i < 5; i++) { dp[1][i] = 1; } // Directed graph using the // adjacency matrix vector<vector<int>> relation = { { 1 }, { 0, 2 }, { 0, 1, 3, 4 }, { 2, 4 }, { 0 } }; // Iterate over the range [1, N] for(int i = 1; i < n; i++) { // Traverse the directed graph for(int u = 0; u < 5; u++) { dp[i + 1][u] = 0; // Traversing the list for(int v : relation[u]) { // Update dp[i + 1][u] dp[i + 1][u] += dp[i][v] % MOD; } } } // Stores total count of permutations long ans = 0; for(int i = 0; i < 5; i++) { ans = (ans + dp[n][i]) % MOD; } // Return count of permutations return (int)ans;} // Driver codeint main(){ int N = 2; cout << countVowelPermutation(N);} // This code is contributed by Mohit kumar 29 // Java program for the above approach import java.io.*;import java.util.*;class GFG { // Function to find the number of // vowel permutations possible public static int countVowelPermutation(int n) { // To avoid the large output value int MOD = (int)(1e9 + 7); // Initialize 2D dp array long[][] dp = new long[n + 1][5]; // Initialize dp[1][i] as 1 since // string of length 1 will consist // of only one vowel in the string for (int i = 0; i < 5; i++) { dp[1][i] = 1; } // Directed graph using the // adjacency matrix int[][] relation = new int[][] { { 1 }, { 0, 2 }, { 0, 1, 3, 4 }, { 2, 4 }, { 0 } }; // Iterate over the range [1, N] for (int i = 1; i < n; i++) { // Traverse the directed graph for (int u = 0; u < 5; u++) { dp[i + 1][u] = 0; // Traversing the list for (int v : relation[u]) { // Update dp[i + 1][u] dp[i + 1][u] += dp[i][v] % MOD; } } } // Stores total count of permutations long ans = 0; for (int i = 0; i < 5; i++) { ans = (ans + dp[n][i]) % MOD; } // Return count of permutations return (int)ans; } // Driver Code public static void main(String[] args) { int N = 2; System.out.println( countVowelPermutation(N)); }} # Python 3 program for the above approach # Function to find the number of# vowel permutations possibledef countVowelPermutation(n): # To avoid the large output value MOD = 1e9 + 7 # Initialize 2D dp array dp = [[0 for i in range(5)] for j in range(n + 1)] # Initialize dp[1][i] as 1 since # string of length 1 will consist # of only one vowel in the string for i in range(5): dp[1][i] = 1 # Directed graph using the # adjacency matrix relation = [[1],[0, 2], [0, 1, 3, 4], [2, 4],[0]] # Iterate over the range [1, N] for i in range(1, n, 1): # Traverse the directed graph for u in range(5): dp[i + 1][u] = 0 # Traversing the list for v in relation[u]: # Update dp[i + 1][u] dp[i + 1][u] += dp[i][v] % MOD # Stores total count of permutations ans = 0 for i in range(5): ans = (ans + dp[n][i]) % MOD # Return count of permutations return int(ans) # Driver codeif __name__ == '__main__': N = 2 print(countVowelPermutation(N)) # This code is contributed by bgangwar59. // C# program to find absolute difference// between the sum of all odd frequenct and// even frequent elements in an arrayusing System;using System.Collections.Generic;class GFG { // Function to find the number of // vowel permutations possible static int countVowelPermutation(int n) { // To avoid the large output value int MOD = (int)(1e9 + 7); // Initialize 2D dp array long[,] dp = new long[n + 1, 5]; // Initialize dp[1][i] as 1 since // string of length 1 will consist // of only one vowel in the string for (int i = 0; i < 5; i++) { dp[1, i] = 1; } // Directed graph using the // adjacency matrix List<List<int>> relation = new List<List<int>>(); relation.Add(new List<int> { 1 }); relation.Add(new List<int> { 0, 2 }); relation.Add(new List<int> { 0, 1, 3, 4 }); relation.Add(new List<int> { 2, 4 }); relation.Add(new List<int> { 0 }); // Iterate over the range [1, N] for (int i = 1; i < n; i++) { // Traverse the directed graph for (int u = 0; u < 5; u++) { dp[i + 1, u] = 0; // Traversing the list foreach(int v in relation[u]) { // Update dp[i + 1][u] dp[i + 1, u] += dp[i, v] % MOD; } } } // Stores total count of permutations long ans = 0; for (int i = 0; i < 5; i++) { ans = (ans + dp[n, i]) % MOD; } // Return count of permutations return (int)ans; } // Driver code static void Main() { int N = 2; Console.WriteLine(countVowelPermutation(N)); }} // This code is contributed by divyesh072019. <script> // JavaScript program to implement// the above approach // Function to find the number of // vowel permutations possible function countVowelPermutation(n) { // To avoid the large output value let MOD = (1e9 + 7); // Initialize 2D dp array let dp = new Array(n + 1); // Loop to create 2D array using 1D array for (var i = 0; i < dp.length; i++) { dp[i] = new Array(2); } // Initialize dp[1][i] as 1 since // string of length 1 will consist // of only one vowel in the string for (let i = 0; i < 5; i++) { dp[1][i] = 1; } // Directed graph using the // adjacency matrix let relation = [ [ 1 ], [ 0, 2 ], [ 0, 1, 3, 4 ], [ 2, 4 ], [ 0 ] ]; // Iterate over the range [1, N] for (let i = 1; i < n; i++) { // Traverse the directed graph for (let u = 0; u < 5; u++) { dp[i + 1][u] = 0; // Traversing the list for (let v in relation[u]) { // Update dp[i + 1][u] dp[i + 1][u] += dp[i][v] % MOD; } } } // Stores total count of permutations let ans = 0; for (let i = 0; i < 5; i++) { ans = (ans + dp[n][i]) % MOD; } // Return count of permutations return ans; } // Driver code let N = 2; document.write( countVowelPermutation(N)); </script> 10 Time Complexity: O(N)Auxiliary Space: O(N) mohit kumar 29 khushboogoyal499 bgangwar59 divyesh072019 target_2 Permutation and Combination Combinatorial Dynamic Programming Graph Mathematical Recursion Strings Strings Dynamic Programming Mathematical Recursion Graph Combinatorial Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python program to get all subsets of given size of a set Lexicographic rank of a string Make all combinations of size k Print all subsets of given size of a set Print all permutations in sorted (lexicographic) order 0-1 Knapsack Problem | DP-10 Program for Fibonacci numbers Largest Sum Contiguous Subarray Longest Common Subsequence | DP-4 Bellman–Ford Algorithm | DP-23
[ { "code": null, "e": 25460, "s": 25432, "text": "\n21 Apr, 2021" }, { "code": null, "e": 25617, "s": 25460, "text": "Given an integer N, the task is to count the number of N-length strings consisting of lowercase vowels that can be generated based the following conditions:" }, { "code": null, "e": 25658, "s": 25617, "text": "Each ‘a’ may only be followed by an ‘e’." }, { "code": null, "e": 25709, "s": 25658, "text": "Each ‘e’ may only be followed by an ‘a’ or an ‘i’." }, { "code": null, "e": 25754, "s": 25709, "text": "Each ‘i’ may not be followed by another ‘i’." }, { "code": null, "e": 25804, "s": 25754, "text": "Each ‘o’ may only be followed by an ‘i’ or a ‘u’." }, { "code": null, "e": 25845, "s": 25804, "text": "Each ‘u’ may only be followed by an ‘a’." }, { "code": null, "e": 25855, "s": 25845, "text": "Examples:" }, { "code": null, "e": 25953, "s": 25855, "text": "Input: N = 1Output: 5Explanation: All strings that can be formed are: “a”, “e”, “i”, “o” and “u”." }, { "code": null, "e": 26087, "s": 25953, "text": "Input: N = 2Output: 10Explanation: All strings that can be formed are: “ae”, “ea”, “ei”, “ia”, “ie”, “io”, “iu”, “oi”, “ou” and “ua”." }, { "code": null, "e": 26467, "s": 26087, "text": "Approach: The idea to solve this problem is to visualize this as a Graph Problem. From the given rules a directed graph can be constructed, where an edge from u to v means that v can be immediately written after u in the resultant strings. The problem reduces to finding the number of N-length paths in the constructed directed graph. Follow the steps below to solve the problem:" }, { "code": null, "e": 26776, "s": 26467, "text": "Let the vowels a, e, i, o, u be numbered as 0, 1, 2, 3, 4 respectively, and using the dependencies shown in the given graph, convert the graph into an adjacency list relation where the index signifies the vowel and the list at that index signifies an edge from that index to the characters given in the list." }, { "code": null, "e": 26917, "s": 26776, "text": "Initialize a 2D array dp[N + 1][5] where dp[N][char] denotes the number of directed paths of length N which end at a particular vertex char." }, { "code": null, "e": 27042, "s": 26917, "text": "Initialize dp[i][char] for all the characters as 1, since a string of length 1 will only consist of one vowel in the string." }, { "code": null, "e": 27382, "s": 27042, "text": "For all possible lengths, say i, traverse over the directed edges using variable u and perform the following steps:Update the value of dp[i + 1][u] as 0.Traverse the adjacency list of the node u and increment the value of dp[i][u] by dp[i][v], that stores the sum of all the values such that there is a directed edge from node u to node v." }, { "code": null, "e": 27421, "s": 27382, "text": "Update the value of dp[i + 1][u] as 0." }, { "code": null, "e": 27608, "s": 27421, "text": "Traverse the adjacency list of the node u and increment the value of dp[i][u] by dp[i][v], that stores the sum of all the values such that there is a directed edge from node u to node v." }, { "code": null, "e": 27765, "s": 27608, "text": "After completing the above steps, the sum of all the values dp[N][i], where i belongs to the range [0, 5), will give the total number of vowel permutations." }, { "code": null, "e": 27816, "s": 27765, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 27820, "s": 27816, "text": "C++" }, { "code": null, "e": 27825, "s": 27820, "text": "Java" }, { "code": null, "e": 27833, "s": 27825, "text": "Python3" }, { "code": null, "e": 27836, "s": 27833, "text": "C#" }, { "code": null, "e": 27847, "s": 27836, "text": "Javascript" }, { "code": "// C++ program for the above approach#include <bits/stdc++.h>using namespace std; // Function to find the number of// vowel permutations possibleint countVowelPermutation(int n){ // To avoid the large output value int MOD = (int)(1e9 + 7); // Initialize 2D dp array long dp[n + 1][5]; // Initialize dp[1][i] as 1 since // string of length 1 will consist // of only one vowel in the string for(int i = 0; i < 5; i++) { dp[1][i] = 1; } // Directed graph using the // adjacency matrix vector<vector<int>> relation = { { 1 }, { 0, 2 }, { 0, 1, 3, 4 }, { 2, 4 }, { 0 } }; // Iterate over the range [1, N] for(int i = 1; i < n; i++) { // Traverse the directed graph for(int u = 0; u < 5; u++) { dp[i + 1][u] = 0; // Traversing the list for(int v : relation[u]) { // Update dp[i + 1][u] dp[i + 1][u] += dp[i][v] % MOD; } } } // Stores total count of permutations long ans = 0; for(int i = 0; i < 5; i++) { ans = (ans + dp[n][i]) % MOD; } // Return count of permutations return (int)ans;} // Driver codeint main(){ int N = 2; cout << countVowelPermutation(N);} // This code is contributed by Mohit kumar 29", "e": 29227, "s": 27847, "text": null }, { "code": "// Java program for the above approach import java.io.*;import java.util.*;class GFG { // Function to find the number of // vowel permutations possible public static int countVowelPermutation(int n) { // To avoid the large output value int MOD = (int)(1e9 + 7); // Initialize 2D dp array long[][] dp = new long[n + 1][5]; // Initialize dp[1][i] as 1 since // string of length 1 will consist // of only one vowel in the string for (int i = 0; i < 5; i++) { dp[1][i] = 1; } // Directed graph using the // adjacency matrix int[][] relation = new int[][] { { 1 }, { 0, 2 }, { 0, 1, 3, 4 }, { 2, 4 }, { 0 } }; // Iterate over the range [1, N] for (int i = 1; i < n; i++) { // Traverse the directed graph for (int u = 0; u < 5; u++) { dp[i + 1][u] = 0; // Traversing the list for (int v : relation[u]) { // Update dp[i + 1][u] dp[i + 1][u] += dp[i][v] % MOD; } } } // Stores total count of permutations long ans = 0; for (int i = 0; i < 5; i++) { ans = (ans + dp[n][i]) % MOD; } // Return count of permutations return (int)ans; } // Driver Code public static void main(String[] args) { int N = 2; System.out.println( countVowelPermutation(N)); }}", "e": 30775, "s": 29227, "text": null }, { "code": "# Python 3 program for the above approach # Function to find the number of# vowel permutations possibledef countVowelPermutation(n): # To avoid the large output value MOD = 1e9 + 7 # Initialize 2D dp array dp = [[0 for i in range(5)] for j in range(n + 1)] # Initialize dp[1][i] as 1 since # string of length 1 will consist # of only one vowel in the string for i in range(5): dp[1][i] = 1 # Directed graph using the # adjacency matrix relation = [[1],[0, 2], [0, 1, 3, 4], [2, 4],[0]] # Iterate over the range [1, N] for i in range(1, n, 1): # Traverse the directed graph for u in range(5): dp[i + 1][u] = 0 # Traversing the list for v in relation[u]: # Update dp[i + 1][u] dp[i + 1][u] += dp[i][v] % MOD # Stores total count of permutations ans = 0 for i in range(5): ans = (ans + dp[n][i]) % MOD # Return count of permutations return int(ans) # Driver codeif __name__ == '__main__': N = 2 print(countVowelPermutation(N)) # This code is contributed by bgangwar59.", "e": 31941, "s": 30775, "text": null }, { "code": "// C# program to find absolute difference// between the sum of all odd frequenct and// even frequent elements in an arrayusing System;using System.Collections.Generic;class GFG { // Function to find the number of // vowel permutations possible static int countVowelPermutation(int n) { // To avoid the large output value int MOD = (int)(1e9 + 7); // Initialize 2D dp array long[,] dp = new long[n + 1, 5]; // Initialize dp[1][i] as 1 since // string of length 1 will consist // of only one vowel in the string for (int i = 0; i < 5; i++) { dp[1, i] = 1; } // Directed graph using the // adjacency matrix List<List<int>> relation = new List<List<int>>(); relation.Add(new List<int> { 1 }); relation.Add(new List<int> { 0, 2 }); relation.Add(new List<int> { 0, 1, 3, 4 }); relation.Add(new List<int> { 2, 4 }); relation.Add(new List<int> { 0 }); // Iterate over the range [1, N] for (int i = 1; i < n; i++) { // Traverse the directed graph for (int u = 0; u < 5; u++) { dp[i + 1, u] = 0; // Traversing the list foreach(int v in relation[u]) { // Update dp[i + 1][u] dp[i + 1, u] += dp[i, v] % MOD; } } } // Stores total count of permutations long ans = 0; for (int i = 0; i < 5; i++) { ans = (ans + dp[n, i]) % MOD; } // Return count of permutations return (int)ans; } // Driver code static void Main() { int N = 2; Console.WriteLine(countVowelPermutation(N)); }} // This code is contributed by divyesh072019.", "e": 33781, "s": 31941, "text": null }, { "code": "<script> // JavaScript program to implement// the above approach // Function to find the number of // vowel permutations possible function countVowelPermutation(n) { // To avoid the large output value let MOD = (1e9 + 7); // Initialize 2D dp array let dp = new Array(n + 1); // Loop to create 2D array using 1D array for (var i = 0; i < dp.length; i++) { dp[i] = new Array(2); } // Initialize dp[1][i] as 1 since // string of length 1 will consist // of only one vowel in the string for (let i = 0; i < 5; i++) { dp[1][i] = 1; } // Directed graph using the // adjacency matrix let relation = [ [ 1 ], [ 0, 2 ], [ 0, 1, 3, 4 ], [ 2, 4 ], [ 0 ] ]; // Iterate over the range [1, N] for (let i = 1; i < n; i++) { // Traverse the directed graph for (let u = 0; u < 5; u++) { dp[i + 1][u] = 0; // Traversing the list for (let v in relation[u]) { // Update dp[i + 1][u] dp[i + 1][u] += dp[i][v] % MOD; } } } // Stores total count of permutations let ans = 0; for (let i = 0; i < 5; i++) { ans = (ans + dp[n][i]) % MOD; } // Return count of permutations return ans; } // Driver code let N = 2; document.write( countVowelPermutation(N)); </script>", "e": 35372, "s": 33781, "text": null }, { "code": null, "e": 35375, "s": 35372, "text": "10" }, { "code": null, "e": 35420, "s": 35377, "text": "Time Complexity: O(N)Auxiliary Space: O(N)" }, { "code": null, "e": 35435, "s": 35420, "text": "mohit kumar 29" }, { "code": null, "e": 35452, "s": 35435, "text": "khushboogoyal499" }, { "code": null, "e": 35463, "s": 35452, "text": "bgangwar59" }, { "code": null, "e": 35477, "s": 35463, "text": "divyesh072019" }, { "code": null, "e": 35486, "s": 35477, "text": "target_2" }, { "code": null, "e": 35514, "s": 35486, "text": "Permutation and Combination" }, { "code": null, "e": 35528, "s": 35514, "text": "Combinatorial" }, { "code": null, "e": 35548, "s": 35528, "text": "Dynamic Programming" }, { "code": null, "e": 35554, "s": 35548, "text": "Graph" }, { "code": null, "e": 35567, "s": 35554, "text": "Mathematical" }, { "code": null, "e": 35577, "s": 35567, "text": "Recursion" }, { "code": null, "e": 35585, "s": 35577, "text": "Strings" }, { "code": null, "e": 35593, "s": 35585, "text": "Strings" }, { "code": null, "e": 35613, "s": 35593, "text": "Dynamic Programming" }, { "code": null, "e": 35626, "s": 35613, "text": "Mathematical" }, { "code": null, "e": 35636, "s": 35626, "text": "Recursion" }, { "code": null, "e": 35642, "s": 35636, "text": "Graph" }, { "code": null, "e": 35656, "s": 35642, "text": "Combinatorial" }, { "code": null, "e": 35754, "s": 35656, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 35811, "s": 35754, "text": "Python program to get all subsets of given size of a set" }, { "code": null, "e": 35842, "s": 35811, "text": "Lexicographic rank of a string" }, { "code": null, "e": 35874, "s": 35842, "text": "Make all combinations of size k" }, { "code": null, "e": 35915, "s": 35874, "text": "Print all subsets of given size of a set" }, { "code": null, "e": 35970, "s": 35915, "text": "Print all permutations in sorted (lexicographic) order" }, { "code": null, "e": 35999, "s": 35970, "text": "0-1 Knapsack Problem | DP-10" }, { "code": null, "e": 36029, "s": 35999, "text": "Program for Fibonacci numbers" }, { "code": null, "e": 36061, "s": 36029, "text": "Largest Sum Contiguous Subarray" }, { "code": null, "e": 36095, "s": 36061, "text": "Longest Common Subsequence | DP-4" } ]
Pycharm - Improving and Writing Code
PyCharm includes various standards for writing code with proper indentations valid for Python. This makes it interesting to improve the code standards and writing the complete code in PyCharm editor. Code completion in PyCharm is really unique. You can enhance it further using many other features. Note that the editor provides start and end of the code block. Consider a file named demo.py with the following code − message = 'GIEWIVrGMTLIVrHIQS' #encrypted message LETTERS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' for key in range(len(LETTERS)): translated = '' for symbol in message: if symbol in LETTERS: num = LETTERS.find(symbol) num = num - key if num < 0: num = num + len(LETTERS) translated = translated + LETTERS[num] else: translated = translated + symbol print('Hacking key #%s: %s' % (key, translated)) The code is completed using the following construct − If you press Ctrl + spacebar while this popup is on the screen, you can see more code completion options − PyCharm includes intent specific actions and the shortcut key for the same is Alt+Enter. The most important example of intentions at work is using language injection in strings. The screenshot given below shows the working of intention actions − Note that we can insert many different languages of intention actions in PyCharm Editor. 19 Lectures 59 mins Mustafa Mahmoud 19 Lectures 49 mins Pedro Planas Print Add Notes Bookmark this page
[ { "code": null, "e": 2299, "s": 2099, "text": "PyCharm includes various standards for writing code with proper indentations valid for Python. This makes it interesting to improve the code standards and writing the complete code in PyCharm editor." }, { "code": null, "e": 2517, "s": 2299, "text": "Code completion in PyCharm is really unique. You can enhance it further using many other features. Note that the editor provides start and end of the code block. Consider a file named demo.py with the following code −" }, { "code": null, "e": 2987, "s": 2517, "text": "message = 'GIEWIVrGMTLIVrHIQS' #encrypted message\nLETTERS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'\n\nfor key in range(len(LETTERS)):\n translated = ''\n\t\n for symbol in message:\n if symbol in LETTERS:\n num = LETTERS.find(symbol)\n num = num - key\n if num < 0:\n num = num + len(LETTERS)\n translated = translated + LETTERS[num]\n else:\n translated = translated + symbol\n print('Hacking key #%s: %s' % (key, translated))" }, { "code": null, "e": 3041, "s": 2987, "text": "The code is completed using the following construct −" }, { "code": null, "e": 3148, "s": 3041, "text": "If you press Ctrl + spacebar while this popup is on the screen, you can see more code completion options −" }, { "code": null, "e": 3326, "s": 3148, "text": "PyCharm includes intent specific actions and the shortcut key for the same is Alt+Enter. The most important example of intentions at work is using language injection in strings." }, { "code": null, "e": 3394, "s": 3326, "text": "The screenshot given below shows the working of intention actions −" }, { "code": null, "e": 3483, "s": 3394, "text": "Note that we can insert many different languages of intention actions in PyCharm Editor." }, { "code": null, "e": 3515, "s": 3483, "text": "\n 19 Lectures \n 59 mins\n" }, { "code": null, "e": 3532, "s": 3515, "text": " Mustafa Mahmoud" }, { "code": null, "e": 3564, "s": 3532, "text": "\n 19 Lectures \n 49 mins\n" }, { "code": null, "e": 3578, "s": 3564, "text": " Pedro Planas" }, { "code": null, "e": 3585, "s": 3578, "text": " Print" }, { "code": null, "e": 3596, "s": 3585, "text": " Add Notes" } ]
response.encoding – Python requests
01 Mar, 2020 Python requests are generally used to fetch the content from a particular resource URI. Whenever we make a request to a specified URI through Python, it returns a response object. Now, this response object would be used to access certain features such as content, headers, etc. This article revolves around how to check the response.encoding out of a response object. response.encoding returns the encoding used to decode response.content. Check more about encoding here – Python Strings encode() method To illustrate use of response.encoding, let’s ping API of Github. To run this script, you need to have Python and requests installed on your PC. Download and Install Python 3 Latest Version How to install requests in Python – For windows, linux, mac # import requests moduleimport requests # Making a get requestresponse = requests.get('https://api.github.com') # print responseprint(response) # print encoding of responseprint(response.encoding) Save above file as request.py and run using Python request.py Check that utf-8 at the start of the output, it shows that string is encoded and decoded using “utf-8”. There are many libraries to make an HTTP request in Python, which are httplib, urllib, httplib2, treq, etc., but requests is the one of the best with cool features. If any attribute of requests shows NULL, check the status code using below attribute. requests.status_code If status_code doesn’t lie in range of 200-29. You probably need to check method begin used for making a request + the url you are requesting for resources. Python-requests Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n01 Mar, 2020" }, { "code": null, "e": 532, "s": 28, "text": "Python requests are generally used to fetch the content from a particular resource URI. Whenever we make a request to a specified URI through Python, it returns a response object. Now, this response object would be used to access certain features such as content, headers, etc. This article revolves around how to check the response.encoding out of a response object. response.encoding returns the encoding used to decode response.content. Check more about encoding here – Python Strings encode() method" }, { "code": null, "e": 677, "s": 532, "text": "To illustrate use of response.encoding, let’s ping API of Github. To run this script, you need to have Python and requests installed on your PC." }, { "code": null, "e": 722, "s": 677, "text": "Download and Install Python 3 Latest Version" }, { "code": null, "e": 782, "s": 722, "text": "How to install requests in Python – For windows, linux, mac" }, { "code": "# import requests moduleimport requests # Making a get requestresponse = requests.get('https://api.github.com') # print responseprint(response) # print encoding of responseprint(response.encoding)", "e": 982, "s": 782, "text": null }, { "code": null, "e": 1026, "s": 982, "text": "Save above file as request.py and run using" }, { "code": null, "e": 1045, "s": 1026, "text": "Python request.py\n" }, { "code": null, "e": 1149, "s": 1045, "text": "Check that utf-8 at the start of the output, it shows that string is encoded and decoded using “utf-8”." }, { "code": null, "e": 1400, "s": 1149, "text": "There are many libraries to make an HTTP request in Python, which are httplib, urllib, httplib2, treq, etc., but requests is the one of the best with cool features. If any attribute of requests shows NULL, check the status code using below attribute." }, { "code": null, "e": 1421, "s": 1400, "text": "requests.status_code" }, { "code": null, "e": 1578, "s": 1421, "text": "If status_code doesn’t lie in range of 200-29. You probably need to check method begin used for making a request + the url you are requesting for resources." }, { "code": null, "e": 1594, "s": 1578, "text": "Python-requests" }, { "code": null, "e": 1601, "s": 1594, "text": "Python" } ]
Remove any corner X rows and columns from a matrix
09 Feb, 2022 Given an NxN matrix and an integer X. The task is to remove X rows and X columns from the NxN matrix. Remove the first X rows and columns from the matrix. Examples: Input: n = 4, arr[][] = {{20, 2, 10, 16}, {20, 17, 11, 6}, {14, 16, 1, 3}, {10, 2, 17, 4}}, x = 2 Output: 1 3 17 4 Explanation: Here the value of X is 2. So remove the first 2 rows and the first 2 columns from the matrix. Hence the output is 1 3 17 4 Simple Approach: Skip the first x rows and columns and print the remaining elements in the matrix. Start from the xth row and print till the n-1th row. Start from the xth column and print till the n-1th column. Implementation: C++ Java Python3 C# PHP Javascript // C++ implementation of the above approach#include <iostream>using namespace std; // Function to remove first x// rows and columns from an arrayvoid remove_X_Rows_and_Columns(int* a, int n, int x){ cout << "\nRemoving First " << x << " rows and columns:\n"; // Start from the xth row // and print till n-1th row for (int i = x; i < n; i++) { // Start from the xth column // and print till the n-1th column for (int j = x; j < n; j++) { // Accessing the array using pointers cout << *((a + i * n) + j) << " "; } cout << endl; }} // Print the matrixvoid printMatrix(int* a, int n){ for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { cout << *((a + i * n) + j) << " "; } cout << endl; }} int main(){ int n = 4; // get the array inputs int a[n][n]; for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { a[i][j] = (i * 10 + j); } } // Print the matrix cout << "Original Matrix:\n"; printMatrix((int*)a, n); int x = 2; // passing the two dimensional // array using a single pointer remove_X_Rows_and_Columns((int*)a, n, x); return 0;} // Java implementation of the above approachclass GFG{ // Function to remove first x// rows and columns from an arraystatic void remove_X_Rows_and_Columns(int a[][], int n, int x){ System.out.print("\nRemoving First " + x + " rows and columns:\n"); // Start from the xth row // and print till n-1th row for(int i = x; i < n; i++) { // Start from the xth column // and print till the n-1th column for(int j = x; j < n; j++) { // Accessing the array using pointers System.out.print(a[i][j] + " "); } System.out.println(); }} // Print the matrixstatic void printMatrix(int a[][], int n){ for(int i = 0; i < n; i++) { for(int j = 0; j < n; j++) { System.out.print(a[ i][j] + " "); } System.out.println(); }} // Driver Codepublic static void main(String [] args){ int n = 4; // Get the array inputs int a[][] = new int[n][n]; for(int i = 0; i < n; i++) { for(int j = 0; j < n; j++) { a[i][j] = (i * 10 + j); } } // Print the matrix System.out.println( "Original Matrix:"); printMatrix(a, n); int x = 2; // Passing the two dimensional // array using a single pointer remove_X_Rows_and_Columns(a, n, x);}} // This code is contributed by chitranayal # Python3 implementation of the above approach # Function to remove first x# rows and columns from an arraydef remove_X_Rows_and_Columns(a, n, x): print("Removing First ", x, " rows and columns:") # Start from the xth row # and print till n-1th row for i in range(x, n): # Start from the xth column # and print till the n-1th column for j in range(x, n): # Accessing the array using pointers print(a[i][j], end = " ") print() # Print the matrixdef printMatrix(a, n): for i in range(n): for j in range(n): print(a[i][j], end = " ") print() # Driver Codeif __name__ == '__main__': n = 4 # get the array inputs a = [[0 for i in range(n)] for i in range(n)] for i in range(n): for j in range(n): a[i][j] = (i * 10 + j) # Print the matrix print("Original Matrix:") printMatrix(a, n) x = 2 # passing the two dimensional # array using a single pointer remove_X_Rows_and_Columns(a, n, x) # This code is contributed by# Mohit kumar 29 // C# implementation of the above approachusing System; class GFG{ // Function to remove first x// rows and columns from an arraystatic void remove_X_Rows_and_Columns(int[,] a, int n, int x){ Console.WriteLine("\nRemoving First " + x + " rows and columns:\n"); // Start from the xth row // and print till n-1th row for(int i = x; i < n; i++) { // Start from the xth column // and print till the n-1th column for(int j = x; j < n; j++) { // Accessing the array using pointers Console.Write(a[i, j] + " "); } Console.WriteLine(); }} // Print the matrixstatic void printMatrix(int[,] a, int n){ for(int i = 0; i < n; i++) { for(int j = 0; j < n; j++) { Console.Write(a[i, j] + " "); } Console.WriteLine(); }} // Driver Codestatic public void Main(){ int n = 4; // Get the array inputs int[,] a = new int[n, n]; for(int i = 0; i < n; i++) { for(int j = 0; j < n; j++) { a[i,j] = (i * 10 + j); } } // Print the matrix Console.WriteLine( "Original Matrix:"); printMatrix(a, n); int x = 2; // Passing the two dimensional // array using a single pointer remove_X_Rows_and_Columns(a, n, x);}} // This code is contributed by avanitrachhadiya2155 <?php// PHP implementation of the above approach // Function to remove first x// rows and columns from an arrayfunction remove_X_Rows_and_Columns($a, $n, $x){ echo "\nRemoving First ", $x, " rows and columns:\n"; // Start from the xth row // and print till n-1th row for ($i = $x; $i < $n; $i++) { // Start from the xth column // and print till the n-1th column for ($j = $x; $j < $n; $j++) { // Accessing the array using pointers echo $a[$i][$j], " "; } echo "\n"; }} // Print the matrixfunction printMatrix($a, $n){ for ($i = 0; $i < $n; $i++) { for ($j = 0; $j < $n; $j++) { echo $a[$i][$j], " "; } echo "\n"; }} $n = 4; // get the array inputs$a = array(array()); for ($i = 0; $i < $n; $i++){ for ($j = 0; $j < $n; $j++) { $a[$i][$j] = $i * 10 + $j; }} // Print the matrixecho "Original Matrix:\n";printMatrix($a, $n); $x = 2; // passing the two dimensional// array using a single pointerremove_X_Rows_and_Columns($a, $n, $x); // This code is contributed by Ryuga?> <script> // javascript implementation of the above approach // Function to remove first x // rows and columns from an array function remove_X_Rows_and_Columns(a , n , x) { document.write("<br/>Removing First " + x + " rows and columns:<br/>"); // Start from the xth row // and print till n-1th row for (i = x; i < n; i++) { // Start from the xth column // and print till the n-1th column for (j = x; j < n; j++) { // Accessing the array using pointers document.write(a[i][j] + " "); } document.write("<br/>"); } } // Print the matrix function printMatrix(a , n) { for (i = 0; i < n; i++) { for (j = 0; j < n; j++) { document.write(a[i][j] + " "); } document.write("<br/>"); } } // Driver Code var n = 4; // Get the array inputs var a = Array(n); for (i = 0; i < n; i++) { a[i] = Array(n).fill(0); for (j = 0; j < n; j++) { a[i][j] = (i * 10 + j); } } // Print the matrix document.write("Original Matrix:"); printMatrix(a, n); var x = 2; // Passing the two dimensional // array using a single pointer remove_X_Rows_and_Columns(a, n, x); // This code contributed by gauravrajput1</script> Original Matrix: 0 1 2 3 10 11 12 13 20 21 22 23 30 31 32 33 Removing First 2 rows and columns: 22 23 32 33 Remove the last X rows and columns from the matrix. Examples: Input: n = 4, arr[][] = {{20, 2, 10, 16}, {20, 17, 11, 6}, {14, 16, 1, 3}, {10, 2, 17, 4}}, x = 2 Output: 20 2 20 17 Explanation: Here the value of X is 2. So remove the last 2 rows and the last 2 columns from the matrix. Hence the output is 20 2 20 17 Simple Approach Skip the last x rows and columns and print the remaining elements in the matrix. Start from the 0th row and print till the n-xth row. Start from the 0th column and print till the n-xth column. Implementation: C++ Java Python3 C# Javascript #include <iostream>using namespace std; // Function to remove last x rows// and columns from an arrayvoid remove_X_Rows_and_Columns(int* a, int n, int x){ cout << "\nRemoving Last " << x << " rows and columns:\n"; // Start from the 0th row // and print till n-xth row for (int i = 0; i < n - x; i++) { // Start from the 0th column // and print till the n-xth column for (int j = 0; j < n - x; j++) { // Accessing the array using pointers cout << *((a + i * n) + j) << " "; } cout << endl; }} // Print the matrixvoid printMatrix(int* a, int n){ for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { cout << *((a + i * n) + j) << " "; } cout << endl; }} int main(){ int n = 4; // get the array inputs int a[n][n]; for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { a[i][j] = (i * 10 + j); } } // Print the matrix cout << "Original Matrix:\n"; printMatrix((int*)a, n); int x = 2; // passing the two dimensional // array using a single pointer remove_X_Rows_and_Columns((int*)a, n, x); return 0;} import java.io.*; class GFG{ public static void remove_X_Rows_and_Columns( int[][] a,int n, int x){ System.out.println("\nRemoving Last " + x + " rows and columns:\n"); // Start from the 0th row // and print till n-xth row for(int i = 0; i < n - x; i++) { // Start from the 0th column // and print till the n-xth column for(int j = 0; j < n - x; j++) { // Accessing the array using pointers System.out.print(a[i][j] + " "); } System.out.println(); } } // Print the matrixpublic static void printMatrix(int[][] a, int n){ for(int i = 0; i < n; i++) { for(int j = 0; j < n; j++) { System.out.print(a[i][j] + " "); } System.out.println(); } } // Driver codepublic static void main(String[] args){ int n = 4; // Get the array inputs int[][] a = new int[n][n]; for(int i = 0; i < n; i++) { for(int j = 0; j < n; j++) { a[i][j] = (i * 10 + j); } } // Print the matrix System.out.println("Original Matrix:"); printMatrix(a, n); int x = 2; // Passing the two dimensional // array using a single pointer remove_X_Rows_and_Columns(a, n, x);}} // This code is contributed by patel2127 # Function to remove last x rows# and columns from an arraydef remove_X_Rows_and_Columns(a, n, x): print("\nRemoving Last", x, "rows and columns:") # Start from the 0th row # and print till n-xth row for i in range(n - x): # Start from the 0th column # and print till the n-xth column for j in range(n - x): # Accessing the array using pointers print(a[i][j], end = " ") print() # Print the matrixdef printMatrix(a, n): for i in range(n): for j in range(n): print(a[i][j], end = " ") print() n = 4 # get the array inputsa = [[0 for i in range(n)] for j in range(n)]for i in range(n): for j in range(n): a[i][j] = (i * 10 + j) # Print the matrixprint("Original Matrix:")printMatrix(a, n)x = 2 # passing the two dimensional# array using a single pointerremove_X_Rows_and_Columns(a, n, x) # This code is contributed by rag2127 using System; public class GFG{ public static void remove_X_Rows_and_Columns( int[,] a,int n, int x){ Console.WriteLine("\nRemoving Last " + x + " rows and columns:\n"); // Start from the 0th row // and print till n-xth row for(int i = 0; i < n - x; i++) { // Start from the 0th column // and print till the n-xth column for(int j = 0; j < n - x; j++) { // Accessing the array using pointers Console.Write(a[i,j] + " "); } Console.WriteLine(); } } // Print the matrixpublic static void printMatrix(int[,] a, int n){ for(int i = 0; i < n; i++) { for(int j = 0; j < n; j++) { Console.Write(a[i,j] + " "); } Console.WriteLine(); } } // Driver code static public void Main (){ int n = 4; // Get the array inputs int[,] a = new int[n,n]; for(int i = 0; i < n; i++) { for(int j = 0; j < n; j++) { a[i,j] = (i * 10 + j); } } // Print the matrix Console.WriteLine("Original Matrix:"); printMatrix(a, n); int x = 2; // Passing the two dimensional // array using a single pointer remove_X_Rows_and_Columns(a, n, x); }} // This code is contributed by ab2127. <script> // Function to remove last x rows// and columns from an arrayfunction remove_X_Rows_and_Columns(a, n, x){ document.write("<br>Removing Last"+ x+ "rows and columns:<br>"); // Start from the 0th row // and print till n-xth row for (let i = 0; i < n - x; i++) { // Start from the 0th column // and print till the n-xth column for (let j = 0; j < n - x; j++) { // Accessing the array using pointers document.write(a[i][j]+" "); } document.write("<br>") }} // Print the matrixfunction printMatrix(a,n){ for (let i = 0; i < n; i++) { for (let j = 0; j < n; j++) { document.write(a[i][j]+" "); } document.write("<br>") }} let n = 4; // get the array inputs let a = new Array(n); for (let i = 0; i < n; i++) { a[i]=new Array(n); for (let j = 0; j < n; j++) { a[i][j] = (i * 10 + j); } } // Print the matrix document.write("Original Matrix:<br>"); printMatrix(a, n); let x = 2; // passing the two dimensional // array using a single pointer remove_X_Rows_and_Columns(a, n, x); // This code is contributed by unknown2108</script> Original Matrix: 0 1 2 3 10 11 12 13 20 21 22 23 30 31 32 33 Removing Last 2 rows and columns: 0 1 10 11 Remove the first X rows and last X columns from the matrix. Examples: Input: n = 4, arr[][] = {{20, 2, 10, 16}, {20, 17, 11, 6}, {14, 16, 1, 3}, {10, 2, 17, 4}}, x = 2 Output: 14 16 10 2 Explanation: Here the value of X is 2. So remove the first 2 rows and the last 2 columns from the matrix. Hence the output is 14 16 10 2 Simple Approach Skip the first x rows and last x columns and print the remaining elements in the matrix. Start from the xth row and print till the n-1th row. Start from the 0th column and print till the n-xth column. Implementation: C++ Java Python3 C# Javascript #include <iostream>using namespace std; // Function to remove first x rows// and last x columns from an arrayvoid remove_X_Rows_and_Columns(int* a, int n, int x){ cout << "\nRemoving First " << x << " rows and Last " << x << " columns:\n"; // Start from the xth row // and print till n-1th row for (int i = x; i < n; i++) { // Start from the 0th column // and print till the n-xth column for (int j = 0; j < n - x; j++) { // Accessing the array using pointers cout << *((a + i * n) + j) << " "; } cout << endl; }} // Print the matrixvoid printMatrix(int* a, int n){ for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { cout << *((a + i * n) + j) << " "; } cout << endl; }} int main(){ int n = 4; // get the array inputs int a[n][n]; for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { a[i][j] = (i * 10 + j); } } // Print the matrix cout << "Original Matrix:\n"; printMatrix((int*)a, n); int x = 2; // passing the two dimensional // array using a single pointer remove_X_Rows_and_Columns((int*)a, n, x); return 0;} import java.util.*; class GFG{ // Function to remove first x rows// and last x columns from an arraystatic void remove_X_Rows_and_Columns(int[][] a, int n, int x){ System.out.print("\nRemoving First " + x + " rows and Last " + x + " columns:\n"); // Start from the xth row // and print till n-1th row for(int i = x; i < n; i++) { // Start from the 0th column // and print till the n-xth column for(int j = 0; j < n - x; j++) { // Accessing the array using pointers System.out.print(a[i][j]+ " "); } System.out.println(); }} // Print the matrixstatic void printMatrix(int[][] a, int n){ for(int i = 0; i < n; i++) { for(int j = 0; j < n; j++) { System.out.print(a[i][j] + " "); } System.out.println(); }} // Driver codepublic static void main(String[] args){ int n = 4; // Get the array inputs int [][]a = new int[n][n]; for(int i = 0; i < n; i++) { for(int j = 0; j < n; j++) { a[i][j] = (i * 10 + j); } } // Print the matrix System.out.print("Original Matrix:\n"); printMatrix(a, n); int x = 2; // Passing the two dimensional // array using a single pointer remove_X_Rows_and_Columns(a, n, x);}} // This code is contributed by 29AjayKumar # Function to remove first x rows# and last x columns from an arraydef remove_X_Rows_and_Columns(a, n, x): print("\nRemoving First " , x , " rows and Last " , x , " columns:"); # Start from the xth row # and print till n-1th row for i in range(x, n): # Start from the 0th column # and print till the n-xth column for j in range(n - x): # Accessing the array using pointers print(a[i][j], end = " "); print(); # Print the matrixdef printMatrix(a, n): for i in range(n): for j in range(n): print(a[i][j], end=" "); print(); # Driver codeif __name__ == '__main__': n = 4; # Get the array inputs a = [[0 for i in range(n)] for j in range(n)] for i in range(n): for j in range(n): a[i][j] = (i * 10 + j); # Print the matrix print("Original Matrix:"); printMatrix(a, n); x = 2; # Passing the two dimensional # array using a single pointer remove_X_Rows_and_Columns(a, n, x); # This code is contributed by shikhasingrajput using System; public class GFG{ // Function to remove first x rows// and last x columns from an arraystatic void remove_X_Rows_and_Columns(int[,] a, int n, int x){ Console.Write("\nRemoving First " + x + " rows and Last " + x + " columns:\n"); // Start from the xth row // and print till n-1th row for(int i = x; i < n; i++) { // Start from the 0th column // and print till the n-xth column for(int j = 0; j < n - x; j++) { // Accessing the array using pointers Console.Write(a[i,j]+ " "); } Console.WriteLine(); }} // Print the matrixstatic void printMatrix(int[,] a, int n){ for(int i = 0; i < n; i++) { for(int j = 0; j < n; j++) { Console.Write(a[i,j] + " "); } Console.WriteLine(); }} // Driver codepublic static void Main(String[] args){ int n = 4; // Get the array inputs int [,]a = new int[n,n]; for(int i = 0; i < n; i++) { for(int j = 0; j < n; j++) { a[i,j] = (i * 10 + j); } } // Print the matrix Console.Write("Original Matrix:\n"); printMatrix(a, n); int x = 2; // Passing the two dimensional // array using a single pointer remove_X_Rows_and_Columns(a, n, x);}} // This code is contributed by 29AjayKumar <script>// Function to remove first x rows// and last x columns from an arrayfunction remove_X_Rows_and_Columns(a , n,x){ document.write("<br>Removing First " + x + " rows and Last " + x + " columns:<br>"); // Start from the xth row // and print till n-1th row for(var i = x; i < n; i++) { // Start from the 0th column // and print till the n-xth column for(var j = 0; j < n - x; j++) { // Accessing the array using pointers document.write(a[i][j]+ " "); } document.write('<br>'); }} // Print the matrixfunction printMatrix(a , n){ for(var i = 0; i < n; i++) { for(var j = 0; j < n; j++) { document.write(a[i][j] + " "); } document.write('<br>'); }} // Driver code var n = 4; // Get the array inputs var a = Array(n).fill(0).map(x => Array(n).fill(0)); for(var i = 0; i < n; i++) { for(var j = 0; j < n; j++) { a[i][j] = (i * 10 + j); } } // Print the matrix document.write("Original Matrix:<br>"); printMatrix(a, n); var x = 2; // Passing the two dimensional // array using a single pointer remove_X_Rows_and_Columns(a, n, x); // This code is contributed by 29AjayKumar</script> Original Matrix: 0 1 2 3 10 11 12 13 20 21 22 23 30 31 32 33 Removing First 2 rows and Last 2 columns: 20 21 30 31 Remove the last X rows and first x columns from the matrix. Examples: Input: n = 4, arr[][] = {{20, 2, 10, 16}, {20, 17, 11, 6}, {14, 16, 1, 3}, {10, 2, 17, 4}}, x = 2 Output: 10 16 11 6 Explanation: Here the value of X is 2. So remove the last 2 rows and the first 2 columns from the matrix. Hence the output is 10 16 11 6 Simple Approach Skip the last x rows and first x columns and print the remaining elements in the matrix. Start from the 0th row and print till the n-xth row. Start from the xth column and print till the n-1th column. Implementation: C++ Java Python3 C# Javascript #include <iostream>using namespace std; // Function to remove last x rows// and first x columns from an arrayvoid remove_X_Rows_and_Columns(int* a, int n, int x){ cout << "\nRemoving Last " << x << " rows and First " << x << " columns:\n"; // Start from the 0th row // and print till n-xth row for (int i = 0; i < n - x; i++) { // Start from the xth column and // print till the n-1th column for (int j = x; j < n; j++) { // Accessing the array using pointers cout << *((a + i * n) + j) << " "; } cout << endl; }} // Print the matrixvoid printMatrix(int* a, int n){ for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { cout << *((a + i * n) + j) << " "; } cout << endl; }} int main(){ int n = 4; // get the array inputs int a[n][n]; for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { a[i][j] = (i * 10 + j); } } // Print the matrix cout << "Original Matrix:\n"; printMatrix((int*)a, n); int x = 2; // passing the two dimensional // array using a single pointer remove_X_Rows_and_Columns((int*)a, n, x); return 0;} import java.util.*; class GFG{ // Function to remove last x rows // and first x columns from an array static void remove_X_Rows_and_Columns(int[][] a, int n, int x) { System.out.print("\nRemoving Last " + x + " rows and First " + x + " columns:\n"); // Start from the 0th row // and print till n-xth row for (int i = 0; i < n - x; i++) { // Start from the xth column and // print till the n-1th column for (int j = x; j < n; j++) { // Accessing the array using pointers System.out.print(a[i][j]+ " "); } System.out.println(); } } // Print the matrix static void printMatrix(int[][] a, int n) { for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { System.out.print(a[i][j]+ " "); } System.out.println(); } } public static void main(String[] args) { int n = 4; // get the array inputs int [][]a= new int[n][n]; for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { a[i][j] = (i * 10 + j); } } // Print the matrix System.out.print("Original Matrix:\n"); printMatrix(a, n); int x = 2; // passing the two dimensional // array using a single pointer remove_X_Rows_and_Columns(a, n, x); }} // This code is contributed by 29AjayKumar # Function to remove last x rows# and first x columns from an arraydef remove_X_Rows_and_Columns(a, n, x): print("\nRemoving Last ", x , " rows and First ", x, " columns:") # Start from the 0th row # and print till n-xth row for i in range(n - x): # Start from the xth column and # print till the n-1th column for j in range(x, n): # Accessing the array using pointers print(a[i][j], end = " ") print() # Print the matrixdef printMatrix(a, n): for i in range(n): for j in range(n): print(a[i][j], end = " ") print() # Driver codeif __name__ == '__main__': n = 4 # Get the array inputs a = [[0 for i in range(n)] for i in range(n)] for i in range(n): for j in range(n): a[i][j] = (i * 10 + j) # Print the matrix print("Original Matrix:") printMatrix(a, n) x = 2 # Passing the two dimensional # array using a single pointer remove_X_Rows_and_Columns(a, n, x) # This code is contributed by mohit kumar 29 using System;using System.Collections.Generic; public class GFG{ // Function to remove last x rows // and first x columns from an array static void remove_X_Rows_and_Columns(int[,] a, int n, int x) { Console.Write("\nRemoving Last " + x + " rows and First " + x + " columns:\n"); // Start from the 0th row // and print till n-xth row for (int i = 0; i < n - x; i++) { // Start from the xth column and // print till the n-1th column for (int j = x; j < n; j++) { // Accessing the array using pointers Console.Write(a[i,j]+ " "); } Console.WriteLine(); } } // Print the matrix static void printMatrix(int[,] a, int n) { for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { Console.Write(a[i,j]+ " "); } Console.WriteLine(); } } public static void Main(String[] args) { int n = 4; // get the array inputs int [,]a= new int[n,n]; for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { a[i,j] = (i * 10 + j); } } // Print the matrix Console.Write("Original Matrix:\n"); printMatrix(a, n); int x = 2; // passing the two dimensional // array using a single pointer remove_X_Rows_and_Columns(a, n, x); }} // This code is contributed by shikhasingrajput <script> // JavaScript implementation of above approach // Function to remove last x rows // and first x columns from an array function remove_X_Rows_and_Columns(a, n, x) { document.write("</br>" + "Removing Last " + x + " rows and First " + x + " columns:" + "</br>"); // Start from the 0th row // and print till n-xth row for (let i = 0; i < n - x; i++) { // Start from the xth column and // print till the n-1th column for (let j = x; j < n; j++) { // Accessing the array using pointers document.write(a[i][j] + " "); } document.write("</br>"); } } // Print the matrix function printMatrix(a, n) { for (let i = 0; i < n; i++) { for (let j = 0; j < n; j++) { document.write(a[i][j] + " "); } document.write("</br>"); } } let n = 4; // get the array inputs let a = new Array(n); for (let i = 0; i < n; i++) { a[i] = new Array(n); for (let j = 0; j < n; j++) { a[i][j] = (i * 10 + j); } } // Print the matrix document.write("Original Matrix:" + "</br>"); printMatrix(a, n); let x = 2; // passing the two dimensional // array using a single pointer remove_X_Rows_and_Columns(a, n, x); </script> Original Matrix: 0 1 2 3 10 11 12 13 20 21 22 23 30 31 32 33 Removing Last 2 rows and First 2 columns: 2 3 12 13 ankthon mohit kumar 29 ukasp avanitrachhadiya2155 rag2127 GauravRajput1 unknown2108 patel2127 vaibhavrabadiya117 ab2127 sweetyty 29AjayKumar surinderdawra388 simranarora5sos shikhasingrajput sagartomar9927 simmytarika5 C++ Programs Matrix Matrix Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Shallow Copy and Deep Copy in C++ C++ Program to check if a given String is Palindrome or not C++ Program for QuickSort How to find the minimum and maximum element of a Vector using STL in C++? delete keyword in C++ Matrix Chain Multiplication | DP-8 Print a given matrix in spiral form Program to find largest element in an array Rat in a Maze | Backtracking-2 Sudoku | Backtracking-7
[ { "code": null, "e": 28, "s": 0, "text": "\n09 Feb, 2022" }, { "code": null, "e": 130, "s": 28, "text": "Given an NxN matrix and an integer X. The task is to remove X rows and X columns from the NxN matrix." }, { "code": null, "e": 183, "s": 130, "text": "Remove the first X rows and columns from the matrix." }, { "code": null, "e": 194, "s": 183, "text": "Examples: " }, { "code": null, "e": 519, "s": 194, "text": "Input: n = 4, \n arr[][] = {{20, 2, 10, 16},\n {20, 17, 11, 6},\n {14, 16, 1, 3},\n {10, 2, 17, 4}}, \n x = 2\nOutput:\n1 3\n17 4\n\nExplanation:\nHere the value of X is 2.\nSo remove the first 2 rows \nand the first 2 columns from the matrix. \nHence the output is\n1 3 \n17 4" }, { "code": null, "e": 537, "s": 519, "text": "Simple Approach: " }, { "code": null, "e": 619, "s": 537, "text": "Skip the first x rows and columns and print the remaining elements in the matrix." }, { "code": null, "e": 672, "s": 619, "text": "Start from the xth row and print till the n-1th row." }, { "code": null, "e": 731, "s": 672, "text": "Start from the xth column and print till the n-1th column." }, { "code": null, "e": 748, "s": 731, "text": "Implementation: " }, { "code": null, "e": 752, "s": 748, "text": "C++" }, { "code": null, "e": 757, "s": 752, "text": "Java" }, { "code": null, "e": 765, "s": 757, "text": "Python3" }, { "code": null, "e": 768, "s": 765, "text": "C#" }, { "code": null, "e": 772, "s": 768, "text": "PHP" }, { "code": null, "e": 783, "s": 772, "text": "Javascript" }, { "code": "// C++ implementation of the above approach#include <iostream>using namespace std; // Function to remove first x// rows and columns from an arrayvoid remove_X_Rows_and_Columns(int* a, int n, int x){ cout << \"\\nRemoving First \" << x << \" rows and columns:\\n\"; // Start from the xth row // and print till n-1th row for (int i = x; i < n; i++) { // Start from the xth column // and print till the n-1th column for (int j = x; j < n; j++) { // Accessing the array using pointers cout << *((a + i * n) + j) << \" \"; } cout << endl; }} // Print the matrixvoid printMatrix(int* a, int n){ for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { cout << *((a + i * n) + j) << \" \"; } cout << endl; }} int main(){ int n = 4; // get the array inputs int a[n][n]; for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { a[i][j] = (i * 10 + j); } } // Print the matrix cout << \"Original Matrix:\\n\"; printMatrix((int*)a, n); int x = 2; // passing the two dimensional // array using a single pointer remove_X_Rows_and_Columns((int*)a, n, x); return 0;}", "e": 2020, "s": 783, "text": null }, { "code": "// Java implementation of the above approachclass GFG{ // Function to remove first x// rows and columns from an arraystatic void remove_X_Rows_and_Columns(int a[][], int n, int x){ System.out.print(\"\\nRemoving First \" + x + \" rows and columns:\\n\"); // Start from the xth row // and print till n-1th row for(int i = x; i < n; i++) { // Start from the xth column // and print till the n-1th column for(int j = x; j < n; j++) { // Accessing the array using pointers System.out.print(a[i][j] + \" \"); } System.out.println(); }} // Print the matrixstatic void printMatrix(int a[][], int n){ for(int i = 0; i < n; i++) { for(int j = 0; j < n; j++) { System.out.print(a[ i][j] + \" \"); } System.out.println(); }} // Driver Codepublic static void main(String [] args){ int n = 4; // Get the array inputs int a[][] = new int[n][n]; for(int i = 0; i < n; i++) { for(int j = 0; j < n; j++) { a[i][j] = (i * 10 + j); } } // Print the matrix System.out.println( \"Original Matrix:\"); printMatrix(a, n); int x = 2; // Passing the two dimensional // array using a single pointer remove_X_Rows_and_Columns(a, n, x);}} // This code is contributed by chitranayal", "e": 3451, "s": 2020, "text": null }, { "code": "# Python3 implementation of the above approach # Function to remove first x# rows and columns from an arraydef remove_X_Rows_and_Columns(a, n, x): print(\"Removing First \", x, \" rows and columns:\") # Start from the xth row # and print till n-1th row for i in range(x, n): # Start from the xth column # and print till the n-1th column for j in range(x, n): # Accessing the array using pointers print(a[i][j], end = \" \") print() # Print the matrixdef printMatrix(a, n): for i in range(n): for j in range(n): print(a[i][j], end = \" \") print() # Driver Codeif __name__ == '__main__': n = 4 # get the array inputs a = [[0 for i in range(n)] for i in range(n)] for i in range(n): for j in range(n): a[i][j] = (i * 10 + j) # Print the matrix print(\"Original Matrix:\") printMatrix(a, n) x = 2 # passing the two dimensional # array using a single pointer remove_X_Rows_and_Columns(a, n, x) # This code is contributed by# Mohit kumar 29", "e": 4567, "s": 3451, "text": null }, { "code": "// C# implementation of the above approachusing System; class GFG{ // Function to remove first x// rows and columns from an arraystatic void remove_X_Rows_and_Columns(int[,] a, int n, int x){ Console.WriteLine(\"\\nRemoving First \" + x + \" rows and columns:\\n\"); // Start from the xth row // and print till n-1th row for(int i = x; i < n; i++) { // Start from the xth column // and print till the n-1th column for(int j = x; j < n; j++) { // Accessing the array using pointers Console.Write(a[i, j] + \" \"); } Console.WriteLine(); }} // Print the matrixstatic void printMatrix(int[,] a, int n){ for(int i = 0; i < n; i++) { for(int j = 0; j < n; j++) { Console.Write(a[i, j] + \" \"); } Console.WriteLine(); }} // Driver Codestatic public void Main(){ int n = 4; // Get the array inputs int[,] a = new int[n, n]; for(int i = 0; i < n; i++) { for(int j = 0; j < n; j++) { a[i,j] = (i * 10 + j); } } // Print the matrix Console.WriteLine( \"Original Matrix:\"); printMatrix(a, n); int x = 2; // Passing the two dimensional // array using a single pointer remove_X_Rows_and_Columns(a, n, x);}} // This code is contributed by avanitrachhadiya2155", "e": 6027, "s": 4567, "text": null }, { "code": "<?php// PHP implementation of the above approach // Function to remove first x// rows and columns from an arrayfunction remove_X_Rows_and_Columns($a, $n, $x){ echo \"\\nRemoving First \", $x, \" rows and columns:\\n\"; // Start from the xth row // and print till n-1th row for ($i = $x; $i < $n; $i++) { // Start from the xth column // and print till the n-1th column for ($j = $x; $j < $n; $j++) { // Accessing the array using pointers echo $a[$i][$j], \" \"; } echo \"\\n\"; }} // Print the matrixfunction printMatrix($a, $n){ for ($i = 0; $i < $n; $i++) { for ($j = 0; $j < $n; $j++) { echo $a[$i][$j], \" \"; } echo \"\\n\"; }} $n = 4; // get the array inputs$a = array(array()); for ($i = 0; $i < $n; $i++){ for ($j = 0; $j < $n; $j++) { $a[$i][$j] = $i * 10 + $j; }} // Print the matrixecho \"Original Matrix:\\n\";printMatrix($a, $n); $x = 2; // passing the two dimensional// array using a single pointerremove_X_Rows_and_Columns($a, $n, $x); // This code is contributed by Ryuga?>", "e": 7155, "s": 6027, "text": null }, { "code": "<script> // javascript implementation of the above approach // Function to remove first x // rows and columns from an array function remove_X_Rows_and_Columns(a , n , x) { document.write(\"<br/>Removing First \" + x + \" rows and columns:<br/>\"); // Start from the xth row // and print till n-1th row for (i = x; i < n; i++) { // Start from the xth column // and print till the n-1th column for (j = x; j < n; j++) { // Accessing the array using pointers document.write(a[i][j] + \" \"); } document.write(\"<br/>\"); } } // Print the matrix function printMatrix(a , n) { for (i = 0; i < n; i++) { for (j = 0; j < n; j++) { document.write(a[i][j] + \" \"); } document.write(\"<br/>\"); } } // Driver Code var n = 4; // Get the array inputs var a = Array(n); for (i = 0; i < n; i++) { a[i] = Array(n).fill(0); for (j = 0; j < n; j++) { a[i][j] = (i * 10 + j); } } // Print the matrix document.write(\"Original Matrix:\"); printMatrix(a, n); var x = 2; // Passing the two dimensional // array using a single pointer remove_X_Rows_and_Columns(a, n, x); // This code contributed by gauravrajput1</script>", "e": 8596, "s": 7155, "text": null }, { "code": null, "e": 8710, "s": 8596, "text": "Original Matrix:\n0 1 2 3 \n10 11 12 13 \n20 21 22 23 \n30 31 32 33 \n\nRemoving First 2 rows and columns:\n22 23 \n32 33" }, { "code": null, "e": 8764, "s": 8712, "text": "Remove the last X rows and columns from the matrix." }, { "code": null, "e": 8775, "s": 8764, "text": "Examples: " }, { "code": null, "e": 9101, "s": 8775, "text": "Input: n = 4, \n arr[][] = {{20, 2, 10, 16},\n {20, 17, 11, 6},\n {14, 16, 1, 3},\n {10, 2, 17, 4}}, \n x = 2\nOutput:\n20 2\n20 17\n\nExplanation:\nHere the value of X is 2.\nSo remove the last 2 rows and \nthe last 2 columns from the matrix. \nHence the output is\n20 2\n20 17" }, { "code": null, "e": 9118, "s": 9101, "text": "Simple Approach " }, { "code": null, "e": 9199, "s": 9118, "text": "Skip the last x rows and columns and print the remaining elements in the matrix." }, { "code": null, "e": 9252, "s": 9199, "text": "Start from the 0th row and print till the n-xth row." }, { "code": null, "e": 9311, "s": 9252, "text": "Start from the 0th column and print till the n-xth column." }, { "code": null, "e": 9328, "s": 9311, "text": "Implementation: " }, { "code": null, "e": 9332, "s": 9328, "text": "C++" }, { "code": null, "e": 9337, "s": 9332, "text": "Java" }, { "code": null, "e": 9345, "s": 9337, "text": "Python3" }, { "code": null, "e": 9348, "s": 9345, "text": "C#" }, { "code": null, "e": 9359, "s": 9348, "text": "Javascript" }, { "code": "#include <iostream>using namespace std; // Function to remove last x rows// and columns from an arrayvoid remove_X_Rows_and_Columns(int* a, int n, int x){ cout << \"\\nRemoving Last \" << x << \" rows and columns:\\n\"; // Start from the 0th row // and print till n-xth row for (int i = 0; i < n - x; i++) { // Start from the 0th column // and print till the n-xth column for (int j = 0; j < n - x; j++) { // Accessing the array using pointers cout << *((a + i * n) + j) << \" \"; } cout << endl; }} // Print the matrixvoid printMatrix(int* a, int n){ for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { cout << *((a + i * n) + j) << \" \"; } cout << endl; }} int main(){ int n = 4; // get the array inputs int a[n][n]; for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { a[i][j] = (i * 10 + j); } } // Print the matrix cout << \"Original Matrix:\\n\"; printMatrix((int*)a, n); int x = 2; // passing the two dimensional // array using a single pointer remove_X_Rows_and_Columns((int*)a, n, x); return 0;}", "e": 10559, "s": 9359, "text": null }, { "code": "import java.io.*; class GFG{ public static void remove_X_Rows_and_Columns( int[][] a,int n, int x){ System.out.println(\"\\nRemoving Last \" + x + \" rows and columns:\\n\"); // Start from the 0th row // and print till n-xth row for(int i = 0; i < n - x; i++) { // Start from the 0th column // and print till the n-xth column for(int j = 0; j < n - x; j++) { // Accessing the array using pointers System.out.print(a[i][j] + \" \"); } System.out.println(); } } // Print the matrixpublic static void printMatrix(int[][] a, int n){ for(int i = 0; i < n; i++) { for(int j = 0; j < n; j++) { System.out.print(a[i][j] + \" \"); } System.out.println(); } } // Driver codepublic static void main(String[] args){ int n = 4; // Get the array inputs int[][] a = new int[n][n]; for(int i = 0; i < n; i++) { for(int j = 0; j < n; j++) { a[i][j] = (i * 10 + j); } } // Print the matrix System.out.println(\"Original Matrix:\"); printMatrix(a, n); int x = 2; // Passing the two dimensional // array using a single pointer remove_X_Rows_and_Columns(a, n, x);}} // This code is contributed by patel2127", "e": 11918, "s": 10559, "text": null }, { "code": "# Function to remove last x rows# and columns from an arraydef remove_X_Rows_and_Columns(a, n, x): print(\"\\nRemoving Last\", x, \"rows and columns:\") # Start from the 0th row # and print till n-xth row for i in range(n - x): # Start from the 0th column # and print till the n-xth column for j in range(n - x): # Accessing the array using pointers print(a[i][j], end = \" \") print() # Print the matrixdef printMatrix(a, n): for i in range(n): for j in range(n): print(a[i][j], end = \" \") print() n = 4 # get the array inputsa = [[0 for i in range(n)] for j in range(n)]for i in range(n): for j in range(n): a[i][j] = (i * 10 + j) # Print the matrixprint(\"Original Matrix:\")printMatrix(a, n)x = 2 # passing the two dimensional# array using a single pointerremove_X_Rows_and_Columns(a, n, x) # This code is contributed by rag2127", "e": 12865, "s": 11918, "text": null }, { "code": "using System; public class GFG{ public static void remove_X_Rows_and_Columns( int[,] a,int n, int x){ Console.WriteLine(\"\\nRemoving Last \" + x + \" rows and columns:\\n\"); // Start from the 0th row // and print till n-xth row for(int i = 0; i < n - x; i++) { // Start from the 0th column // and print till the n-xth column for(int j = 0; j < n - x; j++) { // Accessing the array using pointers Console.Write(a[i,j] + \" \"); } Console.WriteLine(); } } // Print the matrixpublic static void printMatrix(int[,] a, int n){ for(int i = 0; i < n; i++) { for(int j = 0; j < n; j++) { Console.Write(a[i,j] + \" \"); } Console.WriteLine(); } } // Driver code static public void Main (){ int n = 4; // Get the array inputs int[,] a = new int[n,n]; for(int i = 0; i < n; i++) { for(int j = 0; j < n; j++) { a[i,j] = (i * 10 + j); } } // Print the matrix Console.WriteLine(\"Original Matrix:\"); printMatrix(a, n); int x = 2; // Passing the two dimensional // array using a single pointer remove_X_Rows_and_Columns(a, n, x); }} // This code is contributed by ab2127.", "e": 14243, "s": 12865, "text": null }, { "code": "<script> // Function to remove last x rows// and columns from an arrayfunction remove_X_Rows_and_Columns(a, n, x){ document.write(\"<br>Removing Last\"+ x+ \"rows and columns:<br>\"); // Start from the 0th row // and print till n-xth row for (let i = 0; i < n - x; i++) { // Start from the 0th column // and print till the n-xth column for (let j = 0; j < n - x; j++) { // Accessing the array using pointers document.write(a[i][j]+\" \"); } document.write(\"<br>\") }} // Print the matrixfunction printMatrix(a,n){ for (let i = 0; i < n; i++) { for (let j = 0; j < n; j++) { document.write(a[i][j]+\" \"); } document.write(\"<br>\") }} let n = 4; // get the array inputs let a = new Array(n); for (let i = 0; i < n; i++) { a[i]=new Array(n); for (let j = 0; j < n; j++) { a[i][j] = (i * 10 + j); } } // Print the matrix document.write(\"Original Matrix:<br>\"); printMatrix(a, n); let x = 2; // passing the two dimensional // array using a single pointer remove_X_Rows_and_Columns(a, n, x); // This code is contributed by unknown2108</script>", "e": 15466, "s": 14243, "text": null }, { "code": null, "e": 15577, "s": 15466, "text": "Original Matrix:\n0 1 2 3 \n10 11 12 13 \n20 21 22 23 \n30 31 32 33 \n\nRemoving Last 2 rows and columns:\n0 1 \n10 11" }, { "code": null, "e": 15639, "s": 15579, "text": "Remove the first X rows and last X columns from the matrix." }, { "code": null, "e": 15650, "s": 15639, "text": "Examples: " }, { "code": null, "e": 15977, "s": 15650, "text": "Input: n = 4, \n arr[][] = {{20, 2, 10, 16},\n {20, 17, 11, 6},\n {14, 16, 1, 3},\n {10, 2, 17, 4}}, \n x = 2\nOutput:\n14 16\n10 2\n\nExplanation:\nHere the value of X is 2.\nSo remove the first 2 rows \nand the last 2 columns from the matrix. \nHence the output is\n14 16\n10 2" }, { "code": null, "e": 15995, "s": 15977, "text": "Simple Approach " }, { "code": null, "e": 16084, "s": 15995, "text": "Skip the first x rows and last x columns and print the remaining elements in the matrix." }, { "code": null, "e": 16137, "s": 16084, "text": "Start from the xth row and print till the n-1th row." }, { "code": null, "e": 16196, "s": 16137, "text": "Start from the 0th column and print till the n-xth column." }, { "code": null, "e": 16213, "s": 16196, "text": "Implementation: " }, { "code": null, "e": 16217, "s": 16213, "text": "C++" }, { "code": null, "e": 16222, "s": 16217, "text": "Java" }, { "code": null, "e": 16230, "s": 16222, "text": "Python3" }, { "code": null, "e": 16233, "s": 16230, "text": "C#" }, { "code": null, "e": 16244, "s": 16233, "text": "Javascript" }, { "code": "#include <iostream>using namespace std; // Function to remove first x rows// and last x columns from an arrayvoid remove_X_Rows_and_Columns(int* a, int n, int x){ cout << \"\\nRemoving First \" << x << \" rows and Last \" << x << \" columns:\\n\"; // Start from the xth row // and print till n-1th row for (int i = x; i < n; i++) { // Start from the 0th column // and print till the n-xth column for (int j = 0; j < n - x; j++) { // Accessing the array using pointers cout << *((a + i * n) + j) << \" \"; } cout << endl; }} // Print the matrixvoid printMatrix(int* a, int n){ for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { cout << *((a + i * n) + j) << \" \"; } cout << endl; }} int main(){ int n = 4; // get the array inputs int a[n][n]; for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { a[i][j] = (i * 10 + j); } } // Print the matrix cout << \"Original Matrix:\\n\"; printMatrix((int*)a, n); int x = 2; // passing the two dimensional // array using a single pointer remove_X_Rows_and_Columns((int*)a, n, x); return 0;}", "e": 17474, "s": 16244, "text": null }, { "code": "import java.util.*; class GFG{ // Function to remove first x rows// and last x columns from an arraystatic void remove_X_Rows_and_Columns(int[][] a, int n, int x){ System.out.print(\"\\nRemoving First \" + x + \" rows and Last \" + x + \" columns:\\n\"); // Start from the xth row // and print till n-1th row for(int i = x; i < n; i++) { // Start from the 0th column // and print till the n-xth column for(int j = 0; j < n - x; j++) { // Accessing the array using pointers System.out.print(a[i][j]+ \" \"); } System.out.println(); }} // Print the matrixstatic void printMatrix(int[][] a, int n){ for(int i = 0; i < n; i++) { for(int j = 0; j < n; j++) { System.out.print(a[i][j] + \" \"); } System.out.println(); }} // Driver codepublic static void main(String[] args){ int n = 4; // Get the array inputs int [][]a = new int[n][n]; for(int i = 0; i < n; i++) { for(int j = 0; j < n; j++) { a[i][j] = (i * 10 + j); } } // Print the matrix System.out.print(\"Original Matrix:\\n\"); printMatrix(a, n); int x = 2; // Passing the two dimensional // array using a single pointer remove_X_Rows_and_Columns(a, n, x);}} // This code is contributed by 29AjayKumar", "e": 18924, "s": 17474, "text": null }, { "code": "# Function to remove first x rows# and last x columns from an arraydef remove_X_Rows_and_Columns(a, n, x): print(\"\\nRemoving First \" , x , \" rows and Last \" , x , \" columns:\"); # Start from the xth row # and print till n-1th row for i in range(x, n): # Start from the 0th column # and print till the n-xth column for j in range(n - x): # Accessing the array using pointers print(a[i][j], end = \" \"); print(); # Print the matrixdef printMatrix(a, n): for i in range(n): for j in range(n): print(a[i][j], end=\" \"); print(); # Driver codeif __name__ == '__main__': n = 4; # Get the array inputs a = [[0 for i in range(n)] for j in range(n)] for i in range(n): for j in range(n): a[i][j] = (i * 10 + j); # Print the matrix print(\"Original Matrix:\"); printMatrix(a, n); x = 2; # Passing the two dimensional # array using a single pointer remove_X_Rows_and_Columns(a, n, x); # This code is contributed by shikhasingrajput", "e": 20000, "s": 18924, "text": null }, { "code": "using System; public class GFG{ // Function to remove first x rows// and last x columns from an arraystatic void remove_X_Rows_and_Columns(int[,] a, int n, int x){ Console.Write(\"\\nRemoving First \" + x + \" rows and Last \" + x + \" columns:\\n\"); // Start from the xth row // and print till n-1th row for(int i = x; i < n; i++) { // Start from the 0th column // and print till the n-xth column for(int j = 0; j < n - x; j++) { // Accessing the array using pointers Console.Write(a[i,j]+ \" \"); } Console.WriteLine(); }} // Print the matrixstatic void printMatrix(int[,] a, int n){ for(int i = 0; i < n; i++) { for(int j = 0; j < n; j++) { Console.Write(a[i,j] + \" \"); } Console.WriteLine(); }} // Driver codepublic static void Main(String[] args){ int n = 4; // Get the array inputs int [,]a = new int[n,n]; for(int i = 0; i < n; i++) { for(int j = 0; j < n; j++) { a[i,j] = (i * 10 + j); } } // Print the matrix Console.Write(\"Original Matrix:\\n\"); printMatrix(a, n); int x = 2; // Passing the two dimensional // array using a single pointer remove_X_Rows_and_Columns(a, n, x);}} // This code is contributed by 29AjayKumar", "e": 21430, "s": 20000, "text": null }, { "code": "<script>// Function to remove first x rows// and last x columns from an arrayfunction remove_X_Rows_and_Columns(a , n,x){ document.write(\"<br>Removing First \" + x + \" rows and Last \" + x + \" columns:<br>\"); // Start from the xth row // and print till n-1th row for(var i = x; i < n; i++) { // Start from the 0th column // and print till the n-xth column for(var j = 0; j < n - x; j++) { // Accessing the array using pointers document.write(a[i][j]+ \" \"); } document.write('<br>'); }} // Print the matrixfunction printMatrix(a , n){ for(var i = 0; i < n; i++) { for(var j = 0; j < n; j++) { document.write(a[i][j] + \" \"); } document.write('<br>'); }} // Driver code var n = 4; // Get the array inputs var a = Array(n).fill(0).map(x => Array(n).fill(0)); for(var i = 0; i < n; i++) { for(var j = 0; j < n; j++) { a[i][j] = (i * 10 + j); } } // Print the matrix document.write(\"Original Matrix:<br>\"); printMatrix(a, n); var x = 2; // Passing the two dimensional // array using a single pointer remove_X_Rows_and_Columns(a, n, x); // This code is contributed by 29AjayKumar</script>", "e": 22777, "s": 21430, "text": null }, { "code": null, "e": 22898, "s": 22777, "text": "Original Matrix:\n0 1 2 3 \n10 11 12 13 \n20 21 22 23 \n30 31 32 33 \n\nRemoving First 2 rows and Last 2 columns:\n20 21 \n30 31" }, { "code": null, "e": 22960, "s": 22900, "text": "Remove the last X rows and first x columns from the matrix." }, { "code": null, "e": 22971, "s": 22960, "text": "Examples: " }, { "code": null, "e": 23297, "s": 22971, "text": "Input: n = 4, \n arr[][] = {{20, 2, 10, 16},\n {20, 17, 11, 6},\n {14, 16, 1, 3},\n {10, 2, 17, 4}}, \n x = 2\nOutput:\n10 16\n11 6\n\nExplanation:\nHere the value of X is 2.\nSo remove the last 2 rows and\nthe first 2 columns from the matrix. \nHence the output is\n10 16\n11 6" }, { "code": null, "e": 23314, "s": 23297, "text": "Simple Approach " }, { "code": null, "e": 23403, "s": 23314, "text": "Skip the last x rows and first x columns and print the remaining elements in the matrix." }, { "code": null, "e": 23456, "s": 23403, "text": "Start from the 0th row and print till the n-xth row." }, { "code": null, "e": 23515, "s": 23456, "text": "Start from the xth column and print till the n-1th column." }, { "code": null, "e": 23532, "s": 23515, "text": "Implementation: " }, { "code": null, "e": 23536, "s": 23532, "text": "C++" }, { "code": null, "e": 23541, "s": 23536, "text": "Java" }, { "code": null, "e": 23549, "s": 23541, "text": "Python3" }, { "code": null, "e": 23552, "s": 23549, "text": "C#" }, { "code": null, "e": 23563, "s": 23552, "text": "Javascript" }, { "code": "#include <iostream>using namespace std; // Function to remove last x rows// and first x columns from an arrayvoid remove_X_Rows_and_Columns(int* a, int n, int x){ cout << \"\\nRemoving Last \" << x << \" rows and First \" << x << \" columns:\\n\"; // Start from the 0th row // and print till n-xth row for (int i = 0; i < n - x; i++) { // Start from the xth column and // print till the n-1th column for (int j = x; j < n; j++) { // Accessing the array using pointers cout << *((a + i * n) + j) << \" \"; } cout << endl; }} // Print the matrixvoid printMatrix(int* a, int n){ for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { cout << *((a + i * n) + j) << \" \"; } cout << endl; }} int main(){ int n = 4; // get the array inputs int a[n][n]; for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { a[i][j] = (i * 10 + j); } } // Print the matrix cout << \"Original Matrix:\\n\"; printMatrix((int*)a, n); int x = 2; // passing the two dimensional // array using a single pointer remove_X_Rows_and_Columns((int*)a, n, x); return 0;}", "e": 24793, "s": 23563, "text": null }, { "code": "import java.util.*; class GFG{ // Function to remove last x rows // and first x columns from an array static void remove_X_Rows_and_Columns(int[][] a, int n, int x) { System.out.print(\"\\nRemoving Last \" + x + \" rows and First \" + x + \" columns:\\n\"); // Start from the 0th row // and print till n-xth row for (int i = 0; i < n - x; i++) { // Start from the xth column and // print till the n-1th column for (int j = x; j < n; j++) { // Accessing the array using pointers System.out.print(a[i][j]+ \" \"); } System.out.println(); } } // Print the matrix static void printMatrix(int[][] a, int n) { for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { System.out.print(a[i][j]+ \" \"); } System.out.println(); } } public static void main(String[] args) { int n = 4; // get the array inputs int [][]a= new int[n][n]; for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { a[i][j] = (i * 10 + j); } } // Print the matrix System.out.print(\"Original Matrix:\\n\"); printMatrix(a, n); int x = 2; // passing the two dimensional // array using a single pointer remove_X_Rows_and_Columns(a, n, x); }} // This code is contributed by 29AjayKumar", "e": 26134, "s": 24793, "text": null }, { "code": "# Function to remove last x rows# and first x columns from an arraydef remove_X_Rows_and_Columns(a, n, x): print(\"\\nRemoving Last \", x , \" rows and First \", x, \" columns:\") # Start from the 0th row # and print till n-xth row for i in range(n - x): # Start from the xth column and # print till the n-1th column for j in range(x, n): # Accessing the array using pointers print(a[i][j], end = \" \") print() # Print the matrixdef printMatrix(a, n): for i in range(n): for j in range(n): print(a[i][j], end = \" \") print() # Driver codeif __name__ == '__main__': n = 4 # Get the array inputs a = [[0 for i in range(n)] for i in range(n)] for i in range(n): for j in range(n): a[i][j] = (i * 10 + j) # Print the matrix print(\"Original Matrix:\") printMatrix(a, n) x = 2 # Passing the two dimensional # array using a single pointer remove_X_Rows_and_Columns(a, n, x) # This code is contributed by mohit kumar 29", "e": 27259, "s": 26134, "text": null }, { "code": "using System;using System.Collections.Generic; public class GFG{ // Function to remove last x rows // and first x columns from an array static void remove_X_Rows_and_Columns(int[,] a, int n, int x) { Console.Write(\"\\nRemoving Last \" + x + \" rows and First \" + x + \" columns:\\n\"); // Start from the 0th row // and print till n-xth row for (int i = 0; i < n - x; i++) { // Start from the xth column and // print till the n-1th column for (int j = x; j < n; j++) { // Accessing the array using pointers Console.Write(a[i,j]+ \" \"); } Console.WriteLine(); } } // Print the matrix static void printMatrix(int[,] a, int n) { for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { Console.Write(a[i,j]+ \" \"); } Console.WriteLine(); } } public static void Main(String[] args) { int n = 4; // get the array inputs int [,]a= new int[n,n]; for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { a[i,j] = (i * 10 + j); } } // Print the matrix Console.Write(\"Original Matrix:\\n\"); printMatrix(a, n); int x = 2; // passing the two dimensional // array using a single pointer remove_X_Rows_and_Columns(a, n, x); }} // This code is contributed by shikhasingrajput", "e": 28611, "s": 27259, "text": null }, { "code": "<script> // JavaScript implementation of above approach // Function to remove last x rows // and first x columns from an array function remove_X_Rows_and_Columns(a, n, x) { document.write(\"</br>\" + \"Removing Last \" + x + \" rows and First \" + x + \" columns:\" + \"</br>\"); // Start from the 0th row // and print till n-xth row for (let i = 0; i < n - x; i++) { // Start from the xth column and // print till the n-1th column for (let j = x; j < n; j++) { // Accessing the array using pointers document.write(a[i][j] + \" \"); } document.write(\"</br>\"); } } // Print the matrix function printMatrix(a, n) { for (let i = 0; i < n; i++) { for (let j = 0; j < n; j++) { document.write(a[i][j] + \" \"); } document.write(\"</br>\"); } } let n = 4; // get the array inputs let a = new Array(n); for (let i = 0; i < n; i++) { a[i] = new Array(n); for (let j = 0; j < n; j++) { a[i][j] = (i * 10 + j); } } // Print the matrix document.write(\"Original Matrix:\" + \"</br>\"); printMatrix(a, n); let x = 2; // passing the two dimensional // array using a single pointer remove_X_Rows_and_Columns(a, n, x); </script>", "e": 30034, "s": 28611, "text": null }, { "code": null, "e": 30153, "s": 30034, "text": "Original Matrix:\n0 1 2 3 \n10 11 12 13 \n20 21 22 23 \n30 31 32 33 \n\nRemoving Last 2 rows and First 2 columns:\n2 3 \n12 13" }, { "code": null, "e": 30163, "s": 30155, "text": "ankthon" }, { "code": null, "e": 30178, "s": 30163, "text": "mohit kumar 29" }, { "code": null, "e": 30184, "s": 30178, "text": "ukasp" }, { "code": null, "e": 30205, "s": 30184, "text": "avanitrachhadiya2155" }, { "code": null, "e": 30213, "s": 30205, "text": "rag2127" }, { "code": null, "e": 30227, "s": 30213, "text": "GauravRajput1" }, { "code": null, "e": 30239, "s": 30227, "text": "unknown2108" }, { "code": null, "e": 30249, "s": 30239, "text": "patel2127" }, { "code": null, "e": 30268, "s": 30249, "text": "vaibhavrabadiya117" }, { "code": null, "e": 30275, "s": 30268, "text": "ab2127" }, { "code": null, "e": 30284, "s": 30275, "text": "sweetyty" }, { "code": null, "e": 30296, "s": 30284, "text": "29AjayKumar" }, { "code": null, "e": 30313, "s": 30296, "text": "surinderdawra388" }, { "code": null, "e": 30329, "s": 30313, "text": "simranarora5sos" }, { "code": null, "e": 30346, "s": 30329, "text": "shikhasingrajput" }, { "code": null, "e": 30361, "s": 30346, "text": "sagartomar9927" }, { "code": null, "e": 30374, "s": 30361, "text": "simmytarika5" }, { "code": null, "e": 30387, "s": 30374, "text": "C++ Programs" }, { "code": null, "e": 30394, "s": 30387, "text": "Matrix" }, { "code": null, "e": 30401, "s": 30394, "text": "Matrix" }, { "code": null, "e": 30499, "s": 30401, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30533, "s": 30499, "text": "Shallow Copy and Deep Copy in C++" }, { "code": null, "e": 30593, "s": 30533, "text": "C++ Program to check if a given String is Palindrome or not" }, { "code": null, "e": 30619, "s": 30593, "text": "C++ Program for QuickSort" }, { "code": null, "e": 30693, "s": 30619, "text": "How to find the minimum and maximum element of a Vector using STL in C++?" }, { "code": null, "e": 30715, "s": 30693, "text": "delete keyword in C++" }, { "code": null, "e": 30750, "s": 30715, "text": "Matrix Chain Multiplication | DP-8" }, { "code": null, "e": 30786, "s": 30750, "text": "Print a given matrix in spiral form" }, { "code": null, "e": 30830, "s": 30786, "text": "Program to find largest element in an array" }, { "code": null, "e": 30861, "s": 30830, "text": "Rat in a Maze | Backtracking-2" } ]
File.Move() Method in C# with Examples
21 Apr, 2020 File.Move() is an inbuilt File class method that is used to move a specified file to a new location. This method also provides the option to specify a new file name. Syntax: public static void Move (string sourceFileName, string destFileName); Parameter: This function accepts two parameters which are illustrated below: sourceFileName: This is the specified source file which are going to be moved. It can be absolute or relative path. destFileName: This is the specified destination file where source file is going to be moved. Exceptions: IOException: The destFileName already exists. FileNotFoundException: The sourceFileName was not found. ArgumentNullException: The sourceFileName or destFileName is null. ArgumentException: The sourceFileName or destFileName is a zero-length string, contains only white space, or invalid characters as defined in InvalidPathChars. UnauthorizedAccessException: The caller does not have the required permission. PathTooLongException: The given path, file name, or both exceed the system-defined maximum length. DirectoryNotFoundException: The path specified in sourcefilename or destFileName is invalid. NotSupportedException: The sourceFileName or destFileName is in an invalid format. Below are the programs to illustrate the File.Move() method. Program 1: Before running the below code, a file file.txt is created with some contents shown below- // C# program to illustrate the usage// of File.Move() method // Using System and System.IO namespacesusing System;using System.IO; class GFG { static void Main() { try { // Moving the file file.txt to location C:\gfg.txt File.Move(@"file.txt", @"C:\gfg.txt"); Console.WriteLine("Moved"); } catch (IOException ex) { Console.WriteLine(ex); } }} Output: Moved After running the above code, above output is shown and the existing file file.txt moved to a new location C:\gfg.txt which is shown below- Program 2: Initially no file was created. // C# program to illustrate the usage// of File.Move() method // Using System and System.IO namespacesusing System;using System.IO; class GFG { static void Main() { try { // If file.txt is not found // then an exception will be shown File.Move(@"file.txt", @"C:\gfg.txt"); Console.WriteLine("Moved"); } catch (IOException ex) { Console.WriteLine(ex); } }} Runtime Error: System.IO.FileNotFoundException: Could not find file ‘/home/runner/NutritiousHeavyRegression/file.txt’.File name: ‘/home/runner/NutritiousHeavyRegression/file.txt’at System.IO.File.Move (System.String sourceFileName, System.String destFileName) [0x0007c] in :0at GFG.Main () [0x00000] in :0 C# Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. C# | Multiple inheritance using interfaces Differences Between .NET Core and .NET Framework Extension Method in C# C# | List Class HashSet in C# with Examples C# | .NET Framework (Basic Architecture and Component Stack) Switch Statement in C# Partial Classes in C# Lambda Expressions in C# Hello World in C#
[ { "code": null, "e": 28, "s": 0, "text": "\n21 Apr, 2020" }, { "code": null, "e": 194, "s": 28, "text": "File.Move() is an inbuilt File class method that is used to move a specified file to a new location. This method also provides the option to specify a new file name." }, { "code": null, "e": 202, "s": 194, "text": "Syntax:" }, { "code": null, "e": 272, "s": 202, "text": "public static void Move (string sourceFileName, string destFileName);" }, { "code": null, "e": 349, "s": 272, "text": "Parameter: This function accepts two parameters which are illustrated below:" }, { "code": null, "e": 465, "s": 349, "text": "sourceFileName: This is the specified source file which are going to be moved. It can be absolute or relative path." }, { "code": null, "e": 558, "s": 465, "text": "destFileName: This is the specified destination file where source file is going to be moved." }, { "code": null, "e": 570, "s": 558, "text": "Exceptions:" }, { "code": null, "e": 616, "s": 570, "text": "IOException: The destFileName already exists." }, { "code": null, "e": 673, "s": 616, "text": "FileNotFoundException: The sourceFileName was not found." }, { "code": null, "e": 740, "s": 673, "text": "ArgumentNullException: The sourceFileName or destFileName is null." }, { "code": null, "e": 900, "s": 740, "text": "ArgumentException: The sourceFileName or destFileName is a zero-length string, contains only white space, or invalid characters as defined in InvalidPathChars." }, { "code": null, "e": 979, "s": 900, "text": "UnauthorizedAccessException: The caller does not have the required permission." }, { "code": null, "e": 1078, "s": 979, "text": "PathTooLongException: The given path, file name, or both exceed the system-defined maximum length." }, { "code": null, "e": 1171, "s": 1078, "text": "DirectoryNotFoundException: The path specified in sourcefilename or destFileName is invalid." }, { "code": null, "e": 1254, "s": 1171, "text": "NotSupportedException: The sourceFileName or destFileName is in an invalid format." }, { "code": null, "e": 1315, "s": 1254, "text": "Below are the programs to illustrate the File.Move() method." }, { "code": null, "e": 1416, "s": 1315, "text": "Program 1: Before running the below code, a file file.txt is created with some contents shown below-" }, { "code": "// C# program to illustrate the usage// of File.Move() method // Using System and System.IO namespacesusing System;using System.IO; class GFG { static void Main() { try { // Moving the file file.txt to location C:\\gfg.txt File.Move(@\"file.txt\", @\"C:\\gfg.txt\"); Console.WriteLine(\"Moved\"); } catch (IOException ex) { Console.WriteLine(ex); } }}", "e": 1843, "s": 1416, "text": null }, { "code": null, "e": 1851, "s": 1843, "text": "Output:" }, { "code": null, "e": 1858, "s": 1851, "text": "Moved\n" }, { "code": null, "e": 1998, "s": 1858, "text": "After running the above code, above output is shown and the existing file file.txt moved to a new location C:\\gfg.txt which is shown below-" }, { "code": null, "e": 2040, "s": 1998, "text": "Program 2: Initially no file was created." }, { "code": "// C# program to illustrate the usage// of File.Move() method // Using System and System.IO namespacesusing System;using System.IO; class GFG { static void Main() { try { // If file.txt is not found // then an exception will be shown File.Move(@\"file.txt\", @\"C:\\gfg.txt\"); Console.WriteLine(\"Moved\"); } catch (IOException ex) { Console.WriteLine(ex); } }}", "e": 2490, "s": 2040, "text": null }, { "code": null, "e": 2505, "s": 2490, "text": "Runtime Error:" }, { "code": null, "e": 2796, "s": 2505, "text": "System.IO.FileNotFoundException: Could not find file ‘/home/runner/NutritiousHeavyRegression/file.txt’.File name: ‘/home/runner/NutritiousHeavyRegression/file.txt’at System.IO.File.Move (System.String sourceFileName, System.String destFileName) [0x0007c] in :0at GFG.Main () [0x00000] in :0" }, { "code": null, "e": 2799, "s": 2796, "text": "C#" }, { "code": null, "e": 2897, "s": 2799, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2940, "s": 2897, "text": "C# | Multiple inheritance using interfaces" }, { "code": null, "e": 2989, "s": 2940, "text": "Differences Between .NET Core and .NET Framework" }, { "code": null, "e": 3012, "s": 2989, "text": "Extension Method in C#" }, { "code": null, "e": 3028, "s": 3012, "text": "C# | List Class" }, { "code": null, "e": 3056, "s": 3028, "text": "HashSet in C# with Examples" }, { "code": null, "e": 3117, "s": 3056, "text": "C# | .NET Framework (Basic Architecture and Component Stack)" }, { "code": null, "e": 3140, "s": 3117, "text": "Switch Statement in C#" }, { "code": null, "e": 3162, "s": 3140, "text": "Partial Classes in C#" }, { "code": null, "e": 3187, "s": 3162, "text": "Lambda Expressions in C#" } ]
Python | Convert List of lists to list of Strings
22 Jun, 2022 Interconversion of data is very popular nowadays and has many applications. In this scenario, we can have a problem in which we need to convert a list of lists, i.e matrix into list of strings. Let’s discuss certain ways in which this task can be performed. Method #1 : Using list comprehension + join() The combination of above functionalities can be used to perform this task. In this, we perform the task of iteration using list comprehension and join() is used to perform task of joining string to list of strings. Python3 # Python3 code to demonstrate working of# Convert List of lists to list of Strings# using list comprehension + join() # initialize listtest_list = [["g", "f", "g"], ["i", "s"], ["b", "e", "s", "t"]] # printing original listprint("The original list : " + str(test_list)) # Convert List of lists to list of Strings# using list comprehension + join()res = [''.join(ele) for ele in test_list] # printing resultprint("The String of list is : " + str(res)) The original list : [['g', 'f', 'g'], ['i', 's'], ['b', 'e', 's', 't']] The String of list is : ['gfg', 'is', 'best'] Method #2: Using map() + join() The task above can also be performed using combination of above methods. In this, we perform the task of conversion using join and iteration using map(). Python3 # Python3 code to demonstrate working of# Convert List of lists to list of Strings# using map() + join() # initialize listtest_list = [["g", "f", "g"], ["i", "s"], ["b", "e", "s", "t"]] # printing original listprint("The original list : " + str(test_list)) # Convert List of lists to list of Strings# using map() + join()res = list(map(''.join, test_list)) # printing resultprint("The String of list is : " + str(res)) The original list : [['g', 'f', 'g'], ['i', 's'], ['b', 'e', 's', 't']] The String of list is : ['gfg', 'is', 'best'] vinayedula Python list-programs Python string-programs Python-list-of-lists Python Python Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Different ways to create Pandas Dataframe Enumerate() in Python Python String | replace() How to Install PIP on Windows ? *args and **kwargs in Python Defaultdict in Python Python | Get dictionary keys as a list Python | Convert a list to dictionary Python | Convert string dictionary to dictionary Python Program for Fibonacci numbers
[ { "code": null, "e": 28, "s": 0, "text": "\n22 Jun, 2022" }, { "code": null, "e": 287, "s": 28, "text": "Interconversion of data is very popular nowadays and has many applications. In this scenario, we can have a problem in which we need to convert a list of lists, i.e matrix into list of strings. Let’s discuss certain ways in which this task can be performed. " }, { "code": null, "e": 334, "s": 287, "text": "Method #1 : Using list comprehension + join() " }, { "code": null, "e": 550, "s": 334, "text": "The combination of above functionalities can be used to perform this task. In this, we perform the task of iteration using list comprehension and join() is used to perform task of joining string to list of strings. " }, { "code": null, "e": 558, "s": 550, "text": "Python3" }, { "code": "# Python3 code to demonstrate working of# Convert List of lists to list of Strings# using list comprehension + join() # initialize listtest_list = [[\"g\", \"f\", \"g\"], [\"i\", \"s\"], [\"b\", \"e\", \"s\", \"t\"]] # printing original listprint(\"The original list : \" + str(test_list)) # Convert List of lists to list of Strings# using list comprehension + join()res = [''.join(ele) for ele in test_list] # printing resultprint(\"The String of list is : \" + str(res))", "e": 1009, "s": 558, "text": null }, { "code": null, "e": 1127, "s": 1009, "text": "The original list : [['g', 'f', 'g'], ['i', 's'], ['b', 'e', 's', 't']]\nThe String of list is : ['gfg', 'is', 'best']" }, { "code": null, "e": 1162, "s": 1127, "text": " Method #2: Using map() + join() " }, { "code": null, "e": 1317, "s": 1162, "text": "The task above can also be performed using combination of above methods. In this, we perform the task of conversion using join and iteration using map(). " }, { "code": null, "e": 1325, "s": 1317, "text": "Python3" }, { "code": "# Python3 code to demonstrate working of# Convert List of lists to list of Strings# using map() + join() # initialize listtest_list = [[\"g\", \"f\", \"g\"], [\"i\", \"s\"], [\"b\", \"e\", \"s\", \"t\"]] # printing original listprint(\"The original list : \" + str(test_list)) # Convert List of lists to list of Strings# using map() + join()res = list(map(''.join, test_list)) # printing resultprint(\"The String of list is : \" + str(res))", "e": 1744, "s": 1325, "text": null }, { "code": null, "e": 1862, "s": 1744, "text": "The original list : [['g', 'f', 'g'], ['i', 's'], ['b', 'e', 's', 't']]\nThe String of list is : ['gfg', 'is', 'best']" }, { "code": null, "e": 1873, "s": 1862, "text": "vinayedula" }, { "code": null, "e": 1894, "s": 1873, "text": "Python list-programs" }, { "code": null, "e": 1917, "s": 1894, "text": "Python string-programs" }, { "code": null, "e": 1938, "s": 1917, "text": "Python-list-of-lists" }, { "code": null, "e": 1945, "s": 1938, "text": "Python" }, { "code": null, "e": 1961, "s": 1945, "text": "Python Programs" }, { "code": null, "e": 2059, "s": 1961, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2101, "s": 2059, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 2123, "s": 2101, "text": "Enumerate() in Python" }, { "code": null, "e": 2149, "s": 2123, "text": "Python String | replace()" }, { "code": null, "e": 2181, "s": 2149, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 2210, "s": 2181, "text": "*args and **kwargs in Python" }, { "code": null, "e": 2232, "s": 2210, "text": "Defaultdict in Python" }, { "code": null, "e": 2271, "s": 2232, "text": "Python | Get dictionary keys as a list" }, { "code": null, "e": 2309, "s": 2271, "text": "Python | Convert a list to dictionary" }, { "code": null, "e": 2358, "s": 2309, "text": "Python | Convert string dictionary to dictionary" } ]
Streaming Stored Video
02 Dec, 2019 Streaming of videos involve, storing of prerecorded videos on servers. Users send request to those servers. Users may watch the video from the start till the end, and may pause it anytime, do a forward or reverse skip, or stop the video whenever they want to do so. There are 3 video streaming categories: 1. UDP Streaming 2. HTTP Streaming 3. Adaptive HTTP Streaming Usually, today’s system employs HTTP and Adaptive HTTP Streaming. Common characteristic of these three streaming technique is that the extensive use of Client-Side Buffering. Advantages of Client Buffering: Client side buffer absorbs variations in server-client delay. Until the delayed packet is received by the client, the received-but not yet-played video will be played.Even if bandwidth drops, user can view the video until the buffer is completely drained. Client side buffer absorbs variations in server-client delay. Until the delayed packet is received by the client, the received-but not yet-played video will be played. Even if bandwidth drops, user can view the video until the buffer is completely drained. 1. UDP STREAMING:UDP servers send video chunks (Chunk: unit of information that contains either control information or user data) to clients, based on client’s consumption rate. It transmits chunks at a rate, that matches client’s video consumption rate by clocking out video chunks over UDP over steady state. For example, Video consumption rate = 2Mbps Capacity of one UDP packet = 8000 bits Therefore, Transmission rate = 8000 bits/2 Mbps = 4000 msec Properties: UDP does not use congestion-control mechanism. Video chunks are encapsulated before transmission using RTT (Real-Time Transport) Protocol. Additional client-server path is maintained to inform the client state to server like pause, resume, skip and so on. Drawbacks: Bandwidth is unpredictable and varying between client and server. UDP streaming requires a separate media control server like RTSP server(Real-Time Streaming Protocol) to track client state(pause, resume etc). Devices are configured with firewalls to block UDP traffic which prevents the reception of UDP packets to clients. 2. HTTP STREAMING:Video is stored in an HTTP server as a simple ordinary file with a unique URL. Client establishes TCP connection with server and issues a HTTP GET request for that URL. Server sends the video file along with an HTTP RESPONSE. Now the client buffer grabs the video and then displayed on user screen. Advantages: Use of HTTP over TCP allows the video to traverse firewalls and NATs easily. Does not need any media control servers like RTSP servers causing reduction in cost of large-scale deployment over internet. Disadvantages: Latency or lag between a video is recorded and played. This can make the viewers more annoyed and irritated. Only a few milliseconds delay is acceptable. Early pre-fetching of video, but, what if, the user stops playing the video at a early stage? Wastage of data is not appreciated. All clients receive the same encoding of the video, despite the large variations in bandwidth amount available to different clients and also for same client over time. Uses:Youtube and Netflix uses HTTP streaming mechanism. 3. ADAPTIVE HTTP STREAMING:The major drawbacks of HTTP streaming, lead to development of new type of HTTP based streaming referred to as DASH (Dynamic Adaptive Streaming over HTTP). Videos are encoded into different bit rate versions, having different quality. The host makes a dynamic video request of few seconds in length from different bit versions. When bandwidth is high, high bit rate chunks are received hence high quality similarly, low quality video during low bandwidth. Advantages: DASH uses the user to switch over different qualities of video on screen. Client can use HTTP byte-range request to precisely control the amount of pre-fetched video that is locally buffered. DASH also stores the audio in different versions with different quality and different bit-rate with unique URL. So the client dynamically selects the video and audio chunks and synchronizes it locally in the play-out. Uses:COMCAST uses DASH for streaming high quality video contents. Computer Networks Computer Networks Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Wireless Application Protocol GSM in Wireless Communication Secure Socket Layer (SSL) Mobile Internet Protocol (or Mobile IP) Advanced Encryption Standard (AES) Introduction of Mobile Ad hoc Network (MANET) Cryptography and its Types Dynamic Host Configuration Protocol (DHCP) Intrusion Detection System (IDS) Difference between FDMA, TDMA and CDMA
[ { "code": null, "e": 28, "s": 0, "text": "\n02 Dec, 2019" }, { "code": null, "e": 99, "s": 28, "text": "Streaming of videos involve, storing of prerecorded videos on servers." }, { "code": null, "e": 136, "s": 99, "text": "Users send request to those servers." }, { "code": null, "e": 294, "s": 136, "text": "Users may watch the video from the start till the end, and may pause it anytime, do a forward or reverse skip, or stop the video whenever they want to do so." }, { "code": null, "e": 334, "s": 294, "text": "There are 3 video streaming categories:" }, { "code": null, "e": 397, "s": 334, "text": "1. UDP Streaming\n2. HTTP Streaming\n3. Adaptive HTTP Streaming " }, { "code": null, "e": 463, "s": 397, "text": "Usually, today’s system employs HTTP and Adaptive HTTP Streaming." }, { "code": null, "e": 572, "s": 463, "text": "Common characteristic of these three streaming technique is that the extensive use of Client-Side Buffering." }, { "code": null, "e": 604, "s": 572, "text": "Advantages of Client Buffering:" }, { "code": null, "e": 860, "s": 604, "text": "Client side buffer absorbs variations in server-client delay. Until the delayed packet is received by the client, the received-but not yet-played video will be played.Even if bandwidth drops, user can view the video until the buffer is completely drained." }, { "code": null, "e": 1028, "s": 860, "text": "Client side buffer absorbs variations in server-client delay. Until the delayed packet is received by the client, the received-but not yet-played video will be played." }, { "code": null, "e": 1117, "s": 1028, "text": "Even if bandwidth drops, user can view the video until the buffer is completely drained." }, { "code": null, "e": 1428, "s": 1117, "text": "1. UDP STREAMING:UDP servers send video chunks (Chunk: unit of information that contains either control information or user data) to clients, based on client’s consumption rate. It transmits chunks at a rate, that matches client’s video consumption rate by clocking out video chunks over UDP over steady state." }, { "code": null, "e": 1441, "s": 1428, "text": "For example," }, { "code": null, "e": 1574, "s": 1441, "text": "Video consumption rate = 2Mbps\nCapacity of one UDP packet = 8000 bits\n\nTherefore, \nTransmission rate = 8000 bits/2 Mbps = 4000 msec " }, { "code": null, "e": 1586, "s": 1574, "text": "Properties:" }, { "code": null, "e": 1725, "s": 1586, "text": "UDP does not use congestion-control mechanism. Video chunks are encapsulated before transmission using RTT (Real-Time Transport) Protocol." }, { "code": null, "e": 1842, "s": 1725, "text": "Additional client-server path is maintained to inform the client state to server like pause, resume, skip and so on." }, { "code": null, "e": 1853, "s": 1842, "text": "Drawbacks:" }, { "code": null, "e": 1919, "s": 1853, "text": "Bandwidth is unpredictable and varying between client and server." }, { "code": null, "e": 2063, "s": 1919, "text": "UDP streaming requires a separate media control server like RTSP server(Real-Time Streaming Protocol) to track client state(pause, resume etc)." }, { "code": null, "e": 2178, "s": 2063, "text": "Devices are configured with firewalls to block UDP traffic which prevents the reception of UDP packets to clients." }, { "code": null, "e": 2495, "s": 2178, "text": "2. HTTP STREAMING:Video is stored in an HTTP server as a simple ordinary file with a unique URL. Client establishes TCP connection with server and issues a HTTP GET request for that URL. Server sends the video file along with an HTTP RESPONSE. Now the client buffer grabs the video and then displayed on user screen." }, { "code": null, "e": 2507, "s": 2495, "text": "Advantages:" }, { "code": null, "e": 2584, "s": 2507, "text": "Use of HTTP over TCP allows the video to traverse firewalls and NATs easily." }, { "code": null, "e": 2709, "s": 2584, "text": "Does not need any media control servers like RTSP servers causing reduction in cost of large-scale deployment over internet." }, { "code": null, "e": 2724, "s": 2709, "text": "Disadvantages:" }, { "code": null, "e": 2878, "s": 2724, "text": "Latency or lag between a video is recorded and played. This can make the viewers more annoyed and irritated. Only a few milliseconds delay is acceptable." }, { "code": null, "e": 3008, "s": 2878, "text": "Early pre-fetching of video, but, what if, the user stops playing the video at a early stage? Wastage of data is not appreciated." }, { "code": null, "e": 3176, "s": 3008, "text": "All clients receive the same encoding of the video, despite the large variations in bandwidth amount available to different clients and also for same client over time." }, { "code": null, "e": 3232, "s": 3176, "text": "Uses:Youtube and Netflix uses HTTP streaming mechanism." }, { "code": null, "e": 3714, "s": 3232, "text": "3. ADAPTIVE HTTP STREAMING:The major drawbacks of HTTP streaming, lead to development of new type of HTTP based streaming referred to as DASH (Dynamic Adaptive Streaming over HTTP). Videos are encoded into different bit rate versions, having different quality. The host makes a dynamic video request of few seconds in length from different bit versions. When bandwidth is high, high bit rate chunks are received hence high quality similarly, low quality video during low bandwidth." }, { "code": null, "e": 3726, "s": 3714, "text": "Advantages:" }, { "code": null, "e": 3800, "s": 3726, "text": "DASH uses the user to switch over different qualities of video on screen." }, { "code": null, "e": 3918, "s": 3800, "text": "Client can use HTTP byte-range request to precisely control the amount of pre-fetched video that is locally buffered." }, { "code": null, "e": 4030, "s": 3918, "text": "DASH also stores the audio in different versions with different quality and different bit-rate with unique URL." }, { "code": null, "e": 4136, "s": 4030, "text": "So the client dynamically selects the video and audio chunks and synchronizes it locally in the play-out." }, { "code": null, "e": 4202, "s": 4136, "text": "Uses:COMCAST uses DASH for streaming high quality video contents." }, { "code": null, "e": 4220, "s": 4202, "text": "Computer Networks" }, { "code": null, "e": 4238, "s": 4220, "text": "Computer Networks" }, { "code": null, "e": 4336, "s": 4238, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 4366, "s": 4336, "text": "Wireless Application Protocol" }, { "code": null, "e": 4396, "s": 4366, "text": "GSM in Wireless Communication" }, { "code": null, "e": 4422, "s": 4396, "text": "Secure Socket Layer (SSL)" }, { "code": null, "e": 4462, "s": 4422, "text": "Mobile Internet Protocol (or Mobile IP)" }, { "code": null, "e": 4497, "s": 4462, "text": "Advanced Encryption Standard (AES)" }, { "code": null, "e": 4543, "s": 4497, "text": "Introduction of Mobile Ad hoc Network (MANET)" }, { "code": null, "e": 4570, "s": 4543, "text": "Cryptography and its Types" }, { "code": null, "e": 4613, "s": 4570, "text": "Dynamic Host Configuration Protocol (DHCP)" }, { "code": null, "e": 4646, "s": 4613, "text": "Intrusion Detection System (IDS)" } ]
Golismero – Scan Website, Vulnerability Scanning, WEB Server in Kali Linux
17 Jun, 2021 Golismero is a free and open-source tool available on GitHub. Golismero is an Open Source Intelligence and Information Gathering Tool based on (OSINT). Golismero is capable of doing everything almost you need for reconnaissance as per your need it can perform reconnaissance easily. Golismero works as an open-source tool intelligence tool. It integrates with just about every data source available and utilizes a range of methods for data analysis. Golismero is written in python language. You must have python language installed in your Kali Linux system in order to use Gasmask tool. This too is used to get various information about our target. This information includes Real platform independence. This also includes Tested on Windows, Linux, *BSD, and OS X. Golismero Integrates with standards: CWE, Step 1: Open your Kali Linux and then Open your Terminal. sudo bash apt-get install python2.7 python2.7-dev python-pipn docutils git perl map sslscan Step 2: Now install the tool using the following command. git clone https://github.com/golismero/golismero.git cd golismero pip install -r requirements.txt Step 3: The tool has been downloaded and running successfully now use the following command to run the tool. ./golismero.py Example 1: Use the golismero tool to scan www.google.com ./golismero.py scan http://www.google.com Example 2: Use the golismero tool to scan www.geeksforgeeks.org ./golismero.py scan https://www.geeksforgeeks.org Kali-Linux Linux-Tools Linux-Unix Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Docker - COPY Instruction scp command in Linux with Examples chown command in Linux with Examples SED command in Linux | Set 2 mv command in Linux with examples chmod command in Linux with examples nohup Command in Linux with Examples Introduction to Linux Operating System Array Basics in Shell Scripting | Set 1 Basic Operators in Shell Scripting
[ { "code": null, "e": 28, "s": 0, "text": "\n17 Jun, 2021" }, { "code": null, "e": 835, "s": 28, "text": "Golismero is a free and open-source tool available on GitHub. Golismero is an Open Source Intelligence and Information Gathering Tool based on (OSINT). Golismero is capable of doing everything almost you need for reconnaissance as per your need it can perform reconnaissance easily. Golismero works as an open-source tool intelligence tool. It integrates with just about every data source available and utilizes a range of methods for data analysis. Golismero is written in python language. You must have python language installed in your Kali Linux system in order to use Gasmask tool. This too is used to get various information about our target. This information includes Real platform independence. This also includes Tested on Windows, Linux, *BSD, and OS X. Golismero Integrates with standards: CWE, " }, { "code": null, "e": 894, "s": 835, "text": "Step 1: Open your Kali Linux and then Open your Terminal. " }, { "code": null, "e": 904, "s": 894, "text": "sudo bash" }, { "code": null, "e": 986, "s": 904, "text": "apt-get install python2.7 python2.7-dev python-pipn docutils git perl map sslscan" }, { "code": null, "e": 1045, "s": 986, "text": "Step 2: Now install the tool using the following command. " }, { "code": null, "e": 1143, "s": 1045, "text": "git clone https://github.com/golismero/golismero.git\ncd golismero\npip install -r requirements.txt" }, { "code": null, "e": 1252, "s": 1143, "text": "Step 3: The tool has been downloaded and running successfully now use the following command to run the tool." }, { "code": null, "e": 1267, "s": 1252, "text": "./golismero.py" }, { "code": null, "e": 1324, "s": 1267, "text": "Example 1: Use the golismero tool to scan www.google.com" }, { "code": null, "e": 1367, "s": 1324, "text": "./golismero.py scan http://www.google.com " }, { "code": null, "e": 1431, "s": 1367, "text": "Example 2: Use the golismero tool to scan www.geeksforgeeks.org" }, { "code": null, "e": 1481, "s": 1431, "text": "./golismero.py scan https://www.geeksforgeeks.org" }, { "code": null, "e": 1492, "s": 1481, "text": "Kali-Linux" }, { "code": null, "e": 1504, "s": 1492, "text": "Linux-Tools" }, { "code": null, "e": 1515, "s": 1504, "text": "Linux-Unix" }, { "code": null, "e": 1613, "s": 1515, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1639, "s": 1613, "text": "Docker - COPY Instruction" }, { "code": null, "e": 1674, "s": 1639, "text": "scp command in Linux with Examples" }, { "code": null, "e": 1711, "s": 1674, "text": "chown command in Linux with Examples" }, { "code": null, "e": 1740, "s": 1711, "text": "SED command in Linux | Set 2" }, { "code": null, "e": 1774, "s": 1740, "text": "mv command in Linux with examples" }, { "code": null, "e": 1811, "s": 1774, "text": "chmod command in Linux with examples" }, { "code": null, "e": 1848, "s": 1811, "text": "nohup Command in Linux with Examples" }, { "code": null, "e": 1887, "s": 1848, "text": "Introduction to Linux Operating System" }, { "code": null, "e": 1927, "s": 1887, "text": "Array Basics in Shell Scripting | Set 1" } ]
Remove duplicates from an unsorted array using STL in C++
03 Jun, 2019 Given an unsorted array, the task is to remove the duplicate elements from the array using STL in C++ Examples: Input: arr[] = {1, 2, 5, 1, 7, 2, 4, 2} Output: arr[] = {1, 2, 4, 5, 7} Input: arr[] = {1, 2, 4, 3, 5, 4, 4, 2, 5} Output: arr[] = {1, 2, 3, 4, 5} Approach:The duplicates of the array can be removed using the unique() function provided in STL. Below is the implementation of the above approach. #include <bits/stdc++.h>using namespace std; // Function to remove duplicate elementsvoid remDup(int arr[], int n){ // Initialise a vector // to store the array values // and an iterator // to traverse this vector vector<int> v(arr, arr + n); vector<int>::iterator it; // sorting vector sort(v.begin(), v.end()); // using unique() method // to remove duplicates it = unique(v.begin(), v.end()); // resize the new vector v.resize(distance(v.begin(), it)); // Print the array with duplicates removed cout << "\nAfter removing duplicates:\n"; for (it = v.begin(); it != v.end(); ++it) cout << *it << " "; cout << '\n';} // Driver codeint main(){ int arr[] = { 1, 2, 5, 1, 7, 2, 4, 2 }; int n = sizeof(arr) / sizeof(arr[0]); // Print array cout << "\nBefore removing duplicates:\n"; for (int i = 0; i < n; i++) cout << arr[i] << " "; // call remDup() remDup(arr, n); return 0;} Before removing duplicates: 1 2 5 1 7 2 4 2 After removing duplicates: 1 2 4 5 7 cpp-array STL C++ Programs STL Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Shallow Copy and Deep Copy in C++ C++ Program to check if a given String is Palindrome or not How to find the minimum and maximum element of a Vector using STL in C++? C++ Program for QuickSort C Program to Swap two Numbers delete keyword in C++ Passing a function as a parameter in C++ cin in C++ Enumerated Types or Enums in C++ Const keyword in C++
[ { "code": null, "e": 28, "s": 0, "text": "\n03 Jun, 2019" }, { "code": null, "e": 130, "s": 28, "text": "Given an unsorted array, the task is to remove the duplicate elements from the array using STL in C++" }, { "code": null, "e": 140, "s": 130, "text": "Examples:" }, { "code": null, "e": 289, "s": 140, "text": "Input: arr[] = {1, 2, 5, 1, 7, 2, 4, 2}\nOutput: arr[] = {1, 2, 4, 5, 7}\n\nInput: arr[] = {1, 2, 4, 3, 5, 4, 4, 2, 5}\nOutput: arr[] = {1, 2, 3, 4, 5}\n" }, { "code": null, "e": 386, "s": 289, "text": "Approach:The duplicates of the array can be removed using the unique() function provided in STL." }, { "code": null, "e": 437, "s": 386, "text": "Below is the implementation of the above approach." }, { "code": "#include <bits/stdc++.h>using namespace std; // Function to remove duplicate elementsvoid remDup(int arr[], int n){ // Initialise a vector // to store the array values // and an iterator // to traverse this vector vector<int> v(arr, arr + n); vector<int>::iterator it; // sorting vector sort(v.begin(), v.end()); // using unique() method // to remove duplicates it = unique(v.begin(), v.end()); // resize the new vector v.resize(distance(v.begin(), it)); // Print the array with duplicates removed cout << \"\\nAfter removing duplicates:\\n\"; for (it = v.begin(); it != v.end(); ++it) cout << *it << \" \"; cout << '\\n';} // Driver codeint main(){ int arr[] = { 1, 2, 5, 1, 7, 2, 4, 2 }; int n = sizeof(arr) / sizeof(arr[0]); // Print array cout << \"\\nBefore removing duplicates:\\n\"; for (int i = 0; i < n; i++) cout << arr[i] << \" \"; // call remDup() remDup(arr, n); return 0;}", "e": 1420, "s": 437, "text": null }, { "code": null, "e": 1503, "s": 1420, "text": "Before removing duplicates:\n1 2 5 1 7 2 4 2 \nAfter removing duplicates:\n1 2 4 5 7\n" }, { "code": null, "e": 1513, "s": 1503, "text": "cpp-array" }, { "code": null, "e": 1517, "s": 1513, "text": "STL" }, { "code": null, "e": 1530, "s": 1517, "text": "C++ Programs" }, { "code": null, "e": 1534, "s": 1530, "text": "STL" }, { "code": null, "e": 1632, "s": 1534, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1666, "s": 1632, "text": "Shallow Copy and Deep Copy in C++" }, { "code": null, "e": 1726, "s": 1666, "text": "C++ Program to check if a given String is Palindrome or not" }, { "code": null, "e": 1800, "s": 1726, "text": "How to find the minimum and maximum element of a Vector using STL in C++?" }, { "code": null, "e": 1826, "s": 1800, "text": "C++ Program for QuickSort" }, { "code": null, "e": 1856, "s": 1826, "text": "C Program to Swap two Numbers" }, { "code": null, "e": 1878, "s": 1856, "text": "delete keyword in C++" }, { "code": null, "e": 1919, "s": 1878, "text": "Passing a function as a parameter in C++" }, { "code": null, "e": 1930, "s": 1919, "text": "cin in C++" }, { "code": null, "e": 1963, "s": 1930, "text": "Enumerated Types or Enums in C++" } ]
Python Script to Shutdown your PC using Voice Commands
08 Oct, 2021 Yes, it is possible with the help of terminal and some modules in Python through which one can shut down a PC by just using voice commands OS module: It is an in-built module in python that provides function for interacting with the operating system. Speech Recognition module: It is an external module in python whose functionality depends on the voice commands of the user. Pyttsx3 module: it is a text-to-speech conversion library in Python. pip install SpeechRecognition pip install pyttsx3 In terminal there are many tags for the shutdown command, however we will use the /s tag with it to shut down the system. Step 1: Create a class Gfg and then create its methods, create takeCommands() method to take commands as input. Python3 import SpeechRecognition as sr # Create classclass Gfg: # Method to take voice commands as input def takeCommands(self): # Using Recognizer and Microphone Method for input voice commands r = sr.Recognizer() with sr.Microphone() as source: print('Listening') # Number pf seconds of non-speaking audio before # a phrase is considered complete r.pause_threshold = 0.7 audio = r.listen(source) # Voice input is identified try: # Listening voice commands in indian english print("Recognizing") Query = r.recognize_google(audio, language='en-in') # Displaying the voice command print("the query is printed='", Query, "'") except Exception as e: # Displaying exception print(e) print("Say that again sir") return "None" return Query Step 2: Create a Speak() method so that the computer can communicate with the user. Python3 # Method for voice outputdef Speak(self, audio): # Constructor call for pyttsx3.init() engine = pyttsx3.init('sapi5') # Setting voice type and id voices = engine.getProperty('voices') engine.setProperty('voice', voices[1].id) engine.say(audio) engine.runAndWait() Step 3: Now create the quitSelf() to shut down the computer. Python3 # Method to self shut down systemdef quitSelf(self): self.Speak("do u want to switch off the computer sir") # Input voice command take = self.takeCommand() choice = take if choice == 'yes': # Shutting down print("Shutting down the computer") self.Speak("Shutting the computer") os.system("shutdown /s /t 30") if choice == 'no': # Idle print("Thank u sir") self.Speak("Thank u sir") Step 4: Now in the driver code create a Gfg object and call the quitSelf() method. Python3 # Driver codeif __name__ == '__main__': # Creating gfg object Maam = Gfg() # Calling the method to self shut down Maam.quitSelf() Python # Importing required modulesimport osimport pyttsx3import speech_recognition as sr # Creating classclass Gfg: # Method to take choice commands as input def takeCommands(self): # Using Recognizer and Microphone Method for input voice commands r = sr.Recognizer() with sr.Microphone() as source: print('Listening') # Number pf seconds of non-speaking audio before # a phrase is considered complete r.pause_threshold = 0.7 audio = r.listen(source) # Voice input is identified try: # Listening voice commands in indian english print("Recognizing") Query = r.recognize_google(audio, language='en-in') # Displaying the voice command print("the query is printed='", Query, "'") except Exception as e: # Displaying exception print(e) # Handling exception print("Say that again sir") return "None" return Query # Method for voice output def Speak(self, audio): # Constructor call for pyttsx3.init() engine = pyttsx3.init('sapi5') # Setting voice type and id voices = engine.getProperty('voices') engine.setProperty('voice', voices[1].id) engine.say(audio) engine.runAndWait() # Method to self shut down system def quitSelf(self): self.Speak("do u want to switch off the computer sir") # Input voice command take = self.takeCommand() choice = take if choice == 'yes': # Shutting down print("Shutting down the computer") self.Speak("Shutting the computer") os.system("shutdown /s /t 30") if choice == 'no': # Idle print("Thank u sir") self.Speak("Thank u sir") # Driver code if __name__ == '__main__': Maam = Gfg() Maam.quitSelf() Output: kalrap615 prachisoda1234 python-utility Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? 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": 52, "s": 24, "text": "\n08 Oct, 2021" }, { "code": null, "e": 191, "s": 52, "text": "Yes, it is possible with the help of terminal and some modules in Python through which one can shut down a PC by just using voice commands" }, { "code": null, "e": 303, "s": 191, "text": "OS module: It is an in-built module in python that provides function for interacting with the operating system." }, { "code": null, "e": 428, "s": 303, "text": "Speech Recognition module: It is an external module in python whose functionality depends on the voice commands of the user." }, { "code": null, "e": 497, "s": 428, "text": "Pyttsx3 module: it is a text-to-speech conversion library in Python." }, { "code": null, "e": 547, "s": 497, "text": "pip install SpeechRecognition\npip install pyttsx3" }, { "code": null, "e": 669, "s": 547, "text": "In terminal there are many tags for the shutdown command, however we will use the /s tag with it to shut down the system." }, { "code": null, "e": 781, "s": 669, "text": "Step 1: Create a class Gfg and then create its methods, create takeCommands() method to take commands as input." }, { "code": null, "e": 789, "s": 781, "text": "Python3" }, { "code": "import SpeechRecognition as sr # Create classclass Gfg: # Method to take voice commands as input def takeCommands(self): # Using Recognizer and Microphone Method for input voice commands r = sr.Recognizer() with sr.Microphone() as source: print('Listening') # Number pf seconds of non-speaking audio before # a phrase is considered complete r.pause_threshold = 0.7 audio = r.listen(source) # Voice input is identified try: # Listening voice commands in indian english print(\"Recognizing\") Query = r.recognize_google(audio, language='en-in') # Displaying the voice command print(\"the query is printed='\", Query, \"'\") except Exception as e: # Displaying exception print(e) print(\"Say that again sir\") return \"None\" return Query", "e": 1881, "s": 789, "text": null }, { "code": null, "e": 1965, "s": 1881, "text": "Step 2: Create a Speak() method so that the computer can communicate with the user." }, { "code": null, "e": 1973, "s": 1965, "text": "Python3" }, { "code": "# Method for voice outputdef Speak(self, audio): # Constructor call for pyttsx3.init() engine = pyttsx3.init('sapi5') # Setting voice type and id voices = engine.getProperty('voices') engine.setProperty('voice', voices[1].id) engine.say(audio) engine.runAndWait()", "e": 2266, "s": 1973, "text": null }, { "code": null, "e": 2328, "s": 2266, "text": "Step 3: Now create the quitSelf() to shut down the computer. " }, { "code": null, "e": 2336, "s": 2328, "text": "Python3" }, { "code": "# Method to self shut down systemdef quitSelf(self): self.Speak(\"do u want to switch off the computer sir\") # Input voice command take = self.takeCommand() choice = take if choice == 'yes': # Shutting down print(\"Shutting down the computer\") self.Speak(\"Shutting the computer\") os.system(\"shutdown /s /t 30\") if choice == 'no': # Idle print(\"Thank u sir\") self.Speak(\"Thank u sir\")", "e": 2808, "s": 2336, "text": null }, { "code": null, "e": 2894, "s": 2811, "text": "Step 4: Now in the driver code create a Gfg object and call the quitSelf() method." }, { "code": null, "e": 2902, "s": 2894, "text": "Python3" }, { "code": "# Driver codeif __name__ == '__main__': # Creating gfg object Maam = Gfg() # Calling the method to self shut down Maam.quitSelf()", "e": 3054, "s": 2902, "text": null }, { "code": null, "e": 3061, "s": 3054, "text": "Python" }, { "code": "# Importing required modulesimport osimport pyttsx3import speech_recognition as sr # Creating classclass Gfg: # Method to take choice commands as input def takeCommands(self): # Using Recognizer and Microphone Method for input voice commands r = sr.Recognizer() with sr.Microphone() as source: print('Listening') # Number pf seconds of non-speaking audio before # a phrase is considered complete r.pause_threshold = 0.7 audio = r.listen(source) # Voice input is identified try: # Listening voice commands in indian english print(\"Recognizing\") Query = r.recognize_google(audio, language='en-in') # Displaying the voice command print(\"the query is printed='\", Query, \"'\") except Exception as e: # Displaying exception print(e) # Handling exception print(\"Say that again sir\") return \"None\" return Query # Method for voice output def Speak(self, audio): # Constructor call for pyttsx3.init() engine = pyttsx3.init('sapi5') # Setting voice type and id voices = engine.getProperty('voices') engine.setProperty('voice', voices[1].id) engine.say(audio) engine.runAndWait() # Method to self shut down system def quitSelf(self): self.Speak(\"do u want to switch off the computer sir\") # Input voice command take = self.takeCommand() choice = take if choice == 'yes': # Shutting down print(\"Shutting down the computer\") self.Speak(\"Shutting the computer\") os.system(\"shutdown /s /t 30\") if choice == 'no': # Idle print(\"Thank u sir\") self.Speak(\"Thank u sir\") # Driver code if __name__ == '__main__': Maam = Gfg() Maam.quitSelf()", "e": 5163, "s": 3061, "text": null }, { "code": null, "e": 5171, "s": 5163, "text": "Output:" }, { "code": null, "e": 5181, "s": 5171, "text": "kalrap615" }, { "code": null, "e": 5196, "s": 5181, "text": "prachisoda1234" }, { "code": null, "e": 5211, "s": 5196, "text": "python-utility" }, { "code": null, "e": 5218, "s": 5211, "text": "Python" }, { "code": null, "e": 5316, "s": 5218, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 5348, "s": 5316, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 5375, "s": 5348, "text": "Python Classes and Objects" }, { "code": null, "e": 5396, "s": 5375, "text": "Python OOPs Concepts" }, { "code": null, "e": 5419, "s": 5396, "text": "Introduction To PYTHON" }, { "code": null, "e": 5450, "s": 5419, "text": "Python | os.path.join() method" }, { "code": null, "e": 5506, "s": 5450, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 5548, "s": 5506, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 5590, "s": 5548, "text": "Check if element exists in list in Python" }, { "code": null, "e": 5629, "s": 5590, "text": "Python | Get unique values from a list" } ]
Check whether a binary tree is a complete tree or not | Set 2 (Recursive Solution)
24 Jun, 2022 A complete binary tree is a binary tree whose all levels except the last level are completely filled and all the leaves in the last level are all to the left side. More information about complete binary trees can be found here. Example:Below tree is a Complete Binary Tree (All nodes till the second last nodes are filled and all leaves are to the left side) An iterative solution for this problem is discussed in below post. Check whether a given Binary Tree is Complete or not | Set 1 (Using Level Order Traversal)In this post a recursive solution is discussed. In the array representation of a binary tree, if the parent node is assigned an index of ‘i’ and left child gets assigned an index of ‘2*i + 1’ while the right child is assigned an index of ‘2*i + 2’. If we represent the above binary tree as an array with the respective indices assigned to the different nodes of the tree above from top to down and left to right. Hence we proceed in the following manner in order to check if the binary tree is complete binary tree. Calculate the number of nodes (count) in the binary tree.Start recursion of the binary tree from the root node of the binary tree with index (i) being set as 0 and the number of nodes in the binary (count).If the current node under examination is NULL, then the tree is a complete binary tree. Return true.If index (i) of the current node is greater than or equal to the number of nodes in the binary tree (count) i.e. (i>= count), then the tree is not a complete binary. Return false.Recursively check the left and right sub-trees of the binary tree for same condition. For the left sub-tree use the index as (2*i + 1) while for the right sub-tree use the index as (2*i + 2). Calculate the number of nodes (count) in the binary tree. Start recursion of the binary tree from the root node of the binary tree with index (i) being set as 0 and the number of nodes in the binary (count). If the current node under examination is NULL, then the tree is a complete binary tree. Return true. If index (i) of the current node is greater than or equal to the number of nodes in the binary tree (count) i.e. (i>= count), then the tree is not a complete binary. Return false. Recursively check the left and right sub-trees of the binary tree for same condition. For the left sub-tree use the index as (2*i + 1) while for the right sub-tree use the index as (2*i + 2). The time complexity of the above algorithm is O(n). Following is the code for checking if a binary tree is a complete binary tree. Implementation: C++ C Java Python3 C# Javascript /* C++ program to checks if a binary tree complete ot not */#include<bits/stdc++.h>#include<stdbool.h>using namespace std; /* Tree node structure */class Node{ public: int key; Node *left, *right; Node *newNode(char k) { Node *node = ( Node*)malloc(sizeof( Node)); node->key = k; node->right = node->left = NULL; return node; } }; /* Helper function that allocates a new node with thegiven key and NULL left and right pointer. */ /* This function counts the number of nodesin a binary tree */unsigned int countNodes(Node* root){ if (root == NULL) return (0); return (1 + countNodes(root->left) + countNodes(root->right));} /* This function checks if the binary treeis complete or not */bool isComplete ( Node* root, unsigned int index, unsigned int number_nodes){ // An empty tree is complete if (root == NULL) return (true); // If index assigned to current node is more than // number of nodes in tree, then tree is not complete if (index >= number_nodes) return (false); // Recur for left and right subtrees return (isComplete(root->left, 2*index + 1, number_nodes) && isComplete(root->right, 2*index + 2, number_nodes));} // Driver codeint main(){ Node n1; // Let us create tree in the last diagram above Node* root = NULL; root = n1.newNode(1); root->left = n1.newNode(2); root->right = n1.newNode(3); root->left->left = n1.newNode(4); root->left->right = n1.newNode(5); root->right->right = n1.newNode(6); unsigned int node_count = countNodes(root); unsigned int index = 0; if (isComplete(root, index, node_count)) cout << "The Binary Tree is complete\n"; else cout << "The Binary Tree is not complete\n"; return (0);} // This code is contributed by SoumikMondal /* C program to checks if a binary tree complete ot not */#include<stdio.h>#include<stdlib.h>#include<stdbool.h> /* Tree node structure */struct Node{ int key; struct Node *left, *right;}; /* Helper function that allocates a new node with the given key and NULL left and right pointer. */struct Node *newNode(char k){ struct Node *node = (struct Node*)malloc(sizeof(struct Node)); node->key = k; node->right = node->left = NULL; return node;} /* This function counts the number of nodes in a binary tree */unsigned int countNodes(struct Node* root){ if (root == NULL) return (0); return (1 + countNodes(root->left) + countNodes(root->right));} /* This function checks if the binary tree is complete or not */bool isComplete (struct Node* root, unsigned int index, unsigned int number_nodes){ // An empty tree is complete if (root == NULL) return (true); // If index assigned to current node is more than // number of nodes in tree, then tree is not complete if (index >= number_nodes) return (false); // Recur for left and right subtrees return (isComplete(root->left, 2*index + 1, number_nodes) && isComplete(root->right, 2*index + 2, number_nodes));} // Driver programint main(){ // Le us create tree in the last diagram above struct Node* root = NULL; root = newNode(1); root->left = newNode(2); root->right = newNode(3); root->left->left = newNode(4); root->left->right = newNode(5); root->right->right = newNode(6); unsigned int node_count = countNodes(root); unsigned int index = 0; if (isComplete(root, index, node_count)) printf("The Binary Tree is complete\n"); else printf("The Binary Tree is not complete\n"); return (0);} // Java program to check if binary tree is complete or not /* Tree node structure */class Node{ int data; Node left, right; Node(int item) { data = item; left = right = null; }} class BinaryTree{ Node root; /* This function counts the number of nodes in a binary tree */ int countNodes(Node root) { if (root == null) return (0); return (1 + countNodes(root.left) + countNodes(root.right)); } /* This function checks if the binary tree is complete or not */ boolean isComplete(Node root, int index, int number_nodes) { // An empty tree is complete if (root == null) return true; // If index assigned to current node is more than // number of nodes in tree, then tree is not complete if (index >= number_nodes) return false; // Recur for left and right subtrees return (isComplete(root.left, 2 * index + 1, number_nodes) && isComplete(root.right, 2 * index + 2, number_nodes)); } // Driver program public static void main(String args[]) { BinaryTree tree = new BinaryTree(); // Le us create tree in the last diagram above Node NewRoot = null; tree.root = new Node(1); tree.root.left = new Node(2); tree.root.right = new Node(3); tree.root.left.right = new Node(5); tree.root.left.left = new Node(4); tree.root.right.right = new Node(6); int node_count = tree.countNodes(tree.root); int index = 0; if (tree.isComplete(tree.root, index, node_count)) System.out.print("The binary tree is complete"); else System.out.print("The binary tree is not complete"); }} // This code is contributed by Mayank Jaiswal # Python program to check if a binary tree complete or not # Tree node structureclass Node: # Constructor to create a new node def __init__(self, key): self.key = key self.left = None self.right = None # This function counts the number of nodes in a binary treedef countNodes(root): if root is None: return 0 return (1+ countNodes(root.left) + countNodes(root.right)) # This function checks if binary tree is complete or notdef isComplete(root, index, number_nodes): # An empty is complete if root is None: return True # If index assigned to current nodes is more than # number of nodes in tree, then tree is not complete if index >= number_nodes : return False # Recur for left and right subtrees return (isComplete(root.left , 2*index+1 , number_nodes) and isComplete(root.right, 2*index+2, number_nodes) ) # Driver Program root = Node(1)root.left = Node(2)root.right = Node(3)root.left.left = Node(4)root.left.right = Node(5)root.right.right = Node(6) node_count = countNodes(root)index = 0 if isComplete(root, index, node_count): print ("The Binary Tree is complete")else: print ("The Binary Tree is not complete") # This code is contributed by Nikhil Kumar Singh(nickzuck_007) // C# program to check if binary// tree is complete or notusing System; /* Tree node structure */class Node{ public int data; public Node left, right; public Node(int item) { data = item; left = right = null; }} public class BinaryTree{ Node root; /* This function counts the number of nodes in a binary tree */ int countNodes(Node root) { if (root == null) return (0); return (1 + countNodes(root.left) + countNodes(root.right)); } /* This function checks if the binary tree is complete or not */ bool isComplete(Node root, int index, int number_nodes) { // An empty tree is complete if (root == null) return true; // If index assigned to current node is more than // number of nodes in tree, then tree is not complete if (index >= number_nodes) return false; // Recur for left and right subtrees return (isComplete(root.left, 2 * index + 1, number_nodes) && isComplete(root.right, 2 * index + 2, number_nodes)); } // Driver code public static void Main() { BinaryTree tree = new BinaryTree(); // Let us create tree in the last diagram above tree.root = new Node(1); tree.root.left = new Node(2); tree.root.right = new Node(3); tree.root.left.right = new Node(5); tree.root.left.left = new Node(4); tree.root.right.right = new Node(6); int node_count = tree.countNodes(tree.root); int index = 0; if (tree.isComplete(tree.root, index, node_count)) Console.WriteLine("The binary tree is complete"); else Console.WriteLine("The binary tree is not complete"); }} /* This code is contributed by Rajput-Ji*/ <script> // JavaScript program to check if// binary tree is complete or not /* Tree node structure */class Node { constructor(val) { this.data = val; this.left = null; this.right = null; } } var root; /* This function counts the number of nodes in a binary tree */ function countNodes(root) { if (root == null) return (0); return (1 + countNodes(root.left) + countNodes(root.right)); } /* This function checks if the binary tree is complete or not */ function isComplete(root , index , number_nodes) { // An empty tree is complete if (root == null) return true; // If index assigned to current node is more than // number of nodes in tree, then tree is not complete if (index >= number_nodes) return false; // Recur for left and right subtrees return (isComplete(root.left, 2 * index + 1, number_nodes) && isComplete(root.right, 2 * index + 2, number_nodes)); } // Driver program // Le us create tree in the last diagram above var NewRoot = null; root = new Node(1); root.left = new Node(2); root.right = new Node(3); root.left.right = new Node(5); root.left.left = new Node(4); root.right.right = new Node(6); var node_count = countNodes(root); var index = 0; if (isComplete(root, index, node_count)) document.write("The binary tree is complete"); else document.write("The binary tree is not complete"); // This code contributed by umadevi9616 </script> The Binary Tree is not complete Rajput-Ji SoumikMondal simmytarika5 umadevi9616 surindertarika1234 amartyaghoshgfg surinderdawra388 hardikkoriintern Tree Tree Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n24 Jun, 2022" }, { "code": null, "e": 282, "s": 54, "text": "A complete binary tree is a binary tree whose all levels except the last level are completely filled and all the leaves in the last level are all to the left side. More information about complete binary trees can be found here." }, { "code": null, "e": 414, "s": 282, "text": "Example:Below tree is a Complete Binary Tree (All nodes till the second last nodes are filled and all leaves are to the left side) " }, { "code": null, "e": 619, "s": 414, "text": "An iterative solution for this problem is discussed in below post. Check whether a given Binary Tree is Complete or not | Set 1 (Using Level Order Traversal)In this post a recursive solution is discussed." }, { "code": null, "e": 984, "s": 619, "text": "In the array representation of a binary tree, if the parent node is assigned an index of ‘i’ and left child gets assigned an index of ‘2*i + 1’ while the right child is assigned an index of ‘2*i + 2’. If we represent the above binary tree as an array with the respective indices assigned to the different nodes of the tree above from top to down and left to right." }, { "code": null, "e": 1088, "s": 984, "text": "Hence we proceed in the following manner in order to check if the binary tree is complete binary tree. " }, { "code": null, "e": 1765, "s": 1088, "text": "Calculate the number of nodes (count) in the binary tree.Start recursion of the binary tree from the root node of the binary tree with index (i) being set as 0 and the number of nodes in the binary (count).If the current node under examination is NULL, then the tree is a complete binary tree. Return true.If index (i) of the current node is greater than or equal to the number of nodes in the binary tree (count) i.e. (i>= count), then the tree is not a complete binary. Return false.Recursively check the left and right sub-trees of the binary tree for same condition. For the left sub-tree use the index as (2*i + 1) while for the right sub-tree use the index as (2*i + 2)." }, { "code": null, "e": 1823, "s": 1765, "text": "Calculate the number of nodes (count) in the binary tree." }, { "code": null, "e": 1973, "s": 1823, "text": "Start recursion of the binary tree from the root node of the binary tree with index (i) being set as 0 and the number of nodes in the binary (count)." }, { "code": null, "e": 2074, "s": 1973, "text": "If the current node under examination is NULL, then the tree is a complete binary tree. Return true." }, { "code": null, "e": 2254, "s": 2074, "text": "If index (i) of the current node is greater than or equal to the number of nodes in the binary tree (count) i.e. (i>= count), then the tree is not a complete binary. Return false." }, { "code": null, "e": 2446, "s": 2254, "text": "Recursively check the left and right sub-trees of the binary tree for same condition. For the left sub-tree use the index as (2*i + 1) while for the right sub-tree use the index as (2*i + 2)." }, { "code": null, "e": 2578, "s": 2446, "text": "The time complexity of the above algorithm is O(n). Following is the code for checking if a binary tree is a complete binary tree. " }, { "code": null, "e": 2594, "s": 2578, "text": "Implementation:" }, { "code": null, "e": 2598, "s": 2594, "text": "C++" }, { "code": null, "e": 2600, "s": 2598, "text": "C" }, { "code": null, "e": 2605, "s": 2600, "text": "Java" }, { "code": null, "e": 2613, "s": 2605, "text": "Python3" }, { "code": null, "e": 2616, "s": 2613, "text": "C#" }, { "code": null, "e": 2627, "s": 2616, "text": "Javascript" }, { "code": "/* C++ program to checks if a binary tree complete ot not */#include<bits/stdc++.h>#include<stdbool.h>using namespace std; /* Tree node structure */class Node{ public: int key; Node *left, *right; Node *newNode(char k) { Node *node = ( Node*)malloc(sizeof( Node)); node->key = k; node->right = node->left = NULL; return node; } }; /* Helper function that allocates a new node with thegiven key and NULL left and right pointer. */ /* This function counts the number of nodesin a binary tree */unsigned int countNodes(Node* root){ if (root == NULL) return (0); return (1 + countNodes(root->left) + countNodes(root->right));} /* This function checks if the binary treeis complete or not */bool isComplete ( Node* root, unsigned int index, unsigned int number_nodes){ // An empty tree is complete if (root == NULL) return (true); // If index assigned to current node is more than // number of nodes in tree, then tree is not complete if (index >= number_nodes) return (false); // Recur for left and right subtrees return (isComplete(root->left, 2*index + 1, number_nodes) && isComplete(root->right, 2*index + 2, number_nodes));} // Driver codeint main(){ Node n1; // Let us create tree in the last diagram above Node* root = NULL; root = n1.newNode(1); root->left = n1.newNode(2); root->right = n1.newNode(3); root->left->left = n1.newNode(4); root->left->right = n1.newNode(5); root->right->right = n1.newNode(6); unsigned int node_count = countNodes(root); unsigned int index = 0; if (isComplete(root, index, node_count)) cout << \"The Binary Tree is complete\\n\"; else cout << \"The Binary Tree is not complete\\n\"; return (0);} // This code is contributed by SoumikMondal", "e": 4505, "s": 2627, "text": null }, { "code": "/* C program to checks if a binary tree complete ot not */#include<stdio.h>#include<stdlib.h>#include<stdbool.h> /* Tree node structure */struct Node{ int key; struct Node *left, *right;}; /* Helper function that allocates a new node with the given key and NULL left and right pointer. */struct Node *newNode(char k){ struct Node *node = (struct Node*)malloc(sizeof(struct Node)); node->key = k; node->right = node->left = NULL; return node;} /* This function counts the number of nodes in a binary tree */unsigned int countNodes(struct Node* root){ if (root == NULL) return (0); return (1 + countNodes(root->left) + countNodes(root->right));} /* This function checks if the binary tree is complete or not */bool isComplete (struct Node* root, unsigned int index, unsigned int number_nodes){ // An empty tree is complete if (root == NULL) return (true); // If index assigned to current node is more than // number of nodes in tree, then tree is not complete if (index >= number_nodes) return (false); // Recur for left and right subtrees return (isComplete(root->left, 2*index + 1, number_nodes) && isComplete(root->right, 2*index + 2, number_nodes));} // Driver programint main(){ // Le us create tree in the last diagram above struct Node* root = NULL; root = newNode(1); root->left = newNode(2); root->right = newNode(3); root->left->left = newNode(4); root->left->right = newNode(5); root->right->right = newNode(6); unsigned int node_count = countNodes(root); unsigned int index = 0; if (isComplete(root, index, node_count)) printf(\"The Binary Tree is complete\\n\"); else printf(\"The Binary Tree is not complete\\n\"); return (0);}", "e": 6292, "s": 4505, "text": null }, { "code": "// Java program to check if binary tree is complete or not /* Tree node structure */class Node{ int data; Node left, right; Node(int item) { data = item; left = right = null; }} class BinaryTree{ Node root; /* This function counts the number of nodes in a binary tree */ int countNodes(Node root) { if (root == null) return (0); return (1 + countNodes(root.left) + countNodes(root.right)); } /* This function checks if the binary tree is complete or not */ boolean isComplete(Node root, int index, int number_nodes) { // An empty tree is complete if (root == null) return true; // If index assigned to current node is more than // number of nodes in tree, then tree is not complete if (index >= number_nodes) return false; // Recur for left and right subtrees return (isComplete(root.left, 2 * index + 1, number_nodes) && isComplete(root.right, 2 * index + 2, number_nodes)); } // Driver program public static void main(String args[]) { BinaryTree tree = new BinaryTree(); // Le us create tree in the last diagram above Node NewRoot = null; tree.root = new Node(1); tree.root.left = new Node(2); tree.root.right = new Node(3); tree.root.left.right = new Node(5); tree.root.left.left = new Node(4); tree.root.right.right = new Node(6); int node_count = tree.countNodes(tree.root); int index = 0; if (tree.isComplete(tree.root, index, node_count)) System.out.print(\"The binary tree is complete\"); else System.out.print(\"The binary tree is not complete\"); }} // This code is contributed by Mayank Jaiswal", "e": 8130, "s": 6292, "text": null }, { "code": "# Python program to check if a binary tree complete or not # Tree node structureclass Node: # Constructor to create a new node def __init__(self, key): self.key = key self.left = None self.right = None # This function counts the number of nodes in a binary treedef countNodes(root): if root is None: return 0 return (1+ countNodes(root.left) + countNodes(root.right)) # This function checks if binary tree is complete or notdef isComplete(root, index, number_nodes): # An empty is complete if root is None: return True # If index assigned to current nodes is more than # number of nodes in tree, then tree is not complete if index >= number_nodes : return False # Recur for left and right subtrees return (isComplete(root.left , 2*index+1 , number_nodes) and isComplete(root.right, 2*index+2, number_nodes) ) # Driver Program root = Node(1)root.left = Node(2)root.right = Node(3)root.left.left = Node(4)root.left.right = Node(5)root.right.right = Node(6) node_count = countNodes(root)index = 0 if isComplete(root, index, node_count): print (\"The Binary Tree is complete\")else: print (\"The Binary Tree is not complete\") # This code is contributed by Nikhil Kumar Singh(nickzuck_007)", "e": 9426, "s": 8130, "text": null }, { "code": "// C# program to check if binary// tree is complete or notusing System; /* Tree node structure */class Node{ public int data; public Node left, right; public Node(int item) { data = item; left = right = null; }} public class BinaryTree{ Node root; /* This function counts the number of nodes in a binary tree */ int countNodes(Node root) { if (root == null) return (0); return (1 + countNodes(root.left) + countNodes(root.right)); } /* This function checks if the binary tree is complete or not */ bool isComplete(Node root, int index, int number_nodes) { // An empty tree is complete if (root == null) return true; // If index assigned to current node is more than // number of nodes in tree, then tree is not complete if (index >= number_nodes) return false; // Recur for left and right subtrees return (isComplete(root.left, 2 * index + 1, number_nodes) && isComplete(root.right, 2 * index + 2, number_nodes)); } // Driver code public static void Main() { BinaryTree tree = new BinaryTree(); // Let us create tree in the last diagram above tree.root = new Node(1); tree.root.left = new Node(2); tree.root.right = new Node(3); tree.root.left.right = new Node(5); tree.root.left.left = new Node(4); tree.root.right.right = new Node(6); int node_count = tree.countNodes(tree.root); int index = 0; if (tree.isComplete(tree.root, index, node_count)) Console.WriteLine(\"The binary tree is complete\"); else Console.WriteLine(\"The binary tree is not complete\"); }} /* This code is contributed by Rajput-Ji*/", "e": 11284, "s": 9426, "text": null }, { "code": "<script> // JavaScript program to check if// binary tree is complete or not /* Tree node structure */class Node { constructor(val) { this.data = val; this.left = null; this.right = null; } } var root; /* This function counts the number of nodes in a binary tree */ function countNodes(root) { if (root == null) return (0); return (1 + countNodes(root.left) + countNodes(root.right)); } /* This function checks if the binary tree is complete or not */ function isComplete(root , index , number_nodes) { // An empty tree is complete if (root == null) return true; // If index assigned to current node is more than // number of nodes in tree, then tree is not complete if (index >= number_nodes) return false; // Recur for left and right subtrees return (isComplete(root.left, 2 * index + 1, number_nodes) && isComplete(root.right, 2 * index + 2, number_nodes)); } // Driver program // Le us create tree in the last diagram above var NewRoot = null; root = new Node(1); root.left = new Node(2); root.right = new Node(3); root.left.right = new Node(5); root.left.left = new Node(4); root.right.right = new Node(6); var node_count = countNodes(root); var index = 0; if (isComplete(root, index, node_count)) document.write(\"The binary tree is complete\"); else document.write(\"The binary tree is not complete\"); // This code contributed by umadevi9616 </script>", "e": 12940, "s": 11284, "text": null }, { "code": null, "e": 12972, "s": 12940, "text": "The Binary Tree is not complete" }, { "code": null, "e": 12982, "s": 12972, "text": "Rajput-Ji" }, { "code": null, "e": 12995, "s": 12982, "text": "SoumikMondal" }, { "code": null, "e": 13008, "s": 12995, "text": "simmytarika5" }, { "code": null, "e": 13020, "s": 13008, "text": "umadevi9616" }, { "code": null, "e": 13039, "s": 13020, "text": "surindertarika1234" }, { "code": null, "e": 13055, "s": 13039, "text": "amartyaghoshgfg" }, { "code": null, "e": 13072, "s": 13055, "text": "surinderdawra388" }, { "code": null, "e": 13089, "s": 13072, "text": "hardikkoriintern" }, { "code": null, "e": 13094, "s": 13089, "text": "Tree" }, { "code": null, "e": 13099, "s": 13094, "text": "Tree" } ]
Overview of Advanced Convolution layers | by Jehill Parikh | Towards Data Science
Convolution layers are fundamental building blocks of computer vision architectures. Neural networks employing convolutions layers are employed in wide-ranging applications in Segmentation, Reconstruction, Scene Understanding, Synthesis, Object detection and more The goal of this post is to provide a summary and overview of advanced convolution layers and techniques which have emerged in the recent literature. We start with basics of convolution, for completeness, however, more rigorous explanations can be obtained from references within. Convolution: Mathematically speak convolution is an “operation” performed to combine two signals into one, below is an illustration from wikipedia which highlights convolution between two functions/signals f(t) and f(t-z). Convolution to obtain the (f*g)(t) The main convolution operations in deep learning are “2D” Convolution: “2D” Convolution: Pictorially we convolve “slide” a kernel (green size) over an image (blue) and learn weights for these kernels. This kernel’s spatial extent (F) is 3 and filters i.e. depth of the kernel is 1, therefore number of weights are 3*3*1=9. We can skip pixels by “stride” and pad regions our original image, here the stride is 0 Convolution block of accepts a image or feature map of size W1×H1×D1 and kernel of size (F*F*K) and typical requires four hyper-parameters: Number of filters K: K Their spatial extent F: F The stride S The amount of zero padding: P : if we zero pad any image Number of parameter are (channels*F*F)*K Typically shape of the weight matrix is (F, F, Channels, K) These there operations combined provide a final output feature map of W2*H2*D2 for details of working see post W2 =(W1−F+2P)/S+1W2=(W1−F+2P)/S+1 H2 = (H1−F+2P)/S+1H2=(H1−F+2P)/S+1 With convolution, two additional operations are employed Max-pool: this operation reduces the number dimension of the images: generally a 2*2 filter in “max” pool operation is employed. The filter replaces each 2*2 block in the image/feature map with the max of that block, this is reduced the size of the feature maps for the following layer. Non-linearity (relu, tanh etc) are employed prior to max-pool operation to add non linearity to the operation [TODO: future work: add notes on performance of the various non-linearity] Spatial extent of filter (F) is the main contributor of the number of weights for each kernel. As explained in CS231n lecture notes with F=3 and F=7 there is a three fold increase in number of weights. Typically, a full deep-net consists of multiples layers of CONV + RELU + POOL operations to extract features. Thus generally F=3 is employed as a trade off to learn features vectors at each layer without increasing cost of computational cost. Please see the computation considerations section on C231n lecture notes as additional reference Key architectures for object classification tasks which use these three layers are well summarised in the CS231n notes, they are LeNet, AlexNet, ZFNet, GoogLeNet, VGGnet, Resnet. These were developed towards winning the Imagenet challenge. Over the years, there was a trend for larger/deeper the network deeper to improve performance. Residual/skipped connection These were introduced in 2015 by a Microsoft team to maintain accuracy in deeper networks as part of the ImageNet challenge. A single network skipped connection is shown below, it aims to learn Residual R(x). In deeper networks this allows to learning “residual information” at each layer. Hence the name residual connection. This technique has experimentally has proven to increase accuracy in deeper networks. Implementing a residual/skipped connection is very straight forward, as shown below. Skipping the connection also allows us to over come to issue of vanishing gradients, in deep layers, and speeds up training. This experimental results has been widely adopted across a range of computer vision algorithms since original introduction. Variants of the resnets are highlighted in this post, and additional detail and illustrations please see the blog. R(x) = Output — Input = H(x) — xdef res_net_block(input_data, filters, conv_size): x = layers.Conv2D(filters, conv_size, activation='relu', padding='same')(input_data) x = layers.BatchNormalization()(x) x = layers.Conv2D(filters, conv_size, activation=None, padding='same')(x) x = layers.BatchNormalization()(x) x = layers.Add()([x, input_data]) x = layers.Activation('relu')(x) return x Above layers are critical components of neural networks employed for computer vision task, and find application in wide range of domains and different architecture. Now we turn to more specialised layers. Convolution transpose/strided convolutions Convolution operation with stride (≥2) and/or padding reduces the dimension of the resultant feature map. Convolution transpose is the reverse process employed to learn kernels to, up-sample features maps to larger dimensions. With stride >1 being typically employed to upsample the image, this process is well illustrated in a post by Thom Lane and below, where are 2*2 input with padding and strided convolution with a 3*3 kernel leads to a 5*5 feature map Strided convolutions find wide ranging application in different areas U-nets (medical image segmentation)Generative models: GAN: Generators VAE: Decoder, up-sampling layers U-nets (medical image segmentation) Generative models: GAN: Generators VAE: Decoder, up-sampling layers Implementation: All major DL frameworks have strided convolution, then need to employed with proper initialisation i.e. random or Xavier initialisation. Masked and gated convolution Masked and Gated convolution started gaining popularity around 2016, in there seminal work Aaron van den Oord, et al introduced Pixel RNN and Pixel-CNN. These are autoregressive approaches to sample pixel from a probability distribution conditional on the previous pixels. Since each pixel is generated via conditioning on previous pixels, to ensure conditioning on pixel from the left and top rows mask are employed while applying convolution operations. Two types of masks are Mask: A, used in first channel and prior pixels. Mask: B, mask B all channels and prior pixels, following layers, both available here Notes: Inputs must be binarized: 28 e.g. 256 bits of colour, or each sample is between 0–256 in a RGB image Masked gated convolutions were introduced to avoid blind-spots in masked convolutions. Ord et al, 2016 proposed to isolate horizontal and vertical stacks i.e gates with 1*1 convolution, with residual connections in the horizontal stacks, as shown below. Residual connections in vertical stacks didn’t offer additional performance improvement, therefore were not implemented. Implementation of masked gate convolutions is available here. Applications: Mainly employed in decoders for e.g. in VAE frameworks for prior sampling to avoid issues with training GAN’s such as mode collapse and generate high resolution images. Pixel CNN decoder: Pixel conditioned on previous values, leading better performance. Longer inference/sampling as needs to be done on pixel by pixel basis. These were optimised in PixelCNN++ and implementation available on available on Tensorflow Probability.Pixel-VAE: combines, each dimension is diagonal element of the covariance matrix and this Gaussian assumption leads to poor sample images, so combines a traditional decoder with PixelCNN to help “small scale/similar” aspects of the distribution and this puts less demands on latent to learn more global information, demonstrated via improvements to KL term, leading to improved performance. Implementation see hereVQ-VAE and VQ-VAE2: uses Pixel-CNN in latent code map of VAE to avoid Gaussian assumption of the latent variables all together, leading to diverse images in higher dimensions. VQ-VAE implementation were open sourced by the authors, and other implementation are also widely available Pixel CNN decoder: Pixel conditioned on previous values, leading better performance. Longer inference/sampling as needs to be done on pixel by pixel basis. These were optimised in PixelCNN++ and implementation available on available on Tensorflow Probability. Pixel-VAE: combines, each dimension is diagonal element of the covariance matrix and this Gaussian assumption leads to poor sample images, so combines a traditional decoder with PixelCNN to help “small scale/similar” aspects of the distribution and this puts less demands on latent to learn more global information, demonstrated via improvements to KL term, leading to improved performance. Implementation see here VQ-VAE and VQ-VAE2: uses Pixel-CNN in latent code map of VAE to avoid Gaussian assumption of the latent variables all together, leading to diverse images in higher dimensions. VQ-VAE implementation were open sourced by the authors, and other implementation are also widely available Invertible convolutions Invertible convolutions, are based on normalising flows, are currently applied in generative models to learn underlying probability distribution p(x) of image in computer vision. The maintain motivation is to provide a better loss function i.e. negative log likelihood. The two most common generative frameworks modelling suffer from approximation inference time issues, i.e. loss function function for VAE (evidence based lower bound i.e. ELBO) is an approximation is lower bound on log-likelihood, therefore inference/reconstruction is approximation. Adversarial loss employed in GAN’s is a “search” based approach and suffer issues with sampling diversity and are hard to train i.e. mode collapse. Mathematical preliminaries of Normalising flows are best outlined in the Stanford class notes here, we use there summary. In normalising flow, the mapping between random variable Z and X, given by, function f, paramaterized θ, which is deterministic and invertible such that Then probability distributions of X and Z can then be obtained using the change of variable formulation, in this case the two probability distributions are related via determinant term. Loosely speaking the determinant is the “scaling” or normalising constant. Here, “Normalising” means that the change of variables gives a normalised density after applying an invertible transformation“Flow” means that the invertible transformations can be composed with each other to create more complex invertible transformations. “Normalising” means that the change of variables gives a normalised density after applying an invertible transformation “Flow” means that the invertible transformations can be composed with each other to create more complex invertible transformations. Note: function can be a single function, or a series of sequential function, transforming generally, transforming from simple e.g. latent vectors (Z) to complex distributions e.g. (X) images. This formulation allows to us “exactly” between transform between two distribution, and thus can derive the negative log likehood loss function, see the lecture for derivation. Normalising flow and neural networks: Works of Dinh et al, 2014 (NICE) and Dinh et al, 2017 (Real-NVP), started providing neural network architecture, to employ normalising flow for the density estimation. Glow from Kingma et al, is the current (2018) state of art, which builds on these works, In which which introduced 1*1 invertible convolution, to synthesis high resolution images. The key novelty was to reduce the computation cost of the determinant term for the weight matrix, for 1*1 learning invertible convolutions. This was achieved with LU decomposition with permutation, i.e. PLU decomposition, for the weight matrix. Random permutations were employed to maintain “flow” at each iteration. The mathematical details are covered in section 3.2, of the paper they also provide an implementation using numpy and tensorflow, for easier interrogation. These were further generalised to N*N convolutions by Hoogeboom, et al, please see the blog post for additional details and implementations (with optimisation). Our aim was just to highlight these models, for more comprehensive details we refer the reader to, CS236 lectures 7 and 8 and Glow paper and blog post by Lilian Weng. Application area: Image synthesis and generative modelling
[ { "code": null, "e": 435, "s": 171, "text": "Convolution layers are fundamental building blocks of computer vision architectures. Neural networks employing convolutions layers are employed in wide-ranging applications in Segmentation, Reconstruction, Scene Understanding, Synthesis, Object detection and more" }, { "code": null, "e": 716, "s": 435, "text": "The goal of this post is to provide a summary and overview of advanced convolution layers and techniques which have emerged in the recent literature. We start with basics of convolution, for completeness, however, more rigorous explanations can be obtained from references within." }, { "code": null, "e": 974, "s": 716, "text": "Convolution: Mathematically speak convolution is an “operation” performed to combine two signals into one, below is an illustration from wikipedia which highlights convolution between two functions/signals f(t) and f(t-z). Convolution to obtain the (f*g)(t)" }, { "code": null, "e": 1027, "s": 974, "text": "The main convolution operations in deep learning are" }, { "code": null, "e": 1045, "s": 1027, "text": "“2D” Convolution:" }, { "code": null, "e": 1063, "s": 1045, "text": "“2D” Convolution:" }, { "code": null, "e": 1385, "s": 1063, "text": "Pictorially we convolve “slide” a kernel (green size) over an image (blue) and learn weights for these kernels. This kernel’s spatial extent (F) is 3 and filters i.e. depth of the kernel is 1, therefore number of weights are 3*3*1=9. We can skip pixels by “stride” and pad regions our original image, here the stride is 0" }, { "code": null, "e": 1525, "s": 1385, "text": "Convolution block of accepts a image or feature map of size W1×H1×D1 and kernel of size (F*F*K) and typical requires four hyper-parameters:" }, { "code": null, "e": 1548, "s": 1525, "text": "Number of filters K: K" }, { "code": null, "e": 1574, "s": 1548, "text": "Their spatial extent F: F" }, { "code": null, "e": 1587, "s": 1574, "text": "The stride S" }, { "code": null, "e": 1644, "s": 1587, "text": "The amount of zero padding: P : if we zero pad any image" }, { "code": null, "e": 1685, "s": 1644, "text": "Number of parameter are (channels*F*F)*K" }, { "code": null, "e": 1745, "s": 1685, "text": "Typically shape of the weight matrix is (F, F, Channels, K)" }, { "code": null, "e": 1856, "s": 1745, "text": "These there operations combined provide a final output feature map of W2*H2*D2 for details of working see post" }, { "code": null, "e": 1890, "s": 1856, "text": "W2 =(W1−F+2P)/S+1W2=(W1−F+2P)/S+1" }, { "code": null, "e": 1925, "s": 1890, "text": "H2 = (H1−F+2P)/S+1H2=(H1−F+2P)/S+1" }, { "code": null, "e": 1982, "s": 1925, "text": "With convolution, two additional operations are employed" }, { "code": null, "e": 2269, "s": 1982, "text": "Max-pool: this operation reduces the number dimension of the images: generally a 2*2 filter in “max” pool operation is employed. The filter replaces each 2*2 block in the image/feature map with the max of that block, this is reduced the size of the feature maps for the following layer." }, { "code": null, "e": 2454, "s": 2269, "text": "Non-linearity (relu, tanh etc) are employed prior to max-pool operation to add non linearity to the operation [TODO: future work: add notes on performance of the various non-linearity]" }, { "code": null, "e": 2899, "s": 2454, "text": "Spatial extent of filter (F) is the main contributor of the number of weights for each kernel. As explained in CS231n lecture notes with F=3 and F=7 there is a three fold increase in number of weights. Typically, a full deep-net consists of multiples layers of CONV + RELU + POOL operations to extract features. Thus generally F=3 is employed as a trade off to learn features vectors at each layer without increasing cost of computational cost." }, { "code": null, "e": 2996, "s": 2899, "text": "Please see the computation considerations section on C231n lecture notes as additional reference" }, { "code": null, "e": 3331, "s": 2996, "text": "Key architectures for object classification tasks which use these three layers are well summarised in the CS231n notes, they are LeNet, AlexNet, ZFNet, GoogLeNet, VGGnet, Resnet. These were developed towards winning the Imagenet challenge. Over the years, there was a trend for larger/deeper the network deeper to improve performance." }, { "code": null, "e": 3359, "s": 3331, "text": "Residual/skipped connection" }, { "code": null, "e": 4220, "s": 3359, "text": "These were introduced in 2015 by a Microsoft team to maintain accuracy in deeper networks as part of the ImageNet challenge. A single network skipped connection is shown below, it aims to learn Residual R(x). In deeper networks this allows to learning “residual information” at each layer. Hence the name residual connection. This technique has experimentally has proven to increase accuracy in deeper networks. Implementing a residual/skipped connection is very straight forward, as shown below. Skipping the connection also allows us to over come to issue of vanishing gradients, in deep layers, and speeds up training. This experimental results has been widely adopted across a range of computer vision algorithms since original introduction. Variants of the resnets are highlighted in this post, and additional detail and illustrations please see the blog." }, { "code": null, "e": 4628, "s": 4220, "text": "R(x) = Output — Input = H(x) — xdef res_net_block(input_data, filters, conv_size): x = layers.Conv2D(filters, conv_size, activation='relu', padding='same')(input_data) x = layers.BatchNormalization()(x) x = layers.Conv2D(filters, conv_size, activation=None, padding='same')(x) x = layers.BatchNormalization()(x) x = layers.Add()([x, input_data]) x = layers.Activation('relu')(x) return x" }, { "code": null, "e": 4833, "s": 4628, "text": "Above layers are critical components of neural networks employed for computer vision task, and find application in wide range of domains and different architecture. Now we turn to more specialised layers." }, { "code": null, "e": 4876, "s": 4833, "text": "Convolution transpose/strided convolutions" }, { "code": null, "e": 5335, "s": 4876, "text": "Convolution operation with stride (≥2) and/or padding reduces the dimension of the resultant feature map. Convolution transpose is the reverse process employed to learn kernels to, up-sample features maps to larger dimensions. With stride >1 being typically employed to upsample the image, this process is well illustrated in a post by Thom Lane and below, where are 2*2 input with padding and strided convolution with a 3*3 kernel leads to a 5*5 feature map" }, { "code": null, "e": 5405, "s": 5335, "text": "Strided convolutions find wide ranging application in different areas" }, { "code": null, "e": 5508, "s": 5405, "text": "U-nets (medical image segmentation)Generative models: GAN: Generators VAE: Decoder, up-sampling layers" }, { "code": null, "e": 5544, "s": 5508, "text": "U-nets (medical image segmentation)" }, { "code": null, "e": 5612, "s": 5544, "text": "Generative models: GAN: Generators VAE: Decoder, up-sampling layers" }, { "code": null, "e": 5765, "s": 5612, "text": "Implementation: All major DL frameworks have strided convolution, then need to employed with proper initialisation i.e. random or Xavier initialisation." }, { "code": null, "e": 5794, "s": 5765, "text": "Masked and gated convolution" }, { "code": null, "e": 6067, "s": 5794, "text": "Masked and Gated convolution started gaining popularity around 2016, in there seminal work Aaron van den Oord, et al introduced Pixel RNN and Pixel-CNN. These are autoregressive approaches to sample pixel from a probability distribution conditional on the previous pixels." }, { "code": null, "e": 6407, "s": 6067, "text": "Since each pixel is generated via conditioning on previous pixels, to ensure conditioning on pixel from the left and top rows mask are employed while applying convolution operations. Two types of masks are Mask: A, used in first channel and prior pixels. Mask: B, mask B all channels and prior pixels, following layers, both available here" }, { "code": null, "e": 6515, "s": 6407, "text": "Notes: Inputs must be binarized: 28 e.g. 256 bits of colour, or each sample is between 0–256 in a RGB image" }, { "code": null, "e": 6890, "s": 6515, "text": "Masked gated convolutions were introduced to avoid blind-spots in masked convolutions. Ord et al, 2016 proposed to isolate horizontal and vertical stacks i.e gates with 1*1 convolution, with residual connections in the horizontal stacks, as shown below. Residual connections in vertical stacks didn’t offer additional performance improvement, therefore were not implemented." }, { "code": null, "e": 6952, "s": 6890, "text": "Implementation of masked gate convolutions is available here." }, { "code": null, "e": 7135, "s": 6952, "text": "Applications: Mainly employed in decoders for e.g. in VAE frameworks for prior sampling to avoid issues with training GAN’s such as mode collapse and generate high resolution images." }, { "code": null, "e": 8091, "s": 7135, "text": "Pixel CNN decoder: Pixel conditioned on previous values, leading better performance. Longer inference/sampling as needs to be done on pixel by pixel basis. These were optimised in PixelCNN++ and implementation available on available on Tensorflow Probability.Pixel-VAE: combines, each dimension is diagonal element of the covariance matrix and this Gaussian assumption leads to poor sample images, so combines a traditional decoder with PixelCNN to help “small scale/similar” aspects of the distribution and this puts less demands on latent to learn more global information, demonstrated via improvements to KL term, leading to improved performance. Implementation see hereVQ-VAE and VQ-VAE2: uses Pixel-CNN in latent code map of VAE to avoid Gaussian assumption of the latent variables all together, leading to diverse images in higher dimensions. VQ-VAE implementation were open sourced by the authors, and other implementation are also widely available" }, { "code": null, "e": 8351, "s": 8091, "text": "Pixel CNN decoder: Pixel conditioned on previous values, leading better performance. Longer inference/sampling as needs to be done on pixel by pixel basis. These were optimised in PixelCNN++ and implementation available on available on Tensorflow Probability." }, { "code": null, "e": 8766, "s": 8351, "text": "Pixel-VAE: combines, each dimension is diagonal element of the covariance matrix and this Gaussian assumption leads to poor sample images, so combines a traditional decoder with PixelCNN to help “small scale/similar” aspects of the distribution and this puts less demands on latent to learn more global information, demonstrated via improvements to KL term, leading to improved performance. Implementation see here" }, { "code": null, "e": 9049, "s": 8766, "text": "VQ-VAE and VQ-VAE2: uses Pixel-CNN in latent code map of VAE to avoid Gaussian assumption of the latent variables all together, leading to diverse images in higher dimensions. VQ-VAE implementation were open sourced by the authors, and other implementation are also widely available" }, { "code": null, "e": 9073, "s": 9049, "text": "Invertible convolutions" }, { "code": null, "e": 9343, "s": 9073, "text": "Invertible convolutions, are based on normalising flows, are currently applied in generative models to learn underlying probability distribution p(x) of image in computer vision. The maintain motivation is to provide a better loss function i.e. negative log likelihood." }, { "code": null, "e": 9774, "s": 9343, "text": "The two most common generative frameworks modelling suffer from approximation inference time issues, i.e. loss function function for VAE (evidence based lower bound i.e. ELBO) is an approximation is lower bound on log-likelihood, therefore inference/reconstruction is approximation. Adversarial loss employed in GAN’s is a “search” based approach and suffer issues with sampling diversity and are hard to train i.e. mode collapse." }, { "code": null, "e": 9896, "s": 9774, "text": "Mathematical preliminaries of Normalising flows are best outlined in the Stanford class notes here, we use there summary." }, { "code": null, "e": 10049, "s": 9896, "text": "In normalising flow, the mapping between random variable Z and X, given by, function f, paramaterized θ, which is deterministic and invertible such that" }, { "code": null, "e": 10310, "s": 10049, "text": "Then probability distributions of X and Z can then be obtained using the change of variable formulation, in this case the two probability distributions are related via determinant term. Loosely speaking the determinant is the “scaling” or normalising constant." }, { "code": null, "e": 10316, "s": 10310, "text": "Here," }, { "code": null, "e": 10567, "s": 10316, "text": "“Normalising” means that the change of variables gives a normalised density after applying an invertible transformation“Flow” means that the invertible transformations can be composed with each other to create more complex invertible transformations." }, { "code": null, "e": 10687, "s": 10567, "text": "“Normalising” means that the change of variables gives a normalised density after applying an invertible transformation" }, { "code": null, "e": 10819, "s": 10687, "text": "“Flow” means that the invertible transformations can be composed with each other to create more complex invertible transformations." }, { "code": null, "e": 11188, "s": 10819, "text": "Note: function can be a single function, or a series of sequential function, transforming generally, transforming from simple e.g. latent vectors (Z) to complex distributions e.g. (X) images. This formulation allows to us “exactly” between transform between two distribution, and thus can derive the negative log likehood loss function, see the lecture for derivation." }, { "code": null, "e": 11574, "s": 11188, "text": "Normalising flow and neural networks: Works of Dinh et al, 2014 (NICE) and Dinh et al, 2017 (Real-NVP), started providing neural network architecture, to employ normalising flow for the density estimation. Glow from Kingma et al, is the current (2018) state of art, which builds on these works, In which which introduced 1*1 invertible convolution, to synthesis high resolution images." }, { "code": null, "e": 12047, "s": 11574, "text": "The key novelty was to reduce the computation cost of the determinant term for the weight matrix, for 1*1 learning invertible convolutions. This was achieved with LU decomposition with permutation, i.e. PLU decomposition, for the weight matrix. Random permutations were employed to maintain “flow” at each iteration. The mathematical details are covered in section 3.2, of the paper they also provide an implementation using numpy and tensorflow, for easier interrogation." }, { "code": null, "e": 12375, "s": 12047, "text": "These were further generalised to N*N convolutions by Hoogeboom, et al, please see the blog post for additional details and implementations (with optimisation). Our aim was just to highlight these models, for more comprehensive details we refer the reader to, CS236 lectures 7 and 8 and Glow paper and blog post by Lilian Weng." } ]
How to search for ^ character in a MySQL table?
To search for ^ character, use the LIKE operator as in the below syntax − select table_schema,table_name,column_name from information_schema.columns where column_name like '%^%'; Let us first create a table − mysql> create table DemoTable1826 ( `^` varchar(20), Name varchar(20), `^Age` int ); Query OK, 0 rows affected (0.00 sec) Here is the query to search for ^ character in a MySQL table mysql> select table_schema,table_name,column_name from information_schema.columns where column_name like '%^%'; This will produce the following output − +--------------+---------------+-------------+ | TABLE_SCHEMA | TABLE_NAME | COLUMN_NAME | +--------------+---------------+-------------+ | web | demotable1826 | ^ | | web | demotable1826 | ^Age | +--------------+---------------+-------------+ 2 rows in set (0.00 sec)
[ { "code": null, "e": 1136, "s": 1062, "text": "To search for ^ character, use the LIKE operator as in the below syntax −" }, { "code": null, "e": 1243, "s": 1136, "text": "select table_schema,table_name,column_name\n from information_schema.columns\n where column_name like '%^%';" }, { "code": null, "e": 1273, "s": 1243, "text": "Let us first create a table −" }, { "code": null, "e": 1420, "s": 1273, "text": "mysql> create table DemoTable1826\n (\n `^` varchar(20),\n Name varchar(20),\n `^Age` int\n );\nQuery OK, 0 rows affected (0.00 sec)" }, { "code": null, "e": 1481, "s": 1420, "text": "Here is the query to search for ^ character in a MySQL table" }, { "code": null, "e": 1603, "s": 1481, "text": "mysql> select table_schema,table_name,column_name\n from information_schema.columns\n where column_name like '%^%';" }, { "code": null, "e": 1644, "s": 1603, "text": "This will produce the following output −" }, { "code": null, "e": 1951, "s": 1644, "text": "+--------------+---------------+-------------+\n| TABLE_SCHEMA | TABLE_NAME | COLUMN_NAME |\n+--------------+---------------+-------------+\n| web | demotable1826 | ^ |\n| web | demotable1826 | ^Age |\n+--------------+---------------+-------------+\n2 rows in set (0.00 sec)" } ]
DSA using C - Binary Search
Binary search is a very fast search algorithm. This search algorithm works on the principle of divide and conquer. For this algorithm to work properly the data collection should be in sorted form. Binary search search a particular item by comparing the middle most item of the collection. If match occurs then index of item is returned. If middle item is greater than item then item is searched in sub-array to the right of the middle item other wise item is search in sub-array to the left of the middle item. This process continues on sub-array as well until the size of subarray reduces to zero. Binary search halves the searchable items and thus reduces the count of comparisons to be made to very less numbers. Binary Search ( A: array of item, n: total no. of items ,x: item to be searched) Step 1: Set lowerBound = 1 Step 2: Set upperBound = n Step 3: if upperBound < lowerBound go to step 12 Step 4: set midPoint = ( lowerBound + upperBound ) / 2 Step 5: if A[midPoint] < x Step 6: set lowerBound = midPoint + 1 Step 7: if A[midPoint] > x Step 8: set upperBound = midPoint - 1 Step 9: if A[midPoint] = x go to step 11 Step 10: Go to Step 3 Step 11: Print Element x Found at index midPoint and go to step 13 Step 12: Print element not found Step 13: Exit #include <stdio.h> #define MAX 20 // array of items on which linear search will be conducted. int intArray[MAX] = {1,2,3,4,6,7,9,11,12,14,15,16,17,19,33,34,43,45,55,66}; void printline(int count){ int i; for(i=0;i <count-1;i++){ printf("="); } printf("=\n"); } int find(int data){ int lowerBound = 0; int upperBound = MAX -1; int midPoint = -1; int comparisons = 0; int index = -1; while(lowerBound <= upperBound){ printf("Comparison %d\n" , (comparisons +1) ); printf("lowerBound : %d, intArray[%d] = %d\n", lowerBound,lowerBound,intArray[lowerBound]); printf("upperBound : %d, intArray[%d] = %d\n", upperBound,upperBound,intArray[upperBound]); comparisons++; // compute the mid point midPoint = (lowerBound + upperBound) / 2; // data found if(intArray[midPoint] == data){ index = midPoint; break; } else { // if data is larger if(intArray[midPoint] < data){ // data is in upper half lowerBound = midPoint + 1; } // data is smaller else{ // data is in lower half upperBound = midPoint -1; } } } printf("Total comparisons made: %d" , comparisons); return index; } void display(){ int i; printf("["); // navigate through all items for(i=0;i<MAX;i++){ printf("%d ",intArray[i]); } printf("]\n"); } main(){ printf("Input Array: "); display(); printline(50); //find location of 1 int location = find(55); // if element was found if(location != -1) printf("\nElement found at location: %d" ,(location+1)); else printf("\nElement not found."); } If we compile and run the above program then it would produce following output − Input Array: [1 2 3 4 6 7 9 11 12 14 15 16 17 19 33 34 43 45 55 66 ] ================================================== Comparison 1 lowerBound : 0, intArray[0] = 1 upperBound : 19, intArray[19] = 66 Comparison 2 lowerBound : 10, intArray[10] = 15 upperBound : 19, intArray[19] = 66 Comparison 3 lowerBound : 15, intArray[15] = 34 upperBound : 19, intArray[19] = 66 Comparison 4 lowerBound : 18, intArray[18] = 55 upperBound : 19, intArray[19] = 66 Total comparisons made: 4 Element found at location: 19 Print Add Notes Bookmark this page
[ { "code": null, "e": 2288, "s": 2091, "text": "Binary search is a very fast search algorithm. This search algorithm works on the principle of divide and conquer. For this algorithm to work properly the data collection should be in sorted form." }, { "code": null, "e": 2690, "s": 2288, "text": "Binary search search a particular item by comparing the middle most item of the collection. If match occurs then index of item is returned. If middle item is greater than item then item is searched in sub-array to the right of the middle item other wise item is search in sub-array to the left of the middle item. This process continues on sub-array as well until the size of subarray reduces to zero." }, { "code": null, "e": 2807, "s": 2690, "text": "Binary search halves the searchable items and thus reduces the count of comparisons to be made to very less numbers." }, { "code": null, "e": 3364, "s": 2807, "text": "Binary Search ( A: array of item, n: total no. of items ,x: item to be searched)\nStep 1: Set lowerBound = 1\nStep 2: Set upperBound = n \nStep 3: if upperBound < lowerBound go to step 12\nStep 4: set midPoint = ( lowerBound + upperBound ) / 2\nStep 5: if A[midPoint] < x\nStep 6: set lowerBound = midPoint + 1\nStep 7: if A[midPoint] > x\nStep 8: set upperBound = midPoint - 1 \nStep 9: if A[midPoint] = x go to step 11\nStep 10: Go to Step 3\nStep 11: Print Element x Found at index midPoint and go to step 13\nStep 12: Print element not found\nStep 13: Exit" }, { "code": null, "e": 5147, "s": 3364, "text": "#include <stdio.h>\n#define MAX 20\n\n// array of items on which linear search will be conducted. \nint intArray[MAX] = {1,2,3,4,6,7,9,11,12,14,15,16,17,19,33,34,43,45,55,66};\n\nvoid printline(int count){\n int i;\n for(i=0;i <count-1;i++){\n printf(\"=\");\n }\n printf(\"=\\n\");\n}\nint find(int data){\n int lowerBound = 0;\n int upperBound = MAX -1;\n int midPoint = -1;\n int comparisons = 0; \n int index = -1;\n while(lowerBound <= upperBound){\n printf(\"Comparison %d\\n\" , (comparisons +1) );\n printf(\"lowerBound : %d, intArray[%d] = %d\\n\", \n lowerBound,lowerBound,intArray[lowerBound]);\n printf(\"upperBound : %d, intArray[%d] = %d\\n\",\n upperBound,upperBound,intArray[upperBound]);\n comparisons++;\n // compute the mid point \n midPoint = (lowerBound + upperBound) / 2;\n \n // data found\n if(intArray[midPoint] == data){\n index = midPoint;\n break;\n } else {\n // if data is larger \n if(intArray[midPoint] < data){\n // data is in upper half\n lowerBound = midPoint + 1;\n }\n // data is smaller \n else{ \n // data is in lower half \n upperBound = midPoint -1;\n }\n } \n }\n printf(\"Total comparisons made: %d\" , comparisons);\n return index;\n}\nvoid display(){\n int i;\n printf(\"[\");\n // navigate through all items \n for(i=0;i<MAX;i++){\n\t\tprintf(\"%d \",intArray[i]);\n\t}\n\tprintf(\"]\\n\");\n}\nmain(){\n printf(\"Input Array: \");\n display();\n printline(50);\n //find location of 1\n int location = find(55);\n\n // if element was found \n if(location != -1)\n printf(\"\\nElement found at location: %d\" ,(location+1));\n else\n printf(\"\\nElement not found.\");\n}" }, { "code": null, "e": 5228, "s": 5147, "text": "If we compile and run the above program then it would produce following output −" }, { "code": null, "e": 5734, "s": 5228, "text": "Input Array: [1 2 3 4 6 7 9 11 12 14 15 16 17 19 33 34 43 45 55 66 ]\n==================================================\nComparison 1\nlowerBound : 0, intArray[0] = 1\nupperBound : 19, intArray[19] = 66\nComparison 2\nlowerBound : 10, intArray[10] = 15\nupperBound : 19, intArray[19] = 66\nComparison 3\nlowerBound : 15, intArray[15] = 34\nupperBound : 19, intArray[19] = 66\nComparison 4\nlowerBound : 18, intArray[18] = 55\nupperBound : 19, intArray[19] = 66\nTotal comparisons made: 4\nElement found at location: 19\n" }, { "code": null, "e": 5741, "s": 5734, "text": " Print" }, { "code": null, "e": 5752, "s": 5741, "text": " Add Notes" } ]
Java throws Keyword
❮ Java Keywords Throw an exception if age is below 18 (print "Access denied"). If age is 18 or older, print "Access granted": public class Main { static void checkAge(int age) throws ArithmeticException { if (age < 18) { throw new ArithmeticException("Access denied - You must be at least 18 years old."); } else { System.out.println("Access granted - You are old enough!"); } } public static void main(String[] args) { checkAge(15); // Set age to 15 (which is below 18...) } } Try it Yourself » The throws keyword indicates what exception type may be thrown by a method. There are many exception types available in Java: ArithmeticException, ClassNotFoundException, ArrayIndexOutOfBoundsException, SecurityException, etc. Differences between throw and throws: throw is followed by an object (new type) used inside the method throws is followed by a class and used with the method signature Read more about exceptions in our Java Try..Catch Tutorial. ❮ Java Keywords 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: help@w3schools.com Your message has been sent to W3Schools.
[ { "code": null, "e": 18, "s": 0, "text": "\n❮ Java Keywords\n" }, { "code": null, "e": 129, "s": 18, "text": "Throw an exception if age is below 18 (print \"Access \ndenied\"). If age is 18 or older, print \"Access granted\":" }, { "code": null, "e": 523, "s": 129, "text": "public class Main {\n static void checkAge(int age) throws ArithmeticException {\n if (age < 18) {\n throw new ArithmeticException(\"Access denied - You must be at least 18 years old.\");\n }\n else {\n System.out.println(\"Access granted - You are old enough!\");\n }\n }\n\n public static void main(String[] args) {\n checkAge(15); // Set age to 15 (which is below 18...)\n }\n}\n" }, { "code": null, "e": 543, "s": 523, "text": "\nTry it Yourself »\n" }, { "code": null, "e": 619, "s": 543, "text": "The throws keyword indicates what exception type may be thrown by a method." }, { "code": null, "e": 770, "s": 619, "text": "There are many exception types available in Java: ArithmeticException, ClassNotFoundException, ArrayIndexOutOfBoundsException, SecurityException, etc." }, { "code": null, "e": 808, "s": 770, "text": "Differences between throw and throws:" }, { "code": null, "e": 850, "s": 808, "text": "throw is followed by an object (new type)" }, { "code": null, "e": 873, "s": 850, "text": "used inside the method" }, { "code": null, "e": 903, "s": 873, "text": "throws is followed by a class" }, { "code": null, "e": 938, "s": 903, "text": "and used with the method signature" }, { "code": null, "e": 998, "s": 938, "text": "Read more about exceptions in our Java Try..Catch Tutorial." }, { "code": null, "e": 1016, "s": 998, "text": "\n❮ Java Keywords\n" }, { "code": null, "e": 1049, "s": 1016, "text": "We just launchedW3Schools videos" }, { "code": null, "e": 1091, "s": 1049, "text": "Get certifiedby completinga course today!" }, { "code": null, "e": 1198, "s": 1091, "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": 1217, "s": 1198, "text": "help@w3schools.com" } ]
Bootstrap 4 - Breadcrumb
It is used to show hierarchy-based information for a site and indicates current page's location within a navigational hierarchy. Bootstrap uses .breadcrumb class to define the list into breadcrumb and adds a separator via CSS to the list. The following example demonstrates this − <html lang = "en"> <head> <!-- Meta tags --> <meta charset = "utf-8"> <meta name = "viewport" content = "width = device-width, initial-scale = 1, shrink-to-fit = no"> <!-- Bootstrap CSS --> <link rel = "stylesheet" href = "https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity = "sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin = "anonymous"> <title>Bootstrap 4 Example</title> </head> <body> <div class = "container"> <h2>Breadcrumb</h2> <nav aria-label = "breadcrumb"> <!--Add the "breadcrumb" class to ul element that represents the breadcrumb--> <ul class = "breadcrumb"> <!--Add the ".breadcrumb-item" class to each li element within the breadcrumb--> <li class = "breadcrumb-item"><a href = "#">Home</a></li> <li class = "breadcrumb-item"><a href="#">Tutorials Library</a></li> <!--Add the "active" class to li element to represent the current page--> <li class = "breadcrumb-item active" aria-current = "page">Bootstrap 4</li> </ul> </nav> </div> <!-- jQuery first, then Popper.js, then Bootstrap JS --> <script src = "https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity = "sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin = "anonymous"> </script> <script src = "https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js" integrity = "sha384-ZMP7rVo3mIykV+2+9J3UJ46jBk0WLaUAdn689aCwoqbBJiSnjAK/l8WvCWPIPm49" crossorigin = "anonymous"> </script> <script src = "https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js" integrity = "sha384-ChfqqxuZUCnJSK3+MXmPNIyE6ZbWh2IMqE241rYiqJxyMiZ6OW/JmZQ5stwEULTy" crossorigin = "anonymous"> </script> </body> </html> It will produce the following result − Home Tutorials Library Bootstrap 4 26 Lectures 2 hours Anadi Sharma 54 Lectures 4.5 hours Frahaan Hussain 161 Lectures 14.5 hours Eduonix Learning Solutions 20 Lectures 4 hours Azaz Patel 15 Lectures 1.5 hours Muhammad Ismail 62 Lectures 8 hours Yossef Ayman Zedan Print Add Notes Bookmark this page
[ { "code": null, "e": 2055, "s": 1816, "text": "It is used to show hierarchy-based information for a site and indicates current page's location within a navigational hierarchy. Bootstrap uses .breadcrumb class to define the list into breadcrumb and adds a separator via CSS to the list." }, { "code": null, "e": 2097, "s": 2055, "text": "The following example demonstrates this −" }, { "code": null, "e": 4178, "s": 2097, "text": "<html lang = \"en\">\n <head>\n <!-- Meta tags -->\n <meta charset = \"utf-8\">\n <meta name = \"viewport\" content = \"width = device-width, initial-scale = 1, shrink-to-fit = no\">\n \n <!-- Bootstrap CSS -->\n <link rel = \"stylesheet\" \n href = \"https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css\" \n integrity = \"sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO\" \n crossorigin = \"anonymous\">\n \n <title>Bootstrap 4 Example</title>\n </head>\n \n <body>\n <div class = \"container\">\n <h2>Breadcrumb</h2>\n <nav aria-label = \"breadcrumb\">\n <!--Add the \"breadcrumb\" class to ul element that represents the breadcrumb-->\n <ul class = \"breadcrumb\">\n <!--Add the \".breadcrumb-item\" class to each li element within the breadcrumb-->\n <li class = \"breadcrumb-item\"><a href = \"#\">Home</a></li>\n <li class = \"breadcrumb-item\"><a href=\"#\">Tutorials Library</a></li>\n <!--Add the \"active\" class to li element to represent the current page-->\n <li class = \"breadcrumb-item active\" aria-current = \"page\">Bootstrap 4</li>\n </ul>\n </nav>\n </div>\n \n <!-- jQuery first, then Popper.js, then Bootstrap JS -->\n <script src = \"https://code.jquery.com/jquery-3.3.1.slim.min.js\" \n integrity = \"sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo\" \n crossorigin = \"anonymous\">\n </script>\n \n <script src = \"https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js\" \n integrity = \"sha384-ZMP7rVo3mIykV+2+9J3UJ46jBk0WLaUAdn689aCwoqbBJiSnjAK/l8WvCWPIPm49\" \n crossorigin = \"anonymous\">\n </script>\n \n <script src = \"https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js\" \n integrity = \"sha384-ChfqqxuZUCnJSK3+MXmPNIyE6ZbWh2IMqE241rYiqJxyMiZ6OW/JmZQ5stwEULTy\" \n crossorigin = \"anonymous\">\n </script>\n \n </body>\n</html>" }, { "code": null, "e": 4217, "s": 4178, "text": "It will produce the following result −" }, { "code": null, "e": 4222, "s": 4217, "text": "Home" }, { "code": null, "e": 4240, "s": 4222, "text": "Tutorials Library" }, { "code": null, "e": 4252, "s": 4240, "text": "Bootstrap 4" }, { "code": null, "e": 4285, "s": 4252, "text": "\n 26 Lectures \n 2 hours \n" }, { "code": null, "e": 4299, "s": 4285, "text": " Anadi Sharma" }, { "code": null, "e": 4334, "s": 4299, "text": "\n 54 Lectures \n 4.5 hours \n" }, { "code": null, "e": 4351, "s": 4334, "text": " Frahaan Hussain" }, { "code": null, "e": 4388, "s": 4351, "text": "\n 161 Lectures \n 14.5 hours \n" }, { "code": null, "e": 4416, "s": 4388, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 4449, "s": 4416, "text": "\n 20 Lectures \n 4 hours \n" }, { "code": null, "e": 4461, "s": 4449, "text": " Azaz Patel" }, { "code": null, "e": 4496, "s": 4461, "text": "\n 15 Lectures \n 1.5 hours \n" }, { "code": null, "e": 4513, "s": 4496, "text": " Muhammad Ismail" }, { "code": null, "e": 4546, "s": 4513, "text": "\n 62 Lectures \n 8 hours \n" }, { "code": null, "e": 4566, "s": 4546, "text": " Yossef Ayman Zedan" }, { "code": null, "e": 4573, "s": 4566, "text": " Print" }, { "code": null, "e": 4584, "s": 4573, "text": " Add Notes" } ]
SQL Performance Tips #1. Avoiding self joins and join on... | by Guilherme Banhudo | Towards Data Science
Many consider SQL to be data science’s ugly brother, often dedicating little time exploring its nuances and capabilities. And yet, SQL is often the primary means of extracting and preparing information (ETL) to be consumed further on. This series of posts attempts to shed light on some of the often misunderstood or unknown details in modern SQL which can severely hinder a query’s performance. An introductory note is required: I am by no means an SQL expert, feedback and suggestions are more than welcome. The concept of self-join might be daunting for those not used to SQL’s line of thought. But even some seasoned data professionals forget there are alternatives to self-joins, which effectively prevent its complex cardinality. A typical use case is to fill in missing event timestamps. For instance, the following table is missing the event’s termination date, which corresponds to the following event date. Typical solutions rely on using a self-join, which looks cluttered and inefficient, relying on an extremely declarative structure, like so: select ul.id ,ul.user_id ,ul.event_start_date ,coalesce(min(ul_old.event_start_date), '99990101') event_endfrom user_log ulleft join user_log ul_oldon ul.event_start_date < ul_old.event_start_date and ul.user_id = ul_old.user_idgroup by ul.id ,ul.user_id ,ul.event_start_date The same behavior could be emulated using a windowed LEAD term, which effectively retrieves the following event’s timestamp. select id ,user_id ,event_start_date ,lead(event_start_date, 1, '99990101') over (partition by user_id order by event_start_date asc) event_end_datefrom users_log Using a windowed function resulted not only in a cleaner and more succinct code but in significant performance improvements as well. Notice the absence of a loop in the windowed version’s execution plan, a critical aspect of performance. But what if you are interested in retrieving the date of the last known event, after the current record? Or the highest event value after the current date? LEAD wouldn’t help much, unless assuming a fixed lag term. Self-joins on the other hand could do the trick, but they can also be incredibly slow. But what if we could simply look-ahead to the entire dataset for the maximum value? We can, using unbounded partitioned windows. Unbounded window functions allow a partition to consist of all records immediately preceding or following a given record, typically the current record and apply an aggregating function to all those records. In the first case, consider we are interested in retrieving, in addition to the event’s termination date, should it exist, the date of the last known event, disregarding the current date so that if it doesn’t exist, a null is returned instead. To do so, the partition can be modified to skip the current row and retrieve only the posterior records; given the partition is ordered by the event_start_date. select id ,user_id ,event_start_date ,max(event_start_date) over (partition by user_id order by event_start_date rows BETWEEN 1 following and UNBOUNDED following) last_event_datefrom #user_log; How about if we want to sum the event value in the preceding and following 2 records? select id ,user_id ,event_start_date ,sum(event_value) over (partition by user_id order by event_start_date rows BETWEEN 2 preceding and 2 following) last_event_datefrom #user_log; Hopefully, this brief section clarified why using self-joins isn’t always the desirable nor optimal path, and whilst grasping window functions can sometimes take a while, it's a critical and life-saving feature. Another performance hog is typically found in the use of functions and operators in the join statements, to the detriment of a pure equal join. Although apparently innocent, this can lead to the SQL engine not being able to make reasonable decisions on which indexes to use, being forced instead, to perform full-table scans; another possible consequence is an incorrect resultset estimation which again, forces incorrect index usage. For this purpose, consider again a fictional users table, only this time containing user names as well, for one-hundred users, containing a nonclustered index on the name column: Let us retrieve the user data associated with Kaseem Moses, trimming the user name considering the IT department incorrectly inserted some spaces: select namefrom userswhere trim(name) = 'Kaseem Moses' Notice that despite not being able to directly find Kaseem Moses, it still managed to select and scan the NIX_users_name index and applying the trimming operation. However, we get a drastically different behavior if all fields are selected instead of only selecting the name column: select *from userswhere trim(name) = 'Kaseem Moses' Notice how the SQL Server stopped being able to use the nonclustered index. Although in both cases the query estimated 163 results, it actually returned 1 row. It clearly overestimated the resultset, resulting in it thinking the lookup keys would perform poorly, relying on the primary key instead. Recall to consistently use the execution plan and its IO statistics to get a grasp of what's happening, not only will it make it easier to spot performance bottlenecks early on, but it can also help you understand the server’s internal makings. In the next articles, the focus will shift increasingly to these tools. The heavy workload of the self-join cardinality can sometimes be avoided by using windowed functions; Aggregating functions can be combined with the bounding terms effectively allowing creating a narrower, uni, or bi-directional partition window; The bounding terms apply the aggregating function to the entirety of the partition; Whenever possible, avoid using functions or operations to join clauses as they can cause indexes to not be properly selected;
[ { "code": null, "e": 407, "s": 172, "text": "Many consider SQL to be data science’s ugly brother, often dedicating little time exploring its nuances and capabilities. And yet, SQL is often the primary means of extracting and preparing information (ETL) to be consumed further on." }, { "code": null, "e": 568, "s": 407, "text": "This series of posts attempts to shed light on some of the often misunderstood or unknown details in modern SQL which can severely hinder a query’s performance." }, { "code": null, "e": 682, "s": 568, "text": "An introductory note is required: I am by no means an SQL expert, feedback and suggestions are more than welcome." }, { "code": null, "e": 908, "s": 682, "text": "The concept of self-join might be daunting for those not used to SQL’s line of thought. But even some seasoned data professionals forget there are alternatives to self-joins, which effectively prevent its complex cardinality." }, { "code": null, "e": 1089, "s": 908, "text": "A typical use case is to fill in missing event timestamps. For instance, the following table is missing the event’s termination date, which corresponds to the following event date." }, { "code": null, "e": 1229, "s": 1089, "text": "Typical solutions rely on using a self-join, which looks cluttered and inefficient, relying on an extremely declarative structure, like so:" }, { "code": null, "e": 1531, "s": 1229, "text": "select ul.id ,ul.user_id ,ul.event_start_date ,coalesce(min(ul_old.event_start_date), '99990101') event_endfrom user_log ulleft join user_log ul_oldon ul.event_start_date < ul_old.event_start_date and ul.user_id = ul_old.user_idgroup by ul.id ,ul.user_id ,ul.event_start_date" }, { "code": null, "e": 1656, "s": 1531, "text": "The same behavior could be emulated using a windowed LEAD term, which effectively retrieves the following event’s timestamp." }, { "code": null, "e": 1846, "s": 1656, "text": "select id ,user_id ,event_start_date ,lead(event_start_date, 1, '99990101') over (partition by user_id order by event_start_date asc) event_end_datefrom users_log" }, { "code": null, "e": 2084, "s": 1846, "text": "Using a windowed function resulted not only in a cleaner and more succinct code but in significant performance improvements as well. Notice the absence of a loop in the windowed version’s execution plan, a critical aspect of performance." }, { "code": null, "e": 2515, "s": 2084, "text": "But what if you are interested in retrieving the date of the last known event, after the current record? Or the highest event value after the current date? LEAD wouldn’t help much, unless assuming a fixed lag term. Self-joins on the other hand could do the trick, but they can also be incredibly slow. But what if we could simply look-ahead to the entire dataset for the maximum value? We can, using unbounded partitioned windows." }, { "code": null, "e": 2722, "s": 2515, "text": "Unbounded window functions allow a partition to consist of all records immediately preceding or following a given record, typically the current record and apply an aggregating function to all those records." }, { "code": null, "e": 3127, "s": 2722, "text": "In the first case, consider we are interested in retrieving, in addition to the event’s termination date, should it exist, the date of the last known event, disregarding the current date so that if it doesn’t exist, a null is returned instead. To do so, the partition can be modified to skip the current row and retrieve only the posterior records; given the partition is ordered by the event_start_date." }, { "code": null, "e": 3350, "s": 3127, "text": "select id ,user_id ,event_start_date ,max(event_start_date) over (partition by user_id order by event_start_date rows BETWEEN 1 following and UNBOUNDED following) last_event_datefrom #user_log;" }, { "code": null, "e": 3436, "s": 3350, "text": "How about if we want to sum the event value in the preceding and following 2 records?" }, { "code": null, "e": 3643, "s": 3436, "text": "select id ,user_id ,event_start_date ,sum(event_value) over (partition by user_id order by event_start_date rows BETWEEN 2 preceding and 2 following) last_event_datefrom #user_log;" }, { "code": null, "e": 3855, "s": 3643, "text": "Hopefully, this brief section clarified why using self-joins isn’t always the desirable nor optimal path, and whilst grasping window functions can sometimes take a while, it's a critical and life-saving feature." }, { "code": null, "e": 4290, "s": 3855, "text": "Another performance hog is typically found in the use of functions and operators in the join statements, to the detriment of a pure equal join. Although apparently innocent, this can lead to the SQL engine not being able to make reasonable decisions on which indexes to use, being forced instead, to perform full-table scans; another possible consequence is an incorrect resultset estimation which again, forces incorrect index usage." }, { "code": null, "e": 4469, "s": 4290, "text": "For this purpose, consider again a fictional users table, only this time containing user names as well, for one-hundred users, containing a nonclustered index on the name column:" }, { "code": null, "e": 4616, "s": 4469, "text": "Let us retrieve the user data associated with Kaseem Moses, trimming the user name considering the IT department incorrectly inserted some spaces:" }, { "code": null, "e": 4678, "s": 4616, "text": "select namefrom userswhere trim(name) = 'Kaseem Moses'" }, { "code": null, "e": 4842, "s": 4678, "text": "Notice that despite not being able to directly find Kaseem Moses, it still managed to select and scan the NIX_users_name index and applying the trimming operation." }, { "code": null, "e": 4961, "s": 4842, "text": "However, we get a drastically different behavior if all fields are selected instead of only selecting the name column:" }, { "code": null, "e": 5019, "s": 4961, "text": "select *from userswhere trim(name) = 'Kaseem Moses'" }, { "code": null, "e": 5318, "s": 5019, "text": "Notice how the SQL Server stopped being able to use the nonclustered index. Although in both cases the query estimated 163 results, it actually returned 1 row. It clearly overestimated the resultset, resulting in it thinking the lookup keys would perform poorly, relying on the primary key instead." }, { "code": null, "e": 5635, "s": 5318, "text": "Recall to consistently use the execution plan and its IO statistics to get a grasp of what's happening, not only will it make it easier to spot performance bottlenecks early on, but it can also help you understand the server’s internal makings. In the next articles, the focus will shift increasingly to these tools." }, { "code": null, "e": 5737, "s": 5635, "text": "The heavy workload of the self-join cardinality can sometimes be avoided by using windowed functions;" }, { "code": null, "e": 5882, "s": 5737, "text": "Aggregating functions can be combined with the bounding terms effectively allowing creating a narrower, uni, or bi-directional partition window;" }, { "code": null, "e": 5966, "s": 5882, "text": "The bounding terms apply the aggregating function to the entirety of the partition;" } ]
Retail Management - Quick Guide
In my whole retailing career, I have stuck to one guiding principle: give your customers what they want...and customers want everything: a wide assortment of good quality merchandise, lowest possible prices, guaranteed satisfaction with what they buy, friendly knowledgeable service, convenient hours, free parking, and a pleasant shopping experience. You love it when you visit a store that somehow exceeds your expectations and you hate it when a store inconveniences you, or gives you hard time, or just pretends you are invisible... − Sam Walton (Founder, Walmart) In the complex world of today, the consumer is king and retailers are keener on consumer satisfaction. Considering the busy lifestyles of today’s consumers, the retailers also provide services apart from products. Retailing occupies a very important place in the economics of any country. It is the final stage of distribution of product or service. It not only contributes to country’s GDP but also empowers a large number of people by providing employment. Retail Management starts with understanding the term 'Retail'. Retailing includes all activities involved in selling goods or services to the final consumers for personal, non-business use. − Phillip Kotler Any organization that sells the products for consumption to the customers for their personal, family, or household use is in the occupation of retailing. Retailor provides the goods that customer needs, in a desired form, at a required time and place. A retailor does not sell raw material. He sells finished goods or services in the form that customer wants. A retailor does not sell raw material. He sells finished goods or services in the form that customer wants. A retailer buys a wide range of products from different wholesalers and offers the best products under one roof. Thus, the retailor performs the function of both buying and selling. A retailer buys a wide range of products from different wholesalers and offers the best products under one roof. Thus, the retailor performs the function of both buying and selling. A retailor keeps the products or services within easy reach of the customer by making them available at appropriate location. A retailor keeps the products or services within easy reach of the customer by making them available at appropriate location. With industrialization and globalization, the distance between the manufacturer and the consumer has increased. Many times a product is manufactured in one country and sold in another. The levels of intermediaries involved in the marketing channel depends upon the level of service the consumer desires. Type A and B − Retailers. For example, Pantaloons, Walmart. Type C − Service Providers. For example, Eureka Forbes. The retailing formats can be classified into following types as shown in the diagram − Let us see these retailers in detail − Independent Retailers − They own and run a single shop, and determine their policies independently. Their family members can help in business and the ownership of the unit can be passed from one generation to next. The biggest advantage is they can build personal rapport with consumers very easily. For example, stand-alone grocery shops, florists, stationery shops, book shops, etc. Independent Retailers − They own and run a single shop, and determine their policies independently. Their family members can help in business and the ownership of the unit can be passed from one generation to next. The biggest advantage is they can build personal rapport with consumers very easily. For example, stand-alone grocery shops, florists, stationery shops, book shops, etc. Chain Stores − When multiple outlets are under common ownership it is called a chain of stores. Chain stores offer and keep similar merchandise. They are spread over cities and regions. The advantage is, the stores can keep selected merchandise according to the consumers’ preferences in a particular area. For example, Westside Stores, Shopper’s Stop, etc. Chain Stores − When multiple outlets are under common ownership it is called a chain of stores. Chain stores offer and keep similar merchandise. They are spread over cities and regions. The advantage is, the stores can keep selected merchandise according to the consumers’ preferences in a particular area. For example, Westside Stores, Shopper’s Stop, etc. Franchises − These are stores that run business under an established brand name or a particular format by an agreement between franchiser and a franchisee. They can be of two types − Business format. For example, Pizza Hut. Product format. For example, Ice cream parlors of Amul. Franchises − These are stores that run business under an established brand name or a particular format by an agreement between franchiser and a franchisee. They can be of two types − Business format. For example, Pizza Hut. Product format. For example, Ice cream parlors of Amul. Consumers Co-Operative Stores − These are businesses owned and run by consumers with the aim of providing essentials at reasonable cost as compared to market rates. They have to be contemporary with the current business and political policies to keep the business healthy. For example, Sahakar Bhandar from India, Puget Consumers Food Co-Operative from north US, Dublin Food Co-Operative from Ireland. Consumers Co-Operative Stores − These are businesses owned and run by consumers with the aim of providing essentials at reasonable cost as compared to market rates. They have to be contemporary with the current business and political policies to keep the business healthy. For example, Sahakar Bhandar from India, Puget Consumers Food Co-Operative from north US, Dublin Food Co-Operative from Ireland. Let us see these in detail − Convenience Stores − They are small stores generally located near residential premises, and are kept open till late night or 24x7. These stores offer basic essentials such as food, eggs, milk, toiletries, and groceries. They target consumers who want to make quick and easy purchases. For example, mom-and-pop stores, stores located near petrol pumps, 7-Eleven from US, etc. Convenience Stores − They are small stores generally located near residential premises, and are kept open till late night or 24x7. These stores offer basic essentials such as food, eggs, milk, toiletries, and groceries. They target consumers who want to make quick and easy purchases. For example, mom-and-pop stores, stores located near petrol pumps, 7-Eleven from US, etc. Supermarkets − These are large stores with high volume and low profit margin. They target mass consumer and their selling area ranges from 8000 sq.ft. to 10,000 sq.ft. They offer fresh as well as preserved food items, toiletries, groceries and basic household items. Here, at least 70% selling space is reserved for food and grocery products. For example, Food Bazar and Tesco. Supermarkets − These are large stores with high volume and low profit margin. They target mass consumer and their selling area ranges from 8000 sq.ft. to 10,000 sq.ft. They offer fresh as well as preserved food items, toiletries, groceries and basic household items. Here, at least 70% selling space is reserved for food and grocery products. For example, Food Bazar and Tesco. Hypermarkets − These are one-stop shopping retail stores with at least 3000 sq.ft. selling space, out of which 35% space is dedicated towards non-grocery products. They target consumers over large area, and often share space with restaurants and coffee shops. The hypermarket can spread over the space of 80,000 sq.ft. to 250,000 sq.ft. They offer exercise equipment, cycles, CD/DVDs, Books, Electronics equipment, etc. For example, Big Bazar from India, Walmart from US. Hypermarkets − These are one-stop shopping retail stores with at least 3000 sq.ft. selling space, out of which 35% space is dedicated towards non-grocery products. They target consumers over large area, and often share space with restaurants and coffee shops. The hypermarket can spread over the space of 80,000 sq.ft. to 250,000 sq.ft. They offer exercise equipment, cycles, CD/DVDs, Books, Electronics equipment, etc. For example, Big Bazar from India, Walmart from US. Specialty Stores − These retail stores offer a particular kind of merchandise such as home furnishing, domestic electronic appliances, computers and related products, etc. They also offer high level service and product information to consumers. They occupy at least 8000 sq.ft. selling space. For example, Gautier Furniture and Croma from India, High & Mighty from UK. Specialty Stores − These retail stores offer a particular kind of merchandise such as home furnishing, domestic electronic appliances, computers and related products, etc. They also offer high level service and product information to consumers. They occupy at least 8000 sq.ft. selling space. For example, Gautier Furniture and Croma from India, High & Mighty from UK. Departmental Stores − It is a multi-level, multi-product retail store spread across average size of 20,000 sq.ft. to 50,000 sq.ft. It offers selling space in the range of 10% to 70% for food, clothing, and household items. For example, The Bombay Store, Ebony, Meena Bazar from India, Marks & Spencer from UK. Departmental Stores − It is a multi-level, multi-product retail store spread across average size of 20,000 sq.ft. to 50,000 sq.ft. It offers selling space in the range of 10% to 70% for food, clothing, and household items. For example, The Bombay Store, Ebony, Meena Bazar from India, Marks & Spencer from UK. Factory Outlets − These are retail stores which sell items that are produced in excess quantity at discounted price. These outlets are located in the close proximity of manufacturing units or in association with other factory outlets. For example, Nike, Bombay Dyeing factory outlets. Factory Outlets − These are retail stores which sell items that are produced in excess quantity at discounted price. These outlets are located in the close proximity of manufacturing units or in association with other factory outlets. For example, Nike, Bombay Dyeing factory outlets. Catalogue Showrooms − These retail outlets keep catalogues of the products for the consumers to refer. The consumer needs to select the product, write its product code and handover it to the clerk who then manages to provide the selected product from the company’s warehouse. For example, Argos from UK. India’s retail HyperCity has joined hands with Argos to provide a catalogue of over 4000 best quality products in the categories of computers, home furnishing, electronics, cookware, fitness, etc. Catalogue Showrooms − These retail outlets keep catalogues of the products for the consumers to refer. The consumer needs to select the product, write its product code and handover it to the clerk who then manages to provide the selected product from the company’s warehouse. For example, Argos from UK. India’s retail HyperCity has joined hands with Argos to provide a catalogue of over 4000 best quality products in the categories of computers, home furnishing, electronics, cookware, fitness, etc. It is the form of retailing where the retailer is in direct contact with the consumer at the workplace or at home. The consumer becomes aware of the product via email or phone call from the retailer, or through an ad on the television, or Internet. The seller hosts a party for interacting with people. Then introduces and demonstrates the products, their utility, and benefits. Buying and selling happens at the same place. The consumer itself is a distributor. For example, Amway and Herbalife multi-level marketing. Non-Store based retailing includes non-personal contact based retailing such as − Mail Orders/Postal Orders/E-Shopping − The consumer can refer a product catalogue on internet and place order for purchasing the product via email/post. Mail Orders/Postal Orders/E-Shopping − The consumer can refer a product catalogue on internet and place order for purchasing the product via email/post. Telemarketing − The products are advertised on the television. The price, warranty, return policies, buying schemes, contact number etc. are described at the end of the Ad. The consumers can place order by calling the retailer’s number. The retailer then delivers the product at the consumer’s doorstep. For example, Asian Skyshop. Telemarketing − The products are advertised on the television. The price, warranty, return policies, buying schemes, contact number etc. are described at the end of the Ad. The consumers can place order by calling the retailer’s number. The retailer then delivers the product at the consumer’s doorstep. For example, Asian Skyshop. Automated Vending/Kiosks − It is most convenient to the consumers and offers frequently purchased items round the clock, such as drinks, candies, chips, newspapers, etc. Automated Vending/Kiosks − It is most convenient to the consumers and offers frequently purchased items round the clock, such as drinks, candies, chips, newspapers, etc. The success of non-store based retailing hugely lies in timely delivery of appropriate product. These retailers provide various services to the end consumer. The services include banking, car rentals, electricity, and cooking gas container delivery. The success of service based retailer lies in service quality, customization, differentiation and timeliness of service, technological upgradation, and consumer-oriented pricing. Here are some commonly used terms in Retail Management − Though the barter system is considered as the oldest form of retailing, the traditional forms of retailing such as neighborhood stores, main-street stores and fairs still exist in the laid-back towns around the world. During post-war years in the US and Europe, small retailers reformed their shops into large organized stores, markets, and malls. Retail evolution mainly took place in three stages − Conventional Established Emerging We have learnt that if we provide people with an occasion and an excuse to shop, they will come. − Kishore Biyani (CEO Future group) Today’s retail market is satisfying diverse needs of its consumers. The consumer’s needs range from as basic as food & food services to as luxurious as jewelry items. In this chapter, we analyze prominent retail sectors around the world, their structure, and the key players in that sector. The retail sectors are prominently divided into Food, Clothing & Textiles, Consumer Durables, Footwear, Jewelry, Books-Music-Gift Articles, and Fuel. It comprises of food and grocery, and food services. The consumers buy packaged food, ready-to-eat food, and avail food services at workplaces. Visiting a restaurant is no more a luxury in today’s busy life. The retail food industry is growing rapidly with the pace of lifestyles around the world. Key Players − Food and Grocery retail: Food Bazar by Pantaloons, More by Aditya Birla, Haldiram’s (India), Tesco (UK), Walmart (US), Carrefour (France). In food services retail − KFC, McDonalds, Pizza Hut, Barista, Café Coffee Day. Similar to food, clothing is one of the basic needs of humans. The textile industry includes manufacturing of fabrics such as natural fibers, synthetic fibers, looms, and various blends. Clothing is mainly seen as ready-to-wear apparels such as shirts, T-shirts, trousers, jeans, ladies wear, kids wear, baby clothes and hosiery garments such as socks, gloves, and inner wear. Key Players − Arrow by Arvind Mills, Park Avenue by Raymond, Century Textiles (India), Lee, Wrangler, Nautica, and Kipling, all by VF Corp (US), Bonito Deco Inc. (Taiwan). The consumer durables are expected to have long life after purchase and are not purchased frequently. It comprises retailing cars, motorcycles, and home appliances. Key Players − Vijay Sales, Croma by Tata, Maruti-Suzuki (India), Honda Motors (US), Samsung Electronics (Korea). Footwear is categorized according to the consumer’s gender, raw material of product, and design as shown in the diagram. Key Players − Bata, Liberty Footwear, Metro Shoes Ltd. (India), Reebok International Ltd.(UK) Two major segments in this retail sector are precious metal jewelry and gemstones. Out of the precious metals, Indian jewelry market forms 80% of gold jewelry, 15% of gemstone studded jewelry, and 5% of other metal jewelry. Regional festivals, special days, and customs drive the demand in this retail sector. Key Players − Tanishq by Tata, Gili by Gitanjali Group. This includes assorted books, movie or audio CDs, gift articles, and souvenirs. These retail shops are often found near residential areas, tourist places, and historical monuments. Festivals and celebrations are main driving factors for sale in this sector. These items are not very frequently purchased and consumer’s emotional factor is attached to the products than its benefit. Key players − Landmark bookstore by Tata enterprise (India), Paperchase (UK). The highest five fuel consuming countries in the world are the US, China, Japan, India, and Russia. This retail involves activities such as production, refining, and distribution. Fuel companies tie up with other retailers such as pharmacies, food & food service, gift article retails to enter into petrol pump convenience business. Key Players − Bharat Petroleum Corporation Ltd., Hindustan Petroleum Corporation Ltd., Oil & Natural Gas Commission Ltd. (India), Siemens Oil & Gas Co. (US), Caltex Australia Petroleum Pty Ltd. (Australia). Michael Porter, a professor from Harvard Business School, designed a framework named Five Forces Analysis for structured analysis of industries. This framework helps to understand the degree of competition in the industry. Let us see according to his framework, what are the five fundamental forces of competition in the retail industry − The easier it is for a new company to enter the industry, fiercer is the competition. Any new entrant poses a threat to the existing players as it can decrease the profit share of existing players. The factors that limit new entrants are − How loyal are end consumers in the industry? How difficult it is for the consumer to switch to the new product? How large is the amount of capital required to enter into the industry? How difficult it is to access distribution channel? How hard it is to acquire new skills for the staff? For example, Pizza Hut, an old player in food services retail, was founded in 1958 at Kansas, US. The entry of Dominos in 1960 at Michigan posed a threat of competition to it. But following their different marketing policies, they both have acquired prominent places in the market. Substitutes are the products or services that provide the same functionality. A successful product leads to creating other similar products. While entering into retail, one should think of − How many near substitutes are available in the market? What is the price of the substitute? What is the consumer perception about those substitutes? By advertising, marketing, and investing in R&D for the product or service, a retail business can elevate its position in the industry. For example, Google+ and Facebook both are social platforms the consumers use for socializing. They provide similar features such as posts, chat, share text, graphics and media content, forming groups, etc. It is the position of buyers and likelihood of their ability to gain benefit while buying. If there are many suppliers and few buyers, the buyers are at advantageous position while pricing and they generally have the last word. The retail managers need to think of the following − How large market share the retail company has? What size of consumers is the company depending upon for its sales? Are buyers buying in large volumes? How many other retail competitors are in the same product line? It is the ability of the supplier to control the cost and supply of the products in the market. If the suppliers are at a dominating position over the company while product pricing, threatening to raise price or reduce supply, then that retail industry is said to be less attractive. The retail managers need to find out answers for the following − What are the substitute products other than what the supplier provides? Is the supplier providing goods to multiple industries? Is the supplier-switching cost high? If the supplier and the company are capable of entering into one another’s business? The rivalry is intense when there are more or less equal sized competitors in the market and there is no unparalleled market leader. In retail management, theories can be broadly classified as follows − It is based on Darwin’s theory of survival: “The fittest would survive the longest”. The retail sector comprises consumers, manufacturers, marketers, suppliers, and changing technology. Those retailers that adapt to changes in demography, technology, consumer preferences, and legal changes are more likely to survive for long and prosper. McNair represents this theory by Wheel of Retailing that explains the changes taking place in retailing. According to him, the new entrant retailers are often into low cost, low profit margin, low structure retail business, which offers some unique, real benefit to the consumers. Over some time they establish themselves well, prosper, and expand their products with more expensive facilities, without losing focus on their core values. This creates a place for yet new entrants in the market thereby creating threat of competition, substitution, and rivalry. Within a broad retail category, there is always a conflict between the retailing of similar formats, which leads to the development of new formats. Thus, the new retail formats are evolved through dialectic process of blending two formats. Say, Thesis is a single retailer around the corner of the residential area. Antithesis is a large departmental store nearby the same residential area, which develops over some time in opposition to Thesis. Antithesis poses a challenge to Thesis. When there is conflict between Thesis and Antithesis, a new format of retail is born. Whether it is stocks or socks, I like buying quality merchandise when it is marked down. − Warren Buffet (American business magnate) Understanding retail consumer deals with understanding their buying behavior in retail stores. Understanding the consumer is important to know who buys what, when, and how. It is also important to know how to evaluate consumer’s response to sales promotion. It is very vital to understand the consumer in the retail sector for the survival and prosperity of the business. A consumer is a user of a product or a service whereas a customer is a buyer of the product or service. The customer decides what to buy and executes the deal of purchasing by paying and availing the product or service. The consumer uses the product or service for oneself. For example, the customer of a pet food is not the consumer of the same. Also, if a mother in a supermarket is buying Nestlé Milo for her toddler son then she is a customer and her son is a consumer. It is sometimes difficult to understand who is actually a decision maker while purchasing when a customer enters the shop accompanying someone else. Thus everyone who enters the shop is considered as a customer. Still, it is necessary to identify composition and origin of the customers. Composition of Customers − It includes customers of various gender, age, economic and educational status, religion, nationality, and occupation. Composition of Customers − It includes customers of various gender, age, economic and educational status, religion, nationality, and occupation. Origin of Customer − From where the customer comes to shop, how much the customer travels to reach the shop, and which type of area the customer lives in. Origin of Customer − From where the customer comes to shop, how much the customer travels to reach the shop, and which type of area the customer lives in. Objective of Customer − Shopping or Buying? Shopping is visiting the shops with the intention of looking for new products and may or may not necessarily include buying. Buying means actually purchasing a product. What does the customer’s body language depict? Objective of Customer − Shopping or Buying? Shopping is visiting the shops with the intention of looking for new products and may or may not necessarily include buying. Buying means actually purchasing a product. What does the customer’s body language depict? The needs, tastes, and preferences of the consumer for whom the products are purchased drives the buying behavior of the customer. The pattern of customer’s buying behavior can be categorized as − Customers divide their place of purchase. Even if all the products they want are available at a shop, they prefer to visit various shops and compare them in terms of prices. When the customers have a choice of which shop to buy from, their loyalty does not remain permanent to a single shop. Study of customer’s place of purchase is important for selection of location, keeping appropriate merchandise, and selecting a distributor in close proximity. It pertains to what items and how many units of items the customer purchases. The customer purchases a product depending upon the following − Availability/Shortage of product Requirement/Choice of product Perishability of product Storage requirements Purchasing power of oneself This category is important for producers, distributors, and retailers. Say, soaps, toothbrushes, potatoes, and apples are purchased by a large group of customers irrespective of their demographics but live lobsters, French grapes, avocadoes, baked beans, or beef are purchased by only a small number of customers with strong regional demarcation. Similarly, the customers rarely purchase a single potato or a banana, like more than two watermelons at a time. Retailers need to keep their working time tuned with customer’s availability. The time of purchase is influenced by − Weather Season Location of customer The frequency of purchase mainly depends on the following factors − Type of commodity Degree of necessity involved Lifestyle of customers Festivals and customs Influence of the person accompanying the customer. For example, Indian family man from intermediate income group would purchase a car not more than two times in his lifetime whereas a same-class customer from US may buy it more frequently. A tennis player would buy required stuff more frequently than a student learning tennis at a school. It is the way a customer purchases. It involves factors such as − Is the customer purchasing alone or is accompanied by someone? How does the customer pay: by cash or by credit? What is the mode of travel for the customer? The more the customer visits a retail shop, the more (s)he is exposed to the sales promotion methods. The use of sales promotional devices increases the number of shop visitors-turned-impulsive buyers. The promotional methods include − Displays − Consumer products are packaged and displayed with aesthetics while on display. Shape, size, color, and decoration create appeal. Displays − Consumer products are packaged and displayed with aesthetics while on display. Shape, size, color, and decoration create appeal. Demonstrations − Consumers are influenced by giving away sample product or by showing how to use the product and its benefits. Demonstrations − Consumers are influenced by giving away sample product or by showing how to use the product and its benefits. Special pricing − Unit’s special price under some scheme or during festive season, coupons, contests, prizes, etc. Special pricing − Unit’s special price under some scheme or during festive season, coupons, contests, prizes, etc. Sales talks − It is verbal or printed advertisement conducted by the salesperson in the shop. Sales talks − It is verbal or printed advertisement conducted by the salesperson in the shop. An urban customer, due to fast paced life would select easy-to-cook or ready-to-eat food over raw food material as compared to rural counterpart who comes from laid-back lifestyle and self-sufficiency in food items grown on farm. It is found that the couples buy more items in a single transaction than a man or a woman shopping alone. Customers devote time for analyzing alternative products or services. Customers purchase required and perishable products quickly but when it comes to investing in consumer durables, (s)he tries to gather more information about the product. Understanding consumer behavior is critical for a retail business in order to create and develop effective marketing strategies and employ four Ps of marketing mix (Product, Price, Place, and Promotion) to generate high revenue in the long run. Here are some factors which directly influence consumer buying behavior − In a well-performing market, customers don’t mind spending on comfort and luxuries. In contrast, during an economic crisis they tend to prioritize their requirements from basic needs to luxuries, in that order and focus only on what is absolutely essential to survive. Every child (a would-be-customer) acquires a personality, thought process, and attitude while growing up by learning, observing, and forming opinions, likes, and dislikes from its surrounding. Buying behavior differs in people depending on the various cultures they are brought up in and different demographics they come from. Social status is nothing but a position of the customer in the society. Generally, people form groups while interacting with each other for the satisfaction of their social needs. These groups have prominent effects on the buying behavior. When customers buy with family members or friends, the chances are more that their choice is altered or biased under peer pressure for the purpose of trying something new. Dominating people in the family can alter the choice or decision making of a submissive customer. Consumers with high income has high self-respect and expects everything best when it comes to buying products or availing services. Consumers of this class don’t generally think twice on cost if he is buying a good quality product. On the other hand, low-income group consumers would prefer a low-cost substitute of the same product. For example, a professional earning handsome pay package would not hesitate to buy an iPhone6 but a taxi driver in India would buy a low-cost mobile. Here is how the personal elements change buying behavior − Gender − Men and women differ in their perspective, objective, and habits while deciding what to buy and actually buying it. Researchers at Wharton’s Jay H. Baker Retail Initiative and the Verde Group, studied men and women on shopping and found that men buy, while women shop. Women have an emotional attachment to shopping and for men it is a mission. Hence, men shop fast and women stay in the shop for a longer time. Men make faster decisions, women prefer to look for better deals even if they have decided on buying a particular product. Wise retail managers set their marketing policies such that the four Ps are appealing to both the genders. Age − People belonging to different ages or stages of life cycles make different purchase decisions. Age − People belonging to different ages or stages of life cycles make different purchase decisions. Occupation − The occupational status changes the requirement of the products or services. For example, a person working as a small-scale farmer may not require a high-priced electronic gadget but an IT professional would need it. Occupation − The occupational status changes the requirement of the products or services. For example, a person working as a small-scale farmer may not require a high-priced electronic gadget but an IT professional would need it. Lifestyle − Customers of different lifestyles choose different products within the same culture. Lifestyle − Customers of different lifestyles choose different products within the same culture. Nature − Customers with high personal awareness, confidence, adaptability, and dominance are too choosy and take time while selecting a product but are quick in making a buying decision. Nature − Customers with high personal awareness, confidence, adaptability, and dominance are too choosy and take time while selecting a product but are quick in making a buying decision. Psychological factors are a major influence in customer’s buying behavior. Some of them are − Motivation − Customers often make purchase decisions by particular motives such as natural force of hunger, thirst, need of safety, to name a few. Motivation − Customers often make purchase decisions by particular motives such as natural force of hunger, thirst, need of safety, to name a few. Perception − Customers form different perceptions about various products or services of the same category after using it. Hence perceptions of customer leads to biased buying decisions. Perception − Customers form different perceptions about various products or services of the same category after using it. Hence perceptions of customer leads to biased buying decisions. Learning − Customers learn about new products or services in the market from various resources such as peers, advertisements, and Internet. Hence, learning largely affects their buying decisions. For example, today’s IT-age customer finds out the difference between two products’ specifications, costs, durability, expected life, looks, etc., and then decides which one to buy. Learning − Customers learn about new products or services in the market from various resources such as peers, advertisements, and Internet. Hence, learning largely affects their buying decisions. For example, today’s IT-age customer finds out the difference between two products’ specifications, costs, durability, expected life, looks, etc., and then decides which one to buy. Beliefs and Attitudes − Beliefs and attitudes are important drivers of customer’s buying decision. Beliefs and Attitudes − Beliefs and attitudes are important drivers of customer’s buying decision. A customer goes through a number of stages as shown in the following figure before actually deciding to buy the product. However, customers get to know about a product from each other. Smart retail managers therefore insist on recording customers’ feedback upon using the product. They can use this information while interacting with the manufacturer on how to upgrade the product. Identifying one’s need is the stimulating factor in buying decision. Here, the customer recognizes his need of buying a product. As far as satisfying a basic need such as hunger, thirst goes, the customer tends to decide quickly. But this step is important when the customer is buying consumer durables. Identifying one’s need is the stimulating factor in buying decision. Here, the customer recognizes his need of buying a product. As far as satisfying a basic need such as hunger, thirst goes, the customer tends to decide quickly. But this step is important when the customer is buying consumer durables. In the next step, the customer tries to find out as much information as he can about the product. In the next step, the customer tries to find out as much information as he can about the product. Further, the customer tries to seek the alternative products. Further, the customer tries to seek the alternative products. Then, the customer selects the best product available as per choice and budget, and decides to buy the same. Then, the customer selects the best product available as per choice and budget, and decides to buy the same. Market segmentation is the natural result of vast differences among people. − Donald Norman (Director, The Design Lab) Market segmentation gives a clear understanding of the retail customers’ requirements. With the clear understanding of market segmentation, the retail managers and marketing personnel can develop strategies to reach out to the customers with specific needs and preferences. It is a process by which the customers are divided into identifiable groups based on their product or service requirements. Market segmentation is very useful for the marketing force of the retail organization to create a custom marketing mix for specific groups. For example, Venus is in the business of retailing organic vegetables. She would prefer to invest her money for advertising to reach out to working and health conscious people who have monthly income of more than say, $10,000. Market segmentation can also be conducted based on customer’s gender, age, religion, nationality, culture, profession, and preferences. There are two types of retails − Organized Retail and Unorganized Retail. Organized Retailing is a large retail chain of shops run with up-to-date technology, accounting transparency, supply chain management, and distribution systems. Unorganized Retailing is nothing but a small retail business conducted by an owner or a caretaker of the shop with no technological and accounting aids. The following table highlights the points that differentiate organized retail from unorganized retail − It is a plan designed by a retail organization on how the business intends to offer its products and services to the customers. There can be various strategies such as merchandise strategy, own-brand strategy, promotion strategy, to name a few. A retail strategy includes identification of the following − The retailer’s target market. Retail format the retailer works out to satisfy the target market’s needs. Sustainable competitive advantage. For effective market segmentation, the following two strategies are used by the marketing force of the organization − Under this strategy, an organization focuses going after large share of only one or very few segment(s). This strategy provides a differential advantage over competing organizations which are not solely concentrating on one segment. For example, Toyota employs this strategy by offering various models under hybrid vehicles market. Under this strategy, an organization focuses its marketing efforts on two or more distinct market segments. For example, Johnson and Johnson offers healthcare products in the range of baby care, skin care, nutritionals, and vision care products segmented for the customers of all ages. Market penetration strategies include the following − It is setting the price of the product or service lesser than that of the competitor’s product or service. Due to decreased cost, volume may increase which can help to maintain a decent level of profit. Increasing product or service promotion on TV, print media, radio channels, e-mails, pulls the customers and drives them to view and avail the product or service. By offering discounts, various buying schemes along with the added benefits can be useful in high market penetration. By distributing the product or service up to the level of saturation helps penetration of market in a better way. For example, Coca Cola has a very high distribution and is available everywhere from small shops to hypermarkets. If a retail organization conducts SWOT Analysis (Strength, Weakness, Opportunity, Threat) before considering growth strategies, it is helpful for analyzing the organization’s current strategy and planning the growth strategy. An American planning expert named Igor Ansoff developed a strategic planning tool that presents four alternative growth strategies. On one dimension there are products and on the other is markets. This matrix provides strategies for market growth. Here is the sequence of these strategies − Market Penetration − Company focuses on selling the existing products or services in the existing market for higher market share. Market Penetration − Company focuses on selling the existing products or services in the existing market for higher market share. Market Development − Company focuses on selling existing products or services to new markets or market segments. Market Development − Company focuses on selling existing products or services to new markets or market segments. Product Development − Company works on innovations in existing products or developing new products for the existing market. Product Development − Company works on innovations in existing products or developing new products for the existing market. Diversification − Company works on developing new products or services for new markets. Diversification − Company works on developing new products or services for new markets. Silicon valley is a mindset; not a location. − Reid Hoffman (Co-Founder, LinkedIn) Before visiting a mall or a shop, the first question that arises in consumers’ mind is, “How far do I have to walk/drive?” In populous cities such as Mumbai, Delhi, Tokyo, and Shanghai to name a few, consumers face rush-hour traffic jams or jams because of road structure. In such cases, to access a retail outlet to procure day-to-day needs becomes very difficult. It is very important for the consumers to have retail stores near where they stay. Retail store location is also an important factor for the marketing team to consider while setting retail marketing strategy. Here are some reasons − Business location is a unique factor which the competitors cannot imitate. Hence, it can give a strong competitive advantage. Business location is a unique factor which the competitors cannot imitate. Hence, it can give a strong competitive advantage. Selection of retail location is a long-term decision. Selection of retail location is a long-term decision. It requires long-term capital investment. It requires long-term capital investment. Good location is the key element for attracting customers to the outlet. Good location is the key element for attracting customers to the outlet. A well-located store makes supply and distribution easier. A well-located store makes supply and distribution easier. Locations can help to change customers’ buying habits. Locations can help to change customers’ buying habits. A trade area is an area where the retailer attracts customers. It is also called catchment area. There are three basic types of trade areas − These are single, free standing shops/outlets, which are isolated from other retailers. They are positioned on roads or near other retailers or shopping centers. They are mainly used for food and non-food retailing, or as convenience shops. For example, kiosks, mom-andpop stores (similar to kirana stores in India). Advantages − Less occupancy cost, away from competition, less operation restrictions. Disadvantages − No pedestrian traffic, low visibility. These are retail locations that have evolved over time and have multiple outlets in close proximity. They are further divided as − Central business districts such as traditional “downtown” areas in cities/towns. Secondary business districts in larger cities and main street or high street locations. Neighborhood districts. Locations along a street or motorway (Strip locations). Advantages − High pedestrian traffic during business hours, high resident traffic, nearby transport hub. Disadvantages − High security required, threat of shoplifting, Poor parking facilities. These are retail locations that are architecturally well-planned to provide a number of outlets preferably under a theme. These sites have large, key retail brand stores (also called “anchor stores”) and a few small stores to add diversity and elevate customers’ interest. There are various types of planned shopping centers such as neighborhood or strip/community centers, malls, lifestyle centers, specialty centers, outlet centers. Advantages − High visibility, high customer traffic, excellent parking facilities. Disadvantages − High security required, high cost of occupancy. The marketing team must analyze retail location with respect to the following issues − Size of Catchment Area − Primary (with 60 to 80% customers), Secondary (15 to 25% customers), and Tertiary (with remaining customers who shop occasionally). Size of Catchment Area − Primary (with 60 to 80% customers), Secondary (15 to 25% customers), and Tertiary (with remaining customers who shop occasionally). Occupancy Costs − Costs of lease/owning are different in different areas, property taxes, location maintenance costs. Occupancy Costs − Costs of lease/owning are different in different areas, property taxes, location maintenance costs. Customer Traffic − Number of customers visiting the location, number of private vehicles passing through the location, number of pedestrians visiting the location. Customer Traffic − Number of customers visiting the location, number of private vehicles passing through the location, number of pedestrians visiting the location. Restrictions Placed on Store Operations − Restrictions on working hours, noise intensity during media promotion events. Restrictions Placed on Store Operations − Restrictions on working hours, noise intensity during media promotion events. Location Convenience − Proximity to residential areas, proximity to public transport facility. Location Convenience − Proximity to residential areas, proximity to public transport facility. A retail company needs to follow the given steps for choosing the right location − Step 1 - Analyze the market in terms of industry, product, and competitors − How old is the company in this business? How many similar businesses are there in this location? What the new location is supposed to provide: new products or new market? How far is the competitor’s location from the company’s prospective location? Step 2 – Understand the Demographics − Literacy of customers in the prospective location, age groups, profession, income groups, lifestyles, religion. Step 3 – Evaluate the Market Potential − Density of population in the prospective location, anticipation of competition impact, estimation of product demand, knowledge of laws and regulations in operations. Step 4 - Identify Alternative Locations − Is there any other potential location? What is its cost of occupancy? Which factors can be compromised if there is a better location around? Step 5 – Finalize the best and most suitable Location for the retail outlet. Once the retail outlet is opened at the selected location, it is important to keep track of how feasible was the choice of the location. To understand this, the retail company carries out two types of location assessments − It is conducted at a national level when the company wants to start a retail business internationally. Under this assessment, the following steps are carried out − Detailed external audit of the market by analyzing locations as macro environment such as political, social, economic, and technical. Detailed external audit of the market by analyzing locations as macro environment such as political, social, economic, and technical. Most important factors are listed such as customer’s level of spending, degree of competition, Personal Disposable Income (PDI), availability of locations, etc., and minimum acceptable level for each factor is defined and the countries are ranked. Most important factors are listed such as customer’s level of spending, degree of competition, Personal Disposable Income (PDI), availability of locations, etc., and minimum acceptable level for each factor is defined and the countries are ranked. The same factors listed above are considered for local regions within the selected countries to find a reliable location. The same factors listed above are considered for local regions within the selected countries to find a reliable location. At this level of evaluation, the location is assessed against four factors namely − Population − Desirable number of suitable customers who will shop. Population − Desirable number of suitable customers who will shop. Infrastructure − The degree to which the store is accessible to the potential customers. Infrastructure − The degree to which the store is accessible to the potential customers. Store Outlet − Identifying the level of competing stores (those which the decrease attractiveness of a location) as well as complementary stores (which increase attractiveness of a location). Store Outlet − Identifying the level of competing stores (those which the decrease attractiveness of a location) as well as complementary stores (which increase attractiveness of a location). Cost − Costs of development and operation. High startup and ongoing costs affect the performance of retail business. Cost − Costs of development and operation. High startup and ongoing costs affect the performance of retail business. Advertising moves people toward goods; merchandising moves goods toward people. − Morris Hite (American Advertising Expert) In the fierce competition of retail, it is very crucial to attract new customers and to keep the existing customers happy by offering them excellent service. Merchandising helps in achieving far more than just sales can achieve. Merchandising is critical for a retail business. The retail managers must employ their skills and tools to streamline the merchandising process as smooth as possible. Merchandising is the sequence of various activities performed by the retailer such as planning, buying, and selling of products to the customers for their use. It is an integral part of handling store operations and e-commerce of retailing. Merchandising presents the products in retail environment to influence the customer’s buying decision. There are two basic types of merchandise − The following factors influence retail merchandising: This includes issues such as how large is the retail business? What is the demographic scope of business: local, national, or international? What is the scope of operations: direct, online with multilingual option, television, telephonic? How large is the storage space? What is the daily number of customers the business is required to serve? Today’s customers have various shopping channels such as in-store, via electronic media such as Internet, television, or telephone, catalogue reference, to name a few. Every option demands different sets of merchandising tasks and experts. Depending on the size of retail business, there are workforces for handling each stage of merchandising from planning, buying, and selling the product or service. The small retailers might employ a couple of persons to execute all duties of merchandising. A merchandising manager is typically responsible to − Lead the merchandising team. Ensure the merchandising process is smooth and timely. Coordinate and communicate with suppliers. Participate in budgeting, setting and meeting sales goals. Train the employees in the team. Merchandise planning is a strategic process in order to increase profits. This includes long-term planning of setting sales goals, margin goals, and stocks. Step 1 - Define merchandise policy. Get a bird’s eye view of existing and potential customers, retail store image, merchandise quality and customer service levels, marketing approach, and finally desired sales and profits. Step 2 – Collect historical information. Gather data about any carry-forward inventory, total merchandise purchases and sales figures. Step 3 – Identify Components of Planning. Customers − Loyal customers, their buying behavior and spending power. Customers − Loyal customers, their buying behavior and spending power. Departments − What departments are there in the retail business, their subclasses? Departments − What departments are there in the retail business, their subclasses? Vendors − Who delivered the right product on time? Who gave discounts? Vendor’s overall performance with the business. Vendors − Who delivered the right product on time? Who gave discounts? Vendor’s overall performance with the business. Current Trends − Finding trend information from sources including trade publications, merchandise suppliers, competition, other stores located in foreign lands, and from own experience. Current Trends − Finding trend information from sources including trade publications, merchandise suppliers, competition, other stores located in foreign lands, and from own experience. Advertising − Pairing buying and advertising activities together, idea about last successful promotions, budget allocation for Ads. Advertising − Pairing buying and advertising activities together, idea about last successful promotions, budget allocation for Ads. Step 4 – Create a long-term plan. Analyze historical information, predict forecast of sales, and create a long-term plan, say for six months. This activity includes the following − Step 1 - Collect Information − Gather information on consumer demand, current trends, and market requirements. It can be received internally from employees, feedback/complaint boxes, demand slips, or externally by vendors, suppliers, competitors, or via the Internet. Step 1 - Collect Information − Gather information on consumer demand, current trends, and market requirements. It can be received internally from employees, feedback/complaint boxes, demand slips, or externally by vendors, suppliers, competitors, or via the Internet. Step 2 - Determine Merchandise Sources − Know who all can satisfy the demand: vendors, suppliers, and producers. Compare them on the basis of prices, timeliness, guarantee/warranty offerings, payment terms, and performance and selecting the best feasible resource(s). Step 2 - Determine Merchandise Sources − Know who all can satisfy the demand: vendors, suppliers, and producers. Compare them on the basis of prices, timeliness, guarantee/warranty offerings, payment terms, and performance and selecting the best feasible resource(s). Step 3 - Evaluate the Merchandise Items − By going through sample products, or the complete lot of products, assess the products for quality. Step 3 - Evaluate the Merchandise Items − By going through sample products, or the complete lot of products, assess the products for quality. Step 4 - Negotiate the Prices − Realize a good deal of purchase by negotiating prices for bulk purchase. Step 4 - Negotiate the Prices − Realize a good deal of purchase by negotiating prices for bulk purchase. Step 5 - Finalize the Purchase − Finalizing the product prices and buying the merchandise by executing buying transaction. Step 5 - Finalize the Purchase − Finalizing the product prices and buying the merchandise by executing buying transaction. Step 6 - Handle and Store the Merchandise − Deciding on how the vendor will deliver the products, examining product packing, acquiring the product, and stocking a part of products in the storehouse. Step 6 - Handle and Store the Merchandise − Deciding on how the vendor will deliver the products, examining product packing, acquiring the product, and stocking a part of products in the storehouse. Step 7 - Record the Buying Figures − Recording details of transactions, number of unit pieces of products according to product categories and sub-classes, and respective unit prices in the inventory management system of the retail business. Step 7 - Record the Buying Figures − Recording details of transactions, number of unit pieces of products according to product categories and sub-classes, and respective unit prices in the inventory management system of the retail business. Cordial relationship with the vendor can be a great asset for the business. A strong rapport with vendors can lead to − Purchasing products when required and paying the vendor for it later according to credit terms. Purchasing products when required and paying the vendor for it later according to credit terms. Getting the latest new products in the market at discount prices or before other retailers can sell them. Getting the latest new products in the market at discount prices or before other retailers can sell them. Having a great service of delivery, timeliness of delivery, returning faulty products with exchange, etc. Having a great service of delivery, timeliness of delivery, returning faulty products with exchange, etc. The following methods are commonly practiced to analyze merchandise performance − It is a process of inventory classification in which the total inventory is classified into three categories − A – Extremely Important Items − Very crucial inventory control on order scheduling, safety, prompt inspection, consumption pattern, stock balance, refill demands. A – Extremely Important Items − Very crucial inventory control on order scheduling, safety, prompt inspection, consumption pattern, stock balance, refill demands. B – Moderately Important Items − Average attention is paid to them. B – Moderately Important Items − Average attention is paid to them. C – Less important Items − Inventory control is completely stress free. C – Less important Items − Inventory control is completely stress free. This approach of segregation gives importance to each item in the inventory. For example, the telescope retailing company might be having small market share but each telescope is an expensive item in its inventory. This way, a company can decide its investment policy in particular items. In this method, the actual sales and forecast sales are compared and the difference is analyzed to determine whether to apply markdown or to place a fresh request for additional merchandise to satisfy current demand. This method is very helpful in evaluating fashion merchandise performance. This method is based on the concept that the customers consider a retailer or a product as a set of features and attributes. It is used to analyze various alternatives available with regard to vendors and select the best one, which satisfies the store requirements. Customers remember the service a lot longer than they remember the price. − Lauren Freedman (President, E-tailing Group) The retail business operations include all the activities that the employers perform to keep the store functioning smoothly. The shopping experience of a customer is planned before the customer enters, shops, and leaves the store with a smile or with agony by carrying a perception about the store. This experience drives the customer’s decision of visiting the store in future. Let us see, what efforts retail business operations executives put in to make the shopping experience memorable for the customer. The retail store being the fundamental source of revenue and the place of customer interaction, is vital to the retailer. The store manager may not himself perform, but is responsible for the following duties − Maintaining cleanliness in the store. Maintaining cleanliness in the store. Ensuring adequate stock of merchandise in the store. Ensuring adequate stock of merchandise in the store. Appropriate planning, scheduling, and organization of staff, inventory and expenses, for short and long-term success. Appropriate planning, scheduling, and organization of staff, inventory and expenses, for short and long-term success. Monitoring the loss and taking preventive measures to protect the company’s assets and products in the store. Monitoring the loss and taking preventive measures to protect the company’s assets and products in the store. Upgrading store to reflect high profitable image. Upgrading store to reflect high profitable image. Communicating with head office/regional office when required. Communicating with head office/regional office when required. Conducting constructive meetings with staff to boost their morale and motivate the staff to achieve sales goals. Conducting constructive meetings with staff to boost their morale and motivate the staff to achieve sales goals. Communicating with customers to identify their needs, grievances, and complaints. Communicating with customers to identify their needs, grievances, and complaints. Ensuring that the store is in compliance with employment laws regarding salary, work hours, and equal employment opportunities. Ensuring that the store is in compliance with employment laws regarding salary, work hours, and equal employment opportunities. Writing performance appraisals for assisting staff. Writing performance appraisals for assisting staff. The store manager ensures that these duties are performed according to the guidelines set by the company. The store premises are as important as the retail store itself. Managing premises includes the following tasks − Determining Working Hours of Store. It majorly depends upon the target audience, retailed products, and store location. For example, a grocery store near residential area should open earlier than a fashion store. Also, a solitary store can be open as long as the owner wants to but a store in a mall has to adhere to working hours set by the mall management. Managing Store Security. It helps avoiding inventory shrinkage. It depends upon the size of store, the product, and the location of store. Some retailers attach electronic tags on products, which are sensed at store entrance and exits by sensors for theft detection. Some stores install video cameras to monitor movement and some provide separate entry and exit for personnel so that they can be checked. For example, a large departmental store needs high security than the grocery store located near residential area. Here are some basic formulae used while managing premises − Transaction per Hour = No. of Transactions/Number of Hours The retailer keeps track of the number of transactions per hour, which helps in determining store hours and staff scheduling. Sales per Transaction = Net Sales/Number of Transactions The result gives the value of the average sales and net return, which is used to study sales trends over time. Hourly Customer Traffic = Customer Traffic In/Number of Hours This measure is used to track total number of customer traffic per unit time. It is then applied to schedule hours and determine staff strength. Merchandise manager, category manager, and other staff handle the inventory. It includes the following tasks − Receiving products from the vendor. Receiving products from the vendor. Recording inward entry of the products. Recording inward entry of the products. Checking the products against quality norms laid by the retail company and for details such as colors, sizes, and styles. In case of large stores, this task is automated to a large extent. Checking the products against quality norms laid by the retail company and for details such as colors, sizes, and styles. In case of large stores, this task is automated to a large extent. Separating and documenting the faulty or damaged products for returning. Separating and documenting the faulty or damaged products for returning. Displaying the products appropriately to gain customers’ attention. Heavy products are kept at the lower level. Most accessed products are kept at the eye-level and the less accessed products are kept at high level of shelves. On-the-fly-purchased products such as chocolates, candies, etc. are placed near payment counters. Displaying the products appropriately to gain customers’ attention. Heavy products are kept at the lower level. Most accessed products are kept at the eye-level and the less accessed products are kept at high level of shelves. On-the-fly-purchased products such as chocolates, candies, etc. are placed near payment counters. Here are some formulae used for inventory control − Inventory Turnover Rate = Net Sales/Average Retail Value of Inventory It is expressed in number of times and indicates how often the inventory is sold and replaced during a given period of time. Cost of Goods Sold/Average Value of Inventory at Cost When either of these ratio declines, there is a possibility that inventory is excessive. % Inventory Carrying Cost = (Inventory Carrying Cost/Net Sales) * 100 This measure has gained importance due to rise in inventory carrying cost because of high interest rates. This prevents blockage of working capital. Gross Margin Return on Inventory (GMROI) = Gross Margin/Average Value of Inventory The GMROI compares the margin on sales on the original cost value of merchandise to yield a return on merchandise investment. Managing receipt is nothing but determining the manner in which the retailer is going to get the payment for the sold products. The basic modes of receipt are − Cash Credit card Debit card Gift card Large stores have the facility of paying by the modes listed above but small retailers generally prefer accepting cash. The retailer pays card fees depending upon the volume of transactions with the suppliers, manufacturers, or producers. The staff responsible for accepting payment needs to clearly understand the procedure for accepting payment by cards and collecting the amount from the bank. Supply Chain Management (SCM) is the management of materials, information, and finances while they move from manufacturer to wholesaler to retailer to consumer. It involves the activities of coordinating and integrating these flows within and out of a retail business. Most supply chains operate in collaboration if the suppliers and retail businesses are dealing with each other for a long time. Retailers depend upon supply chain members to a great extent. If the retailers develop a strong partnership with supply chain members, it can be beneficial for suppliers to create seamless procedures, which are difficult to imitate. The top management of a retail business decides the customer service policy. The entire retail store staff is trained for customer service. Each employer in the retail store ensures that the service starts with smile and the interacting customer is comfortable and has a pleasant shopping experience. The promptness and politeness of the retail store staff, their knowledge about the product and language, ability to overcome challenges, and rapidness at the billing counter; everything is noted by the customer. These aspects build a great deal of customer’s perception about the store. Many retail stores train staff members to handle the cash counter. They have also introduced a concept of express billing where customers buying less than 10 products can bill faster without having to stand in the regular payment queue. During festivals and markdown periods, the trend of shopping increases. Customer Conversion Ratio = (Number of Transactions/Customer Traffic) * 100 The result is the retailer’s ability to turn a potential customer into a buyer. It is also called “walk to buy ratio”. Low results mean that promotional activities are not being converted into sales and the overall sales efforts need to be assessed afresh. Space management is one of the crucial challenges faced by today’s retail managers. A well-organized shopping place increases productivity of inventory, enhances customers’ shopping experience, reduces operating costs, and increases financial performance of the retail store. It also elevates the chances of customer loyalty. Let us see, how space management is important and how retailers manage it. It is the process of managing the floor space adequately to facilitate the customers and to increase the sale. Since store space is a limited resource, it needs to be used wisely. Space management is very crucial in retail as the sales volume and gross profitability depends on the amount of space used to generate those sales. While allocating the space to various products, the managers need to consider the following points − Product Category − Profit builders − High profit margins-low sales products. Allocate quality space rather than quantity. Star performers − Products exceeding sales and profit margins. Allocate large amount of quality space. Space wasters − Low sales-low profit margins products. Put them at the top or bottom of shelves. Traffic builders − High sales-low profit margins products. These products need to be displayed close to impulse products. Product Category − Profit builders − High profit margins-low sales products. Allocate quality space rather than quantity. Profit builders − High profit margins-low sales products. Allocate quality space rather than quantity. Star performers − Products exceeding sales and profit margins. Allocate large amount of quality space. Star performers − Products exceeding sales and profit margins. Allocate large amount of quality space. Space wasters − Low sales-low profit margins products. Put them at the top or bottom of shelves. Space wasters − Low sales-low profit margins products. Put them at the top or bottom of shelves. Traffic builders − High sales-low profit margins products. These products need to be displayed close to impulse products. Traffic builders − High sales-low profit margins products. These products need to be displayed close to impulse products. Size, shape, and weight of the product. Size, shape, and weight of the product. Product adjacencies − It means which products can coexist on display? Product adjacencies − It means which products can coexist on display? Product life on the shelf. Product life on the shelf. Here are the steps to take into consideration for using floor space effectively − Measure the total area of space available. Measure the total area of space available. Divide this area into selling and non-selling areas such as aisle, storage, promotional displays, customer support cell, (trial rooms in case of clothing retail) and billing counters. Divide this area into selling and non-selling areas such as aisle, storage, promotional displays, customer support cell, (trial rooms in case of clothing retail) and billing counters. Create a Planogram, a pictorial diagram that depicts how and where to place specific retail products on shelves or displays in order to increase customer purchases. Create a Planogram, a pictorial diagram that depicts how and where to place specific retail products on shelves or displays in order to increase customer purchases. Allocate the selling space to each product category. Determine the amount of space for a particular category by considering historical and forecasted sales data. Determine the space for billing counter by referring historical customer volume data. In case of clothing retail, allocate a separate space for trial rooms that is near the product display but away from the billing area. Allocate the selling space to each product category. Determine the amount of space for a particular category by considering historical and forecasted sales data. Determine the space for billing counter by referring historical customer volume data. In case of clothing retail, allocate a separate space for trial rooms that is near the product display but away from the billing area. Determine the location of the product categories within the space. This helps the customers to locate the required product easily. Determine the location of the product categories within the space. This helps the customers to locate the required product easily. Decide product adjacencies logically. This facilitates multiple product purchase. For example, pasta sauces and spices are kept near raw pasta packets. Decide product adjacencies logically. This facilitates multiple product purchase. For example, pasta sauces and spices are kept near raw pasta packets. Make use of irregular shaped corner space wisely. Some products such as domestic cleaning devices or garden furniture can stand in a corner. Make use of irregular shaped corner space wisely. Some products such as domestic cleaning devices or garden furniture can stand in a corner. Allocate space for promotional displays and schemes facing towards road to notify and attract the customers. Use glass walls or doors wisely for promotion. Allocate space for promotional displays and schemes facing towards road to notify and attract the customers. Use glass walls or doors wisely for promotion. Customer buying behavior is an important point of consideration while designing store layout. The objectives of store layout and design are − It should attract customers. It should help the customers to locate the products effortlessly. It should help the customers spend longer time in the store. It should motivate customers to make unplanned, impulsive purchases. It should influence the customers’ buying behavior. The retail store layouts are designed in way to use the space efficiently. There are broadly three popular layouts for retail stores − Grid Layout − Mainly used in grocery stores. Loop Layout − Used in malls and departmental stores. Free Layout − Followed mainly in luxury retail or fashion stores. Both internal and external factors matter when it comes to store design. The store interior is the area where customers actually look for products and make purchases. It directly contributes to influence customer decision making. In includes the following − Clear and adequate walking space, separate from product display area. Clear and adequate walking space, separate from product display area. Free standing displays: Fixtures, rotary displays, or mannequins installed to attract customers’ attention and bring them to the store. Free standing displays: Fixtures, rotary displays, or mannequins installed to attract customers’ attention and bring them to the store. End caps: These displays at the end of the aisles can be used to display promotional offers. End caps: These displays at the end of the aisles can be used to display promotional offers. Windows and doors can provide visual messages about merchandise on sale. Windows and doors can provide visual messages about merchandise on sale. Proper lighting at the product display. For example, jewelry retail needs more acute lighting. Proper lighting at the product display. For example, jewelry retail needs more acute lighting. Relevant signage with readable typefaces and limited text for product categories, for promotional schemes, and at Point of Sale (POS) that guides customers’ decision-making process. It can also include hanging signage for enhancing visibility. Relevant signage with readable typefaces and limited text for product categories, for promotional schemes, and at Point of Sale (POS) that guides customers’ decision-making process. It can also include hanging signage for enhancing visibility. Sitting area for a few differently abled people or senior citizens. Sitting area for a few differently abled people or senior citizens. This area outside the store is as much important as the interior of the store. It communicates with the customer on who the retailer is and what it stands for. The exterior includes − Name of the store, which tells the world that it exists. It can be a plain painted board or as fancy as an aesthetically designed digital board of the outlet. Name of the store, which tells the world that it exists. It can be a plain painted board or as fancy as an aesthetically designed digital board of the outlet. The store entrance: Standard or automatic, glass, wood, or metal? Width of the entrance. The store entrance: Standard or automatic, glass, wood, or metal? Width of the entrance. The cleanliness of the area around the store. The cleanliness of the area around the store. The aesthetics used to draw the customers inside the store. The aesthetics used to draw the customers inside the store. The bitterness of poor quality remains a long after low price is forgotten. − Leon M. Cautillo We as customers, often get to read advertisements from various retailers saying, “Quality product for right price!” This leads to following questions such as what is the right price and who sets it? What are the factors and strategies that determine the price for what we buy? The core capability of the retailers lies in pricing the products or services in a right manner to keep the customers happy, recover investment for production, and to generate revenue. The price at which the product is sold to the end customer is called the retail price of the product. Retail price is the summation of the manufacturing cost and all the costs that retailers incur at the time of charging the customer. Retail prices are affected by internal and external factors. Internal factors that influence retail prices include the following − Manufacturing Cost − The retail company considers both, fixed and variable costs of manufacturing the product. The fixed costs does not vary depending upon the production volume. For example, property tax. The variable costs include varying costs of raw material and costs depending upon volume of production. For example, labor. Manufacturing Cost − The retail company considers both, fixed and variable costs of manufacturing the product. The fixed costs does not vary depending upon the production volume. For example, property tax. The variable costs include varying costs of raw material and costs depending upon volume of production. For example, labor. The Predetermined Objectives − The objective of the retail company varies with time and market situations. If the objective is to increase return on investment, then the company may charge a higher price. If the objective is to increase market share, then it may charge a lower price. The Predetermined Objectives − The objective of the retail company varies with time and market situations. If the objective is to increase return on investment, then the company may charge a higher price. If the objective is to increase market share, then it may charge a lower price. Image of the Firm − The retail company may consider its own image in the market. For example, companies with large goodwill such as Procter & Gamble can demand a higher price for their products. Image of the Firm − The retail company may consider its own image in the market. For example, companies with large goodwill such as Procter & Gamble can demand a higher price for their products. Product Status − The stage at which the product is in its product life cycle determines its price. At the time of introducing the product in the market, the company may charge lower price for it to attract new customers. When the product is accepted and established in the market, the company increases the price. Product Status − The stage at which the product is in its product life cycle determines its price. At the time of introducing the product in the market, the company may charge lower price for it to attract new customers. When the product is accepted and established in the market, the company increases the price. Promotional Activity − If the company is spending high cost on advertising and sales promotion, then it keeps product price high in order to recover the cost of investments. Promotional Activity − If the company is spending high cost on advertising and sales promotion, then it keeps product price high in order to recover the cost of investments. External prices that influence retail prices include the following − Competition − In case of high competition, the prices may be set low to face the competition effectively, and if there is less competition, the prices may be kept high. Competition − In case of high competition, the prices may be set low to face the competition effectively, and if there is less competition, the prices may be kept high. Buying Power of Consumers − The sensitivity of the customer towards price variation and purchasing power of the customer contribute to setting price. Buying Power of Consumers − The sensitivity of the customer towards price variation and purchasing power of the customer contribute to setting price. Government Policies − Government rules and regulation about manufacturing and announcement of administered prices can increase the price of product. Government Policies − Government rules and regulation about manufacturing and announcement of administered prices can increase the price of product. Market Conditions − If market is under recession, the consumers buying pattern changes. To modify their buying behavior, the product prices are set less. Market Conditions − If market is under recession, the consumers buying pattern changes. To modify their buying behavior, the product prices are set less. Levels of Channels Involved − The retailer has to consider number of channels involved from manufacturing to retail and their expectations. The deeper the level of channels, the higher would be the product prices. Levels of Channels Involved − The retailer has to consider number of channels involved from manufacturing to retail and their expectations. The deeper the level of channels, the higher would be the product prices. The price charged is high if there is high demand for the product and low if the demand is low. The methods employed while pricing the product on the basis of demand are − Price Skimming − Initially the product is charged at a high price that the customer is willing to pay and then it decreases gradually with time. Price Skimming − Initially the product is charged at a high price that the customer is willing to pay and then it decreases gradually with time. Odd Even Pricing − The customers perceive prices like 99.99, 11.49 to be cheaper than 100. Odd Even Pricing − The customers perceive prices like 99.99, 11.49 to be cheaper than 100. Penetration Pricing − Price is reduced to compete with other similar products to allow more customer penetration. Penetration Pricing − Price is reduced to compete with other similar products to allow more customer penetration. Prestige Pricing − Pricing is done to convey quality of the product. Prestige Pricing − Pricing is done to convey quality of the product. Price Bundling − The offer of additional product or service is combined with the main product, together with special price. Price Bundling − The offer of additional product or service is combined with the main product, together with special price. A method of determining prices that takes a retail company’s profit objectives and production costs into account. These methods include the following − Cost plus Pricing − The company sets prices little above the manufacturing cost. For example, if the cost of a product is Rs. 600 per unit and the marketer expects 10 per cent profit, then the selling price is set to Rs. 660. Mark-up Pricing − The mark-ups are calculated as a percentage of the selling price and not as a percentage of the cost price. The formula used to determine the selling price is − Selling Price = Average unit cost/Selling price Break-even Pricing − The retail company determines the level of sales needed to cover all the relevant fixed and variable costs. They break-even when there is neither profit nor loss. For example, Fixed cost = Rs. 2, 00,000, Variable cost per unit = Rs. 15, and Selling price = Rs. 20. In this case, the company needs to sell (2,00, 000 / (20-15)) = 40,000 units to break even the fixed cost. Hence, the company may plan to sell at least 40,000 units to be profitable. If it is not possible, then it has to increase the selling price. The following formula is used to calculate the break-even point − Contribution = Selling price – Variable cost per unit Target Return Pricing − The retail company sets prices in order to achieve a particular Return On Investment (ROI). This can be calculated using the following formula − Target return price = Total costs + (Desired % ROI investment)/Total sales in units For example, Total investment = Rs. 10,000, Desired ROI = 20 per cent, Total cost = Rs.5000, and Total expected sales = 1,000 units Then the target return price will be Rs. 7 per unit as shown below − Target Return Price = (5000 + (20% * 10,000))/ 1000 = Rs. 7 This method ensures that the price exceeds all costs and contributes to profit. Early Cash Recovery Pricing − When market forecasts depict short life, it is essential for the price sensitive product segments such as fashion and technology to recover the investment. Sometimes the company anticipates the entry of a larger company in the market. In these cases, the companies price their products to shorten the risks and maximize short-term profit. When a retail company sets the prices for its product depending on how much the competitor is charging for a similar product, it is competition-oriented pricing. Competitor’s Parity − The retail company may set the price as close as the giant competitor in the market. Competitor’s Parity − The retail company may set the price as close as the giant competitor in the market. Discount Pricing − A product is priced at low cost if it is lacking some feature than the competitor’s product. Discount Pricing − A product is priced at low cost if it is lacking some feature than the competitor’s product. The company may charge different prices for the same product or service. Customer Segment Pricing − The price is charged differently for customers from different customer segments. For example, customers who purchase online may be charged less as the cost of service is low for the segment of online customers. Customer Segment Pricing − The price is charged differently for customers from different customer segments. For example, customers who purchase online may be charged less as the cost of service is low for the segment of online customers. Time Pricing − The retailer charges price depending upon time, season, occasions, etc. For example, many resorts charge more for their vacation packages depending on the time of year. Time Pricing − The retailer charges price depending upon time, season, occasions, etc. For example, many resorts charge more for their vacation packages depending on the time of year. Location Pricing − The retailer charges the price depending on where the customer is located. For example, front-row seats of a drama theater are charged high price than rear-row seats. Location Pricing − The retailer charges the price depending on where the customer is located. For example, front-row seats of a drama theater are charged high price than rear-row seats. Retail marketing is the range of activities the retailer does to create awareness about the products or services among customers for selling. Retail marketing consists of visual merchandising, sales promotion, advertising, and marketing mix. All these factors are involved in shaping the marketing strategies of retail. It is the activity of developing floor plans and three-dimensional displays in order to engage customers and boost sales. Both, products or services can be displayed to highlight their features and benefits. It is based on the idea that good looks pay off. It requires creativity and an eye for presenting the products or services aesthetically so that the customers find it appealing and are motivated towards buying. Visual merchandising involves displaying products or services aesthetically using various objects, colors, shapes, materials, designs, and styles to attract the customers. It is advertising the product or service on communication media. The retailer can advertise on electronic media such as television, radio, mobile, and Internet. Print media such as newspaper, brochures, handbills, product catalogues, are also popular among retailers to publish Ads. Retail advertising enables the retailer to reach out to a large number of people and create awareness among them about the product’s availability. The success of an Ad on a particular media depends upon the literacy level of the customers, their age and location. Sales promotion is the communication strategy designed to act directly as an inducement, as added value, or as incentive for the product to the customer. Advertising may create desire to possess the product but sales promotion actually helps conversion to sales. Sales promotion drives existing customers’ loyalty, attracts new customers, influences customers’ buying behavior, and increases sales. It includes the following techniques − They are Ads placed near the merchandise to promote the sale where the customer makes buying decision. They are Ads placed near the checkout or billing counters to promote on-the-fly purchase that the customer makes at the last minute. Some techniques such as Loss Leading (where irrespective of how luxurious the product is, retailer offers steep discount), Markdown (where retailer brings down the prices for wide range of products in the store), and Bundle Pricing (Buy one get one free or Get 3 pay for 1) are used in promotional pricing. Retailers conduct loyalty program for the customers who make frequent purchase by offering first access to new products, free coupons, or special discounted price on particular days. It is identification, satisfaction, and management of customers’ stated and unstated needs and demands by the retailer for mutual benefit. It include four prominent phases − Develop and Customize − Develop products or services to meet customers’ requirements. Customize the same according to customer segments. Develop and Customize − Develop products or services to meet customers’ requirements. Customize the same according to customer segments. Interact and Deliver − Communicate with existing and prospective customers and deliver the product or service with the added value. Interact and Deliver − Communicate with existing and prospective customers and deliver the product or service with the added value. Acquire and Retain − Acquire new customers and retain the loyal ones. Acquire and Retain − Acquire new customers and retain the loyal ones. Understand and Differentiate − Understand customers’ needs, differentiate policies and products depending on customer behavior and preferences. Understand and Differentiate − Understand customers’ needs, differentiate policies and products depending on customer behavior and preferences. The retail marketing mix is the combination of marketing activities that the retailers carry out to meet the target market’s requirements in the best possible way. Retail marketing mix is a combination of 7 Ps − Product − The quality and range of variants of the product or service. Product − The quality and range of variants of the product or service. Place − It is the location where the product or service is sold: online, type of store, location of store, time taken and the mode of transport to reach the retail place. Place − It is the location where the product or service is sold: online, type of store, location of store, time taken and the mode of transport to reach the retail place. Price − Cost of product or service for different customer segments by considering various price affecting factors. Price − Cost of product or service for different customer segments by considering various price affecting factors. Promotion − It is raising customers’ awareness about the product or service and driving customers to buy the products by offering tempting deals. Promotion − It is raising customers’ awareness about the product or service and driving customers to buy the products by offering tempting deals. People − This includes internal stakeholders such as customers, sales staff, management staff, and external stakeholders such as suppliers and supply chain management force. People − This includes internal stakeholders such as customers, sales staff, management staff, and external stakeholders such as suppliers and supply chain management force. Process − It is the range of activities involved in manufacturing and delivering the product or service to the customer. Process − It is the range of activities involved in manufacturing and delivering the product or service to the customer. Physical Environment − Presenting the products or offering services in a wellorganized and attractive manner, keeping an aesthetic sense in presentation to elevate customers’ shopping experience. Physical Environment − Presenting the products or offering services in a wellorganized and attractive manner, keeping an aesthetic sense in presentation to elevate customers’ shopping experience. Retailers communicate with the customers about their products or services, new product updates, and upcoming events regarding retail business via print, audio, video, or Internet media. Retail communication involves the following strategies − Providing retail information based on stored data about celebration dates of the customers. Providing retail information based on stored data about celebration dates of the customers. Holding contests to gain new customers and keep existing ones. Holding contests to gain new customers and keep existing ones. Posting retail information on social websites to increase followers. Posting retail information on social websites to increase followers. Sending coupons on mobile so that customers can avail the benefits of the schemes right when they enter the store. Sending coupons on mobile so that customers can avail the benefits of the schemes right when they enter the store. Conducting customer surveys and reviews. Rewarding participating customers. Conducting customer surveys and reviews. Rewarding participating customers. Using automated retail communication. Using automated retail communication. Retail is a pretty simple business, but what adds complexity is the size and scale. We couldn’t do it without technology. − Bob Nardelli (American businessman) In today’s era, the places in the cities have become congested, infrastructure has changed, transport facilities have increased, and the speed of exchanging information has become extremely fast. Retailers are adopting new technology. Society is changing, consumers are changing and so are the retailers. Retailing has managed to keep itself paced with the changing times. Retailers are changing their business formats, store designs, modes of communication with customers and ways of handling commercial dealings. Modern retailers are adapting new technology for marketing, retail operations, and business transactions. Modern retailers are adapting new technology for marketing, retail operations, and business transactions. Forward-thinking retailers are using social media to communicate with the consumers. Forward-thinking retailers are using social media to communicate with the consumers. With the space crunch, modern retailers have learnt how to use every inch of the floor constructively. With the space crunch, modern retailers have learnt how to use every inch of the floor constructively. Apart from opening online retail store, the retailers take the help of Augmented Reality such as 3D mock-ups to let the customer try the products on themselves. Apart from opening online retail store, the retailers take the help of Augmented Reality such as 3D mock-ups to let the customer try the products on themselves. Retailers are working progressively on delivery of orders that customers placed through online shopping. Retailers are working progressively on delivery of orders that customers placed through online shopping. Retailers are bringing something new now and then to charm the customers. Those places where internet is still not accessible, retailers are exploiting the power of mobile phones to advertise their products. Retailers are bringing something new now and then to charm the customers. Those places where internet is still not accessible, retailers are exploiting the power of mobile phones to advertise their products. Today, the Internet has changed the way products are advertised and the manner of selling-buying transactions. Here are some modern innovations in retail − Modern retail businesses such as malls, specialty stores, and hypermarkets are using micro development and contemporary technology to increase customers’ shopping experience and in turn generate business revenue. Modern retail businesses such as malls, specialty stores, and hypermarkets are using micro development and contemporary technology to increase customers’ shopping experience and in turn generate business revenue. Around the year 2000, online retail startups started changing the face of retail businesses around the world. Around the year 2000, online retail startups started changing the face of retail businesses around the world. Social media websites such as Facebook changed consumer behavior as well as made retailers sweat out to take the benefits and develop their brands. Social media websites such as Facebook changed consumer behavior as well as made retailers sweat out to take the benefits and develop their brands. Modern e-commerce facilities enable faster transactions and allow purchase on a simple 30-day credit facility. Modern e-commerce facilities enable faster transactions and allow purchase on a simple 30-day credit facility. It is nothing but E-Retailing. It is the process of selling or purchasing the products using Internet for B2B or B2C transactions. E-tailing process includes the customer’s visit to the website, purchasing products by choosing a mode of payment, product delivery by the retailer and finally, the customer’s review or feedback. It does not require floor space to display products. It does not require floor space to display products. It allows the customer having internet access to shop any time, any place It allows the customer having internet access to shop any time, any place It saves time of the customer otherwise spent travelling to a shopping place in the real world. It saves time of the customer otherwise spent travelling to a shopping place in the real world. It creates a platform for products from around the world, which are imported by the e-tailer when the customer places an order. It creates a platform for products from around the world, which are imported by the e-tailer when the customer places an order. 20 Lectures 3.5 hours Richa Maheshwari 44 Lectures 5.5 hours Navdeep Yadav Print Add Notes Bookmark this page
[ { "code": null, "e": 2367, "s": 2015, "text": "In my whole retailing career, I have stuck to one guiding principle: give your customers what they want...and customers want everything: a wide assortment of good quality merchandise, lowest possible prices, guaranteed satisfaction with what they buy, friendly knowledgeable service, convenient hours, free parking, and a pleasant shopping experience." }, { "code": null, "e": 2552, "s": 2367, "text": "You love it when you visit a store that somehow exceeds your expectations and you hate it when a store inconveniences you, or gives you hard time, or just pretends you are invisible..." }, { "code": null, "e": 2584, "s": 2552, "text": "− Sam Walton (Founder, Walmart)" }, { "code": null, "e": 2798, "s": 2584, "text": "In the complex world of today, the consumer is king and retailers are keener on consumer satisfaction. Considering the busy lifestyles of today’s consumers, the retailers also provide services apart from products." }, { "code": null, "e": 3043, "s": 2798, "text": "Retailing occupies a very important place in the economics of any country. It is the final stage of distribution of product or service. It not only contributes to country’s GDP but also empowers a large number of people by providing employment." }, { "code": null, "e": 3106, "s": 3043, "text": "Retail Management starts with understanding the term 'Retail'." }, { "code": null, "e": 3233, "s": 3106, "text": "Retailing includes all activities involved in selling goods or services to the final consumers for personal, non-business use." }, { "code": null, "e": 3250, "s": 3233, "text": "− Phillip Kotler" }, { "code": null, "e": 3404, "s": 3250, "text": "Any organization that sells the products for consumption to the customers for their personal, family, or household use is in the occupation of retailing." }, { "code": null, "e": 3502, "s": 3404, "text": "Retailor provides the goods that customer needs, in a desired form, at a required time and place." }, { "code": null, "e": 3610, "s": 3502, "text": "A retailor does not sell raw material. He sells finished goods or services in the form that customer wants." }, { "code": null, "e": 3718, "s": 3610, "text": "A retailor does not sell raw material. He sells finished goods or services in the form that customer wants." }, { "code": null, "e": 3900, "s": 3718, "text": "A retailer buys a wide range of products from different wholesalers and offers the best products under one roof. Thus, the retailor performs the function of both buying and selling." }, { "code": null, "e": 4082, "s": 3900, "text": "A retailer buys a wide range of products from different wholesalers and offers the best products under one roof. Thus, the retailor performs the function of both buying and selling." }, { "code": null, "e": 4208, "s": 4082, "text": "A retailor keeps the products or services within easy reach of the customer by making them available at appropriate location." }, { "code": null, "e": 4334, "s": 4208, "text": "A retailor keeps the products or services within easy reach of the customer by making them available at appropriate location." }, { "code": null, "e": 4638, "s": 4334, "text": "With industrialization and globalization, the distance between the manufacturer and the consumer has increased. Many times a product is manufactured in one country and sold in another. The levels of intermediaries involved in the marketing channel depends upon the level of service the consumer desires." }, { "code": null, "e": 4698, "s": 4638, "text": "Type A and B − Retailers. For example, Pantaloons, Walmart." }, { "code": null, "e": 4754, "s": 4698, "text": "Type C − Service Providers. For example, Eureka Forbes." }, { "code": null, "e": 4841, "s": 4754, "text": "The retailing formats can be classified into following types as shown in the diagram −" }, { "code": null, "e": 4880, "s": 4841, "text": "Let us see these retailers in detail −" }, { "code": null, "e": 5265, "s": 4880, "text": "Independent Retailers − They own and run a single shop, and determine their policies independently. Their family members can help in business and the ownership of the unit can be passed from one generation to next. The biggest advantage is they can build personal rapport with consumers very easily. For example, stand-alone grocery shops, florists, stationery shops, book shops, etc." }, { "code": null, "e": 5650, "s": 5265, "text": "Independent Retailers − They own and run a single shop, and determine their policies independently. Their family members can help in business and the ownership of the unit can be passed from one generation to next. The biggest advantage is they can build personal rapport with consumers very easily. For example, stand-alone grocery shops, florists, stationery shops, book shops, etc." }, { "code": null, "e": 6008, "s": 5650, "text": "Chain Stores − When multiple outlets are under common ownership it is called a chain of stores. Chain stores offer and keep similar merchandise. They are spread over cities and regions. The advantage is, the stores can keep selected merchandise according to the consumers’ preferences in a particular area. For example, Westside Stores, Shopper’s Stop, etc." }, { "code": null, "e": 6366, "s": 6008, "text": "Chain Stores − When multiple outlets are under common ownership it is called a chain of stores. Chain stores offer and keep similar merchandise. They are spread over cities and regions. The advantage is, the stores can keep selected merchandise according to the consumers’ preferences in a particular area. For example, Westside Stores, Shopper’s Stop, etc." }, { "code": null, "e": 6649, "s": 6366, "text": "Franchises − These are stores that run business under an established brand name or a particular format by an agreement between franchiser and a franchisee. They can be of two types −\n\nBusiness format. For example, Pizza Hut.\nProduct format. For example, Ice cream parlors of Amul.\n\n" }, { "code": null, "e": 6832, "s": 6649, "text": "Franchises − These are stores that run business under an established brand name or a particular format by an agreement between franchiser and a franchisee. They can be of two types −" }, { "code": null, "e": 6873, "s": 6832, "text": "Business format. For example, Pizza Hut." }, { "code": null, "e": 6929, "s": 6873, "text": "Product format. For example, Ice cream parlors of Amul." }, { "code": null, "e": 7332, "s": 6929, "text": "Consumers Co-Operative Stores − These are businesses owned and run by consumers with the aim of providing essentials at reasonable cost as compared to market rates. They have to be contemporary with the current business and political policies to keep the business healthy. For example, Sahakar Bhandar from India, Puget Consumers Food Co-Operative from north US, Dublin Food Co-Operative from Ireland.\n" }, { "code": null, "e": 7735, "s": 7332, "text": "Consumers Co-Operative Stores − These are businesses owned and run by consumers with the aim of providing essentials at reasonable cost as compared to market rates. They have to be contemporary with the current business and political policies to keep the business healthy. For example, Sahakar Bhandar from India, Puget Consumers Food Co-Operative from north US, Dublin Food Co-Operative from Ireland.\n" }, { "code": null, "e": 7764, "s": 7735, "text": "Let us see these in detail −" }, { "code": null, "e": 8139, "s": 7764, "text": "Convenience Stores − They are small stores generally located near residential premises, and are kept open till late night or 24x7. These stores offer basic essentials such as food, eggs, milk, toiletries, and groceries. They target consumers who want to make quick and easy purchases.\nFor example, mom-and-pop stores, stores located near petrol pumps, 7-Eleven from US, etc." }, { "code": null, "e": 8424, "s": 8139, "text": "Convenience Stores − They are small stores generally located near residential premises, and are kept open till late night or 24x7. These stores offer basic essentials such as food, eggs, milk, toiletries, and groceries. They target consumers who want to make quick and easy purchases." }, { "code": null, "e": 8514, "s": 8424, "text": "For example, mom-and-pop stores, stores located near petrol pumps, 7-Eleven from US, etc." }, { "code": null, "e": 8892, "s": 8514, "text": "Supermarkets − These are large stores with high volume and low profit margin. They target mass consumer and their selling area ranges from 8000 sq.ft. to 10,000 sq.ft. They offer fresh as well as preserved food items, toiletries, groceries and basic household items. Here, at least 70% selling space is reserved for food and\ngrocery products.\nFor example, Food Bazar and Tesco." }, { "code": null, "e": 9235, "s": 8892, "text": "Supermarkets − These are large stores with high volume and low profit margin. They target mass consumer and their selling area ranges from 8000 sq.ft. to 10,000 sq.ft. They offer fresh as well as preserved food items, toiletries, groceries and basic household items. Here, at least 70% selling space is reserved for food and\ngrocery products." }, { "code": null, "e": 9270, "s": 9235, "text": "For example, Food Bazar and Tesco." }, { "code": null, "e": 9742, "s": 9270, "text": "Hypermarkets − These are one-stop shopping retail stores with at least 3000 sq.ft. selling space, out of which 35% space is dedicated towards non-grocery products. They target consumers over large area, and often share space with restaurants and coffee shops. The hypermarket can spread over the space of 80,000 sq.ft. to 250,000 sq.ft. They offer exercise equipment, cycles, CD/DVDs, Books, Electronics equipment, etc.\nFor example, Big Bazar from India, Walmart from US." }, { "code": null, "e": 10162, "s": 9742, "text": "Hypermarkets − These are one-stop shopping retail stores with at least 3000 sq.ft. selling space, out of which 35% space is dedicated towards non-grocery products. They target consumers over large area, and often share space with restaurants and coffee shops. The hypermarket can spread over the space of 80,000 sq.ft. to 250,000 sq.ft. They offer exercise equipment, cycles, CD/DVDs, Books, Electronics equipment, etc." }, { "code": null, "e": 10214, "s": 10162, "text": "For example, Big Bazar from India, Walmart from US." }, { "code": null, "e": 10583, "s": 10214, "text": "Specialty Stores − These retail stores offer a particular kind of merchandise such as home furnishing, domestic electronic appliances, computers and related products, etc. They also offer high level service and product information to consumers. They occupy at least 8000 sq.ft. selling space.\nFor example, Gautier Furniture and Croma from India, High & Mighty from UK." }, { "code": null, "e": 10876, "s": 10583, "text": "Specialty Stores − These retail stores offer a particular kind of merchandise such as home furnishing, domestic electronic appliances, computers and related products, etc. They also offer high level service and product information to consumers. They occupy at least 8000 sq.ft. selling space." }, { "code": null, "e": 10952, "s": 10876, "text": "For example, Gautier Furniture and Croma from India, High & Mighty from UK." }, { "code": null, "e": 11262, "s": 10952, "text": "Departmental Stores − It is a multi-level, multi-product retail store spread across average size of 20,000 sq.ft. to 50,000 sq.ft. It offers selling space in the range of 10% to 70% for food, clothing, and household items.\nFor example, The Bombay Store, Ebony, Meena Bazar from India, Marks & Spencer from UK." }, { "code": null, "e": 11485, "s": 11262, "text": "Departmental Stores − It is a multi-level, multi-product retail store spread across average size of 20,000 sq.ft. to 50,000 sq.ft. It offers selling space in the range of 10% to 70% for food, clothing, and household items." }, { "code": null, "e": 11572, "s": 11485, "text": "For example, The Bombay Store, Ebony, Meena Bazar from India, Marks & Spencer from UK." }, { "code": null, "e": 11857, "s": 11572, "text": "Factory Outlets − These are retail stores which sell items that are produced in excess quantity at discounted price. These outlets are located in the close proximity of manufacturing units or in association with other factory outlets.\nFor example, Nike, Bombay Dyeing factory outlets." }, { "code": null, "e": 12092, "s": 11857, "text": "Factory Outlets − These are retail stores which sell items that are produced in excess quantity at discounted price. These outlets are located in the close proximity of manufacturing units or in association with other factory outlets." }, { "code": null, "e": 12142, "s": 12092, "text": "For example, Nike, Bombay Dyeing factory outlets." }, { "code": null, "e": 12644, "s": 12142, "text": "Catalogue Showrooms − These retail outlets keep catalogues of the products for the consumers to refer. The consumer needs to select the product, write its product code and handover it to the clerk who then manages to provide the selected product from the company’s warehouse.\nFor example, Argos from UK. India’s retail HyperCity has joined hands with Argos to provide a catalogue of over 4000 best quality products in the categories of computers, home furnishing, electronics, cookware, fitness, etc.\n" }, { "code": null, "e": 12920, "s": 12644, "text": "Catalogue Showrooms − These retail outlets keep catalogues of the products for the consumers to refer. The consumer needs to select the product, write its product code and handover it to the clerk who then manages to provide the selected product from the company’s warehouse." }, { "code": null, "e": 13145, "s": 12920, "text": "For example, Argos from UK. India’s retail HyperCity has joined hands with Argos to provide a catalogue of over 4000 best quality products in the categories of computers, home furnishing, electronics, cookware, fitness, etc." }, { "code": null, "e": 13608, "s": 13145, "text": "It is the form of retailing where the retailer is in direct contact with the consumer at the workplace or at home. The consumer becomes aware of the product via email or phone call from the retailer, or through an ad on the television, or Internet. The seller hosts a party for interacting with people. Then introduces and demonstrates the products, their utility, and benefits. Buying and selling happens at the same place. The consumer itself is a distributor." }, { "code": null, "e": 13664, "s": 13608, "text": "For example, Amway and Herbalife multi-level marketing." }, { "code": null, "e": 13746, "s": 13664, "text": "Non-Store based retailing includes non-personal contact based retailing such as −" }, { "code": null, "e": 13899, "s": 13746, "text": "Mail Orders/Postal Orders/E-Shopping − The consumer can refer a product catalogue on internet and place order for purchasing the product via email/post." }, { "code": null, "e": 14052, "s": 13899, "text": "Mail Orders/Postal Orders/E-Shopping − The consumer can refer a product catalogue on internet and place order for purchasing the product via email/post." }, { "code": null, "e": 14384, "s": 14052, "text": "Telemarketing − The products are advertised on the television. The price, warranty, return policies, buying schemes, contact number etc. are described at the end of the Ad. The consumers can place order by calling the retailer’s number. The retailer then delivers the product at the consumer’s doorstep. For example, Asian Skyshop." }, { "code": null, "e": 14716, "s": 14384, "text": "Telemarketing − The products are advertised on the television. The price, warranty, return policies, buying schemes, contact number etc. are described at the end of the Ad. The consumers can place order by calling the retailer’s number. The retailer then delivers the product at the consumer’s doorstep. For example, Asian Skyshop." }, { "code": null, "e": 14886, "s": 14716, "text": "Automated Vending/Kiosks − It is most convenient to the consumers and offers frequently purchased items round the clock, such as drinks, candies, chips, newspapers, etc." }, { "code": null, "e": 15056, "s": 14886, "text": "Automated Vending/Kiosks − It is most convenient to the consumers and offers frequently purchased items round the clock, such as drinks, candies, chips, newspapers, etc." }, { "code": null, "e": 15152, "s": 15056, "text": "The success of non-store based retailing hugely lies in timely delivery of appropriate product." }, { "code": null, "e": 15306, "s": 15152, "text": "These retailers provide various services to the end consumer. The services include banking, car rentals, electricity, and cooking gas container delivery." }, { "code": null, "e": 15485, "s": 15306, "text": "The success of service based retailer lies in service quality, customization, differentiation and timeliness of service, technological upgradation, and consumer-oriented pricing." }, { "code": null, "e": 15542, "s": 15485, "text": "Here are some commonly used terms in Retail Management −" }, { "code": null, "e": 15890, "s": 15542, "text": "Though the barter system is considered as the oldest form of retailing, the traditional forms of retailing such as neighborhood stores, main-street stores and fairs still exist in the laid-back towns around the world. During post-war years in the US and Europe, small retailers reformed their shops into large organized stores, markets, and malls." }, { "code": null, "e": 15943, "s": 15890, "text": "Retail evolution mainly took place in three stages −" }, { "code": null, "e": 15956, "s": 15943, "text": "Conventional" }, { "code": null, "e": 15968, "s": 15956, "text": "Established" }, { "code": null, "e": 15977, "s": 15968, "text": "Emerging" }, { "code": null, "e": 16074, "s": 15977, "text": "We have learnt that if we provide people with an occasion and an excuse to shop, they will come." }, { "code": null, "e": 16110, "s": 16074, "text": "− Kishore Biyani (CEO Future group)" }, { "code": null, "e": 16401, "s": 16110, "text": "Today’s retail market is satisfying diverse needs of its consumers. The consumer’s needs range from as basic as food & food services to as luxurious as jewelry items. In this chapter, we analyze prominent retail sectors around the world, their structure, and the key players in that sector." }, { "code": null, "e": 16551, "s": 16401, "text": "The retail sectors are prominently divided into Food, Clothing & Textiles, Consumer Durables, Footwear, Jewelry, Books-Music-Gift Articles, and Fuel." }, { "code": null, "e": 16849, "s": 16551, "text": "It comprises of food and grocery, and food services. The consumers buy packaged food, ready-to-eat food, and avail food services at workplaces. Visiting a restaurant is no more a luxury in today’s busy life. The retail food industry is growing rapidly with the pace of lifestyles around the world." }, { "code": null, "e": 17002, "s": 16849, "text": "Key Players − Food and Grocery retail: Food Bazar by Pantaloons, More by Aditya Birla, Haldiram’s (India), Tesco (UK), Walmart (US), Carrefour (France)." }, { "code": null, "e": 17082, "s": 17002, "text": "In food services retail − KFC, McDonalds, Pizza Hut, Barista, Café Coffee Day." }, { "code": null, "e": 17459, "s": 17082, "text": "Similar to food, clothing is one of the basic needs of humans. The textile industry includes manufacturing of fabrics such as natural fibers, synthetic fibers, looms, and various blends. Clothing is mainly seen as ready-to-wear apparels such as shirts, T-shirts, trousers, jeans, ladies wear, kids wear, baby clothes and hosiery garments such as socks, gloves, and inner wear." }, { "code": null, "e": 17631, "s": 17459, "text": "Key Players − Arrow by Arvind Mills, Park Avenue by Raymond, Century Textiles (India), Lee, Wrangler, Nautica, and Kipling, all by VF Corp (US), Bonito Deco Inc. (Taiwan)." }, { "code": null, "e": 17796, "s": 17631, "text": "The consumer durables are expected to have long life after purchase and are not purchased frequently. It comprises retailing cars, motorcycles, and home appliances." }, { "code": null, "e": 17909, "s": 17796, "text": "Key Players − Vijay Sales, Croma by Tata, Maruti-Suzuki (India), Honda Motors (US), Samsung Electronics (Korea)." }, { "code": null, "e": 18030, "s": 17909, "text": "Footwear is categorized according to the consumer’s gender, raw material of product, and design as shown in the diagram." }, { "code": null, "e": 18124, "s": 18030, "text": "Key Players − Bata, Liberty Footwear, Metro Shoes Ltd. (India), Reebok International Ltd.(UK)" }, { "code": null, "e": 18348, "s": 18124, "text": "Two major segments in this retail sector are precious metal jewelry and gemstones. Out of the precious metals, Indian jewelry market forms 80% of gold jewelry, 15% of gemstone studded jewelry, and 5% of other metal jewelry." }, { "code": null, "e": 18434, "s": 18348, "text": "Regional festivals, special days, and customs drive the demand in this retail sector." }, { "code": null, "e": 18490, "s": 18434, "text": "Key Players − Tanishq by Tata, Gili by Gitanjali Group." }, { "code": null, "e": 18872, "s": 18490, "text": "This includes assorted books, movie or audio CDs, gift articles, and souvenirs. These retail shops are often found near residential areas, tourist places, and historical monuments. Festivals and celebrations are main driving factors for sale in this sector. These items are not very frequently purchased and consumer’s emotional factor is attached to the products than its benefit." }, { "code": null, "e": 18950, "s": 18872, "text": "Key players − Landmark bookstore by Tata enterprise (India), Paperchase (UK)." }, { "code": null, "e": 19283, "s": 18950, "text": "The highest five fuel consuming countries in the world are the US, China, Japan, India, and Russia. This retail involves activities such as production, refining, and distribution. Fuel companies tie up with other retailers such as pharmacies, food & food service, gift article retails to enter into petrol pump convenience business." }, { "code": null, "e": 19490, "s": 19283, "text": "Key Players − Bharat Petroleum Corporation Ltd., Hindustan Petroleum Corporation Ltd., Oil & Natural Gas Commission Ltd. (India), Siemens Oil & Gas Co. (US), Caltex Australia Petroleum Pty Ltd. (Australia)." }, { "code": null, "e": 19829, "s": 19490, "text": "Michael Porter, a professor from Harvard Business School, designed a framework named Five Forces Analysis for structured analysis of industries. This framework helps to understand the degree of competition in the industry. Let us see according to his framework, what are the five fundamental forces of competition in the retail industry −" }, { "code": null, "e": 20069, "s": 19829, "text": "The easier it is for a new company to enter the industry, fiercer is the competition. Any new entrant poses a threat to the existing players as it can decrease the profit share of existing players. The factors that limit new entrants are −" }, { "code": null, "e": 20114, "s": 20069, "text": "How loyal are end consumers in the industry?" }, { "code": null, "e": 20181, "s": 20114, "text": "How difficult it is for the consumer to switch to the new product?" }, { "code": null, "e": 20253, "s": 20181, "text": "How large is the amount of capital required to enter into the industry?" }, { "code": null, "e": 20305, "s": 20253, "text": "How difficult it is to access distribution channel?" }, { "code": null, "e": 20357, "s": 20305, "text": "How hard it is to acquire new skills for the staff?" }, { "code": null, "e": 20639, "s": 20357, "text": "For example, Pizza Hut, an old player in food services retail, was founded in 1958 at Kansas, US. The entry of Dominos in 1960 at Michigan posed a threat of competition to it. But following their different marketing policies, they both have acquired prominent places in the market." }, { "code": null, "e": 20830, "s": 20639, "text": "Substitutes are the products or services that provide the same functionality. A successful product leads to creating other similar products. While entering into retail, one should think of −" }, { "code": null, "e": 20885, "s": 20830, "text": "How many near substitutes are available in the market?" }, { "code": null, "e": 20922, "s": 20885, "text": "What is the price of the substitute?" }, { "code": null, "e": 20979, "s": 20922, "text": "What is the consumer perception about those substitutes?" }, { "code": null, "e": 21115, "s": 20979, "text": "By advertising, marketing, and investing in R&D for the product or service, a retail business can elevate its position in the industry." }, { "code": null, "e": 21322, "s": 21115, "text": "For example, Google+ and Facebook both are social platforms the consumers use for socializing. They provide similar features such as posts, chat, share text, graphics and media content, forming groups, etc." }, { "code": null, "e": 21603, "s": 21322, "text": "It is the position of buyers and likelihood of their ability to gain benefit while buying. If there are many suppliers and few buyers, the buyers are at advantageous position while pricing and they generally have the last word. The retail managers need to think of the following −" }, { "code": null, "e": 21650, "s": 21603, "text": "How large market share the retail company has?" }, { "code": null, "e": 21718, "s": 21650, "text": "What size of consumers is the company depending upon for its sales?" }, { "code": null, "e": 21754, "s": 21718, "text": "Are buyers buying in large volumes?" }, { "code": null, "e": 21818, "s": 21754, "text": "How many other retail competitors are in the same product line?" }, { "code": null, "e": 22167, "s": 21818, "text": "It is the ability of the supplier to control the cost and supply of the products in the market. If the suppliers are at a dominating position over the company while product pricing, threatening to raise price or reduce supply, then that retail industry is said to be less attractive. The retail managers need to find out answers for the following −" }, { "code": null, "e": 22239, "s": 22167, "text": "What are the substitute products other than what the supplier provides?" }, { "code": null, "e": 22295, "s": 22239, "text": "Is the supplier providing goods to multiple industries?" }, { "code": null, "e": 22332, "s": 22295, "text": "Is the supplier-switching cost high?" }, { "code": null, "e": 22417, "s": 22332, "text": "If the supplier and the company are capable of entering into one another’s business?" }, { "code": null, "e": 22550, "s": 22417, "text": "The rivalry is intense when there are more or less equal sized competitors in the market and there is no unparalleled market leader." }, { "code": null, "e": 22620, "s": 22550, "text": "In retail management, theories can be broadly classified as follows −" }, { "code": null, "e": 22960, "s": 22620, "text": "It is based on Darwin’s theory of survival: “The fittest would survive the longest”. The retail sector comprises consumers, manufacturers, marketers, suppliers, and changing technology. Those retailers that adapt to changes in demography, technology, consumer preferences, and legal changes are more likely to survive for long and prosper." }, { "code": null, "e": 23065, "s": 22960, "text": "McNair represents this theory by Wheel of Retailing that explains the changes taking place in retailing." }, { "code": null, "e": 23398, "s": 23065, "text": "According to him, the new entrant retailers are often into low cost, low profit margin, low structure retail business, which offers some unique, real benefit to the consumers. Over some time they establish themselves well, prosper, and expand their products with more expensive facilities, without losing focus on their core values." }, { "code": null, "e": 23521, "s": 23398, "text": "This creates a place for yet new entrants in the market thereby creating threat of\ncompetition, substitution, and rivalry." }, { "code": null, "e": 23761, "s": 23521, "text": "Within a broad retail category, there is always a conflict between the retailing of similar formats, which leads to the development of new formats. Thus, the new retail formats are evolved through dialectic process of blending two formats." }, { "code": null, "e": 24093, "s": 23761, "text": "Say, Thesis is a single retailer around the corner of the residential area. Antithesis is a large departmental store nearby the same residential area, which develops over some time in opposition to Thesis. Antithesis poses a challenge to Thesis. When there is conflict between Thesis and Antithesis, a new format of retail is born." }, { "code": null, "e": 24182, "s": 24093, "text": "Whether it is stocks or socks, I like buying quality merchandise when it is marked down." }, { "code": null, "e": 24226, "s": 24182, "text": "− Warren Buffet (American business magnate)" }, { "code": null, "e": 24598, "s": 24226, "text": "Understanding retail consumer deals with understanding their buying behavior in retail stores. Understanding the consumer is important to know who buys what, when, and how. It is also important to know how to evaluate consumer’s response to sales promotion. It is very vital to understand the consumer in the retail sector for the survival and prosperity of the business." }, { "code": null, "e": 24872, "s": 24598, "text": "A consumer is a user of a product or a service whereas a customer is a buyer of the product or service. The customer decides what to buy and executes the deal of purchasing by paying and availing the product or service. The consumer uses the product or service for oneself." }, { "code": null, "e": 25073, "s": 24872, "text": "For example, the customer of a pet food is not the consumer of the same. Also, if a mother in a supermarket is buying Nestlé Milo for her toddler son then she is a customer and her son is a consumer." }, { "code": null, "e": 25361, "s": 25073, "text": "It is sometimes difficult to understand who is actually a decision maker while purchasing when a customer enters the shop accompanying someone else. Thus everyone who enters the shop is considered as a customer. Still, it is necessary to identify composition and origin of the customers." }, { "code": null, "e": 25506, "s": 25361, "text": "Composition of Customers − It includes customers of various gender, age, economic and educational status, religion, nationality, and occupation." }, { "code": null, "e": 25651, "s": 25506, "text": "Composition of Customers − It includes customers of various gender, age, economic and educational status, religion, nationality, and occupation." }, { "code": null, "e": 25806, "s": 25651, "text": "Origin of Customer − From where the customer comes to shop, how much the customer travels to reach the shop, and which type of area the customer lives in." }, { "code": null, "e": 25961, "s": 25806, "text": "Origin of Customer − From where the customer comes to shop, how much the customer travels to reach the shop, and which type of area the customer lives in." }, { "code": null, "e": 26221, "s": 25961, "text": "Objective of Customer − Shopping or Buying? Shopping is visiting the shops with the intention of looking for new products and may or may not necessarily include buying. Buying means actually purchasing a product. What does the customer’s body language depict?" }, { "code": null, "e": 26481, "s": 26221, "text": "Objective of Customer − Shopping or Buying? Shopping is visiting the shops with the intention of looking for new products and may or may not necessarily include buying. Buying means actually purchasing a product. What does the customer’s body language depict?" }, { "code": null, "e": 26678, "s": 26481, "text": "The needs, tastes, and preferences of the consumer for whom the products are purchased drives the buying behavior of the customer. The pattern of customer’s buying behavior can be categorized as −" }, { "code": null, "e": 26970, "s": 26678, "text": "Customers divide their place of purchase. Even if all the products they want are available at a shop, they prefer to visit various shops and compare them in terms of prices. When the customers have a choice of which shop to buy from, their loyalty does not remain permanent to a single shop." }, { "code": null, "e": 27129, "s": 26970, "text": "Study of customer’s place of purchase is important for selection of location, keeping appropriate merchandise, and selecting a distributor in close proximity." }, { "code": null, "e": 27271, "s": 27129, "text": "It pertains to what items and how many units of items the customer purchases. The customer purchases a product depending upon the following −" }, { "code": null, "e": 27304, "s": 27271, "text": "Availability/Shortage of product" }, { "code": null, "e": 27334, "s": 27304, "text": "Requirement/Choice of product" }, { "code": null, "e": 27359, "s": 27334, "text": "Perishability of product" }, { "code": null, "e": 27380, "s": 27359, "text": "Storage requirements" }, { "code": null, "e": 27408, "s": 27380, "text": "Purchasing power of oneself" }, { "code": null, "e": 27755, "s": 27408, "text": "This category is important for producers, distributors, and retailers. Say, soaps, toothbrushes, potatoes, and apples are purchased by a large group of customers irrespective of their demographics but live lobsters, French grapes, avocadoes, baked beans, or beef are purchased by only a small number of customers with strong regional demarcation." }, { "code": null, "e": 27867, "s": 27755, "text": "Similarly, the customers rarely purchase a single potato or a banana, like more than two watermelons at a time." }, { "code": null, "e": 27985, "s": 27867, "text": "Retailers need to keep their working time tuned with customer’s availability. The time of purchase is influenced by −" }, { "code": null, "e": 27993, "s": 27985, "text": "Weather" }, { "code": null, "e": 28000, "s": 27993, "text": "Season" }, { "code": null, "e": 28021, "s": 28000, "text": "Location of customer" }, { "code": null, "e": 28089, "s": 28021, "text": "The frequency of purchase mainly depends on the following factors −" }, { "code": null, "e": 28107, "s": 28089, "text": "Type of commodity" }, { "code": null, "e": 28136, "s": 28107, "text": "Degree of necessity involved" }, { "code": null, "e": 28159, "s": 28136, "text": "Lifestyle of customers" }, { "code": null, "e": 28181, "s": 28159, "text": "Festivals and customs" }, { "code": null, "e": 28232, "s": 28181, "text": "Influence of the person accompanying the customer." }, { "code": null, "e": 28522, "s": 28232, "text": "For example, Indian family man from intermediate income group would purchase a car not more than two times in his lifetime whereas a same-class customer from US may buy it more frequently. A tennis player would buy required stuff more frequently than a student learning tennis at a school." }, { "code": null, "e": 28588, "s": 28522, "text": "It is the way a customer purchases. It involves factors such as −" }, { "code": null, "e": 28651, "s": 28588, "text": "Is the customer purchasing alone or is accompanied by someone?" }, { "code": null, "e": 28700, "s": 28651, "text": "How does the customer pay: by cash or by credit?" }, { "code": null, "e": 28745, "s": 28700, "text": "What is the mode of travel for the customer?" }, { "code": null, "e": 28947, "s": 28745, "text": "The more the customer visits a retail shop, the more (s)he is exposed to the sales promotion methods. The use of sales promotional devices increases the number of shop visitors-turned-impulsive buyers." }, { "code": null, "e": 28981, "s": 28947, "text": "The promotional methods include −" }, { "code": null, "e": 29121, "s": 28981, "text": "Displays − Consumer products are packaged and displayed with aesthetics while on display. Shape, size, color, and decoration create appeal." }, { "code": null, "e": 29261, "s": 29121, "text": "Displays − Consumer products are packaged and displayed with aesthetics while on display. Shape, size, color, and decoration create appeal." }, { "code": null, "e": 29388, "s": 29261, "text": "Demonstrations − Consumers are influenced by giving away sample product or by showing how to use the product and its benefits." }, { "code": null, "e": 29515, "s": 29388, "text": "Demonstrations − Consumers are influenced by giving away sample product or by showing how to use the product and its benefits." }, { "code": null, "e": 29630, "s": 29515, "text": "Special pricing − Unit’s special price under some scheme or during festive season, coupons, contests, prizes, etc." }, { "code": null, "e": 29745, "s": 29630, "text": "Special pricing − Unit’s special price under some scheme or during festive season, coupons, contests, prizes, etc." }, { "code": null, "e": 29839, "s": 29745, "text": "Sales talks − It is verbal or printed advertisement conducted by the salesperson in the shop." }, { "code": null, "e": 29933, "s": 29839, "text": "Sales talks − It is verbal or printed advertisement conducted by the salesperson in the shop." }, { "code": null, "e": 30163, "s": 29933, "text": "An urban customer, due to fast paced life would select easy-to-cook or ready-to-eat food over raw food material as compared to rural counterpart who comes from laid-back lifestyle and self-sufficiency in food items grown on farm." }, { "code": null, "e": 30510, "s": 30163, "text": "It is found that the couples buy more items in a single transaction than a man or a woman shopping alone. Customers devote time for analyzing alternative products or services. Customers purchase required and perishable products quickly but when it comes to investing in consumer durables, (s)he tries to gather more information about the product." }, { "code": null, "e": 30755, "s": 30510, "text": "Understanding consumer behavior is critical for a retail business in order to create and develop effective marketing strategies and employ four Ps of marketing mix (Product, Price, Place, and Promotion) to generate high revenue in the long run." }, { "code": null, "e": 30829, "s": 30755, "text": "Here are some factors which directly influence consumer buying behavior −" }, { "code": null, "e": 31098, "s": 30829, "text": "In a well-performing market, customers don’t mind spending on comfort and luxuries. In contrast, during an economic crisis they tend to prioritize their requirements from basic needs to luxuries, in that order and focus only on what is absolutely essential to survive." }, { "code": null, "e": 31425, "s": 31098, "text": "Every child (a would-be-customer) acquires a personality, thought process, and attitude while growing up by learning, observing, and forming opinions, likes, and dislikes from its surrounding. Buying behavior differs in people depending on the various cultures they are brought up in and different demographics they come from." }, { "code": null, "e": 31605, "s": 31425, "text": "Social status is nothing but a position of the customer in the society. Generally, people form groups while interacting with each other for the satisfaction of their social needs." }, { "code": null, "e": 31935, "s": 31605, "text": "These groups have prominent effects on the buying behavior. When customers buy with family members or friends, the chances are more that their choice is altered or biased under peer pressure for the purpose of trying something new. Dominating people in the family can alter the choice or decision making of a submissive customer." }, { "code": null, "e": 32167, "s": 31935, "text": "Consumers with high income has high self-respect and expects everything best when it comes to buying products or availing services. Consumers of this class don’t generally think twice on cost if he is buying a good quality product." }, { "code": null, "e": 32419, "s": 32167, "text": "On the other hand, low-income group consumers would prefer a low-cost substitute of the same product. For example, a professional earning handsome pay package would not hesitate to buy an iPhone6 but a taxi driver in India would buy a low-cost mobile." }, { "code": null, "e": 32478, "s": 32419, "text": "Here is how the personal elements change buying behavior −" }, { "code": null, "e": 33022, "s": 32478, "text": "Gender − Men and women differ in their perspective, objective, and habits while deciding what to buy and actually buying it. Researchers at Wharton’s Jay H. Baker Retail Initiative and the Verde Group, studied men and women on shopping and found that men buy, while women shop. Women have an emotional attachment to shopping and for men it is a mission. Hence, men shop fast and women stay in the shop for a longer time. Men make faster decisions, women prefer to look for better deals even if they have decided on buying a particular product." }, { "code": null, "e": 33129, "s": 33022, "text": "Wise retail managers set their marketing policies such that the four Ps are appealing to both the genders." }, { "code": null, "e": 33230, "s": 33129, "text": "Age − People belonging to different ages or stages of life cycles make different purchase decisions." }, { "code": null, "e": 33331, "s": 33230, "text": "Age − People belonging to different ages or stages of life cycles make different purchase decisions." }, { "code": null, "e": 33561, "s": 33331, "text": "Occupation − The occupational status changes the requirement of the products or services. For example, a person working as a small-scale farmer may not require a high-priced electronic gadget but an IT professional would need it." }, { "code": null, "e": 33791, "s": 33561, "text": "Occupation − The occupational status changes the requirement of the products or services. For example, a person working as a small-scale farmer may not require a high-priced electronic gadget but an IT professional would need it." }, { "code": null, "e": 33888, "s": 33791, "text": "Lifestyle − Customers of different lifestyles choose different products within the same culture." }, { "code": null, "e": 33985, "s": 33888, "text": "Lifestyle − Customers of different lifestyles choose different products within the same culture." }, { "code": null, "e": 34172, "s": 33985, "text": "Nature − Customers with high personal awareness, confidence, adaptability, and dominance are too choosy and take time while selecting a product but are quick in making a buying decision." }, { "code": null, "e": 34359, "s": 34172, "text": "Nature − Customers with high personal awareness, confidence, adaptability, and dominance are too choosy and take time while selecting a product but are quick in making a buying decision." }, { "code": null, "e": 34453, "s": 34359, "text": "Psychological factors are a major influence in customer’s buying behavior. Some of them\nare −" }, { "code": null, "e": 34600, "s": 34453, "text": "Motivation − Customers often make purchase decisions by particular motives such as natural force of hunger, thirst, need of safety, to name a few." }, { "code": null, "e": 34747, "s": 34600, "text": "Motivation − Customers often make purchase decisions by particular motives such as natural force of hunger, thirst, need of safety, to name a few." }, { "code": null, "e": 34933, "s": 34747, "text": "Perception − Customers form different perceptions about various products or services of the same category after using it. Hence perceptions of customer leads to biased buying decisions." }, { "code": null, "e": 35119, "s": 34933, "text": "Perception − Customers form different perceptions about various products or services of the same category after using it. Hence perceptions of customer leads to biased buying decisions." }, { "code": null, "e": 35497, "s": 35119, "text": "Learning − Customers learn about new products or services in the market from various resources such as peers, advertisements, and Internet. Hence, learning largely affects their buying decisions. For example, today’s IT-age customer finds out the difference between two products’ specifications, costs, durability, expected life, looks, etc., and then decides which one to buy." }, { "code": null, "e": 35875, "s": 35497, "text": "Learning − Customers learn about new products or services in the market from various resources such as peers, advertisements, and Internet. Hence, learning largely affects their buying decisions. For example, today’s IT-age customer finds out the difference between two products’ specifications, costs, durability, expected life, looks, etc., and then decides which one to buy." }, { "code": null, "e": 35974, "s": 35875, "text": "Beliefs and Attitudes − Beliefs and attitudes are important drivers of customer’s buying decision." }, { "code": null, "e": 36073, "s": 35974, "text": "Beliefs and Attitudes − Beliefs and attitudes are important drivers of customer’s buying decision." }, { "code": null, "e": 36194, "s": 36073, "text": "A customer goes through a number of stages as shown in the following figure before\nactually deciding to buy the product." }, { "code": null, "e": 36455, "s": 36194, "text": "However, customers get to know about a product from each other. Smart retail managers therefore insist on recording customers’ feedback upon using the product. They can use this information while interacting with the manufacturer on how to upgrade the product." }, { "code": null, "e": 36759, "s": 36455, "text": "Identifying one’s need is the stimulating factor in buying decision. Here, the customer recognizes his need of buying a product. As far as satisfying a basic need such as hunger, thirst goes, the customer tends to decide quickly. But this step is important when the customer is buying consumer durables." }, { "code": null, "e": 37063, "s": 36759, "text": "Identifying one’s need is the stimulating factor in buying decision. Here, the customer recognizes his need of buying a product. As far as satisfying a basic need such as hunger, thirst goes, the customer tends to decide quickly. But this step is important when the customer is buying consumer durables." }, { "code": null, "e": 37161, "s": 37063, "text": "In the next step, the customer tries to find out as much information as he can about the product." }, { "code": null, "e": 37259, "s": 37161, "text": "In the next step, the customer tries to find out as much information as he can about the product." }, { "code": null, "e": 37321, "s": 37259, "text": "Further, the customer tries to seek the alternative products." }, { "code": null, "e": 37383, "s": 37321, "text": "Further, the customer tries to seek the alternative products." }, { "code": null, "e": 37492, "s": 37383, "text": "Then, the customer selects the best product available as per choice and budget, and decides to buy the same." }, { "code": null, "e": 37601, "s": 37492, "text": "Then, the customer selects the best product available as per choice and budget, and decides to buy the same." }, { "code": null, "e": 37677, "s": 37601, "text": "Market segmentation is the natural result of vast differences among people." }, { "code": null, "e": 37720, "s": 37677, "text": "− Donald Norman (Director, The Design Lab)" }, { "code": null, "e": 37994, "s": 37720, "text": "Market segmentation gives a clear understanding of the retail customers’ requirements. With the clear understanding of market segmentation, the retail managers and marketing personnel can develop strategies to reach out to the customers with specific needs and preferences." }, { "code": null, "e": 38258, "s": 37994, "text": "It is a process by which the customers are divided into identifiable groups based on their product or service requirements. Market segmentation is very useful for the marketing force of the retail organization to create a custom marketing mix for specific groups." }, { "code": null, "e": 38485, "s": 38258, "text": "For example, Venus is in the business of retailing organic vegetables. She would prefer to invest her money for advertising to reach out to working and health conscious people who have monthly income of more than say, $10,000." }, { "code": null, "e": 38621, "s": 38485, "text": "Market segmentation can also be conducted based on customer’s gender, age, religion, nationality, culture, profession, and preferences." }, { "code": null, "e": 38695, "s": 38621, "text": "There are two types of retails − Organized Retail and Unorganized Retail." }, { "code": null, "e": 38856, "s": 38695, "text": "Organized Retailing is a large retail chain of shops run with up-to-date technology, accounting transparency, supply chain management, and distribution systems." }, { "code": null, "e": 39009, "s": 38856, "text": "Unorganized Retailing is nothing but a small retail business conducted by an owner or a caretaker of the shop with no technological and accounting aids." }, { "code": null, "e": 39113, "s": 39009, "text": "The following table highlights the points that differentiate organized retail from unorganized retail −" }, { "code": null, "e": 39358, "s": 39113, "text": "It is a plan designed by a retail organization on how the business intends to offer its products and services to the customers. There can be various strategies such as merchandise strategy, own-brand strategy, promotion strategy, to name a few." }, { "code": null, "e": 39419, "s": 39358, "text": "A retail strategy includes identification of the following −" }, { "code": null, "e": 39449, "s": 39419, "text": "The retailer’s target market." }, { "code": null, "e": 39524, "s": 39449, "text": "Retail format the retailer works out to satisfy the target market’s needs." }, { "code": null, "e": 39559, "s": 39524, "text": "Sustainable competitive advantage." }, { "code": null, "e": 39677, "s": 39559, "text": "For effective market segmentation, the following two strategies are used by the marketing force of the organization −" }, { "code": null, "e": 39910, "s": 39677, "text": "Under this strategy, an organization focuses going after large share of only one or very few segment(s). This strategy provides a differential advantage over competing organizations which are not solely concentrating on one segment." }, { "code": null, "e": 40009, "s": 39910, "text": "For example, Toyota employs this strategy by offering various models under hybrid vehicles market." }, { "code": null, "e": 40117, "s": 40009, "text": "Under this strategy, an organization focuses its marketing efforts on two or more distinct market segments." }, { "code": null, "e": 40295, "s": 40117, "text": "For example, Johnson and Johnson offers healthcare products in the range of baby care, skin care, nutritionals, and vision care products segmented for the customers of all ages." }, { "code": null, "e": 40349, "s": 40295, "text": "Market penetration strategies include the following −" }, { "code": null, "e": 40552, "s": 40349, "text": "It is setting the price of the product or service lesser than that of the competitor’s product or service. Due to decreased cost, volume may increase which can help to maintain a decent level of profit." }, { "code": null, "e": 40833, "s": 40552, "text": "Increasing product or service promotion on TV, print media, radio channels, e-mails, pulls the customers and drives them to view and avail the product or service. By offering discounts, various buying schemes along with the added benefits can be useful in high market penetration." }, { "code": null, "e": 41061, "s": 40833, "text": "By distributing the product or service up to the level of saturation helps penetration of market in a better way. For example, Coca Cola has a very high distribution and is available everywhere from small shops to hypermarkets." }, { "code": null, "e": 41287, "s": 41061, "text": "If a retail organization conducts SWOT Analysis (Strength, Weakness, Opportunity, Threat) before considering growth strategies, it is helpful for analyzing the organization’s current strategy and planning the growth strategy." }, { "code": null, "e": 41484, "s": 41287, "text": "An American planning expert named Igor Ansoff developed a strategic planning tool that presents four alternative growth strategies. On one dimension there are products and on the other is markets." }, { "code": null, "e": 41578, "s": 41484, "text": "This matrix provides strategies for market growth. Here is the sequence of these strategies −" }, { "code": null, "e": 41708, "s": 41578, "text": "Market Penetration − Company focuses on selling the existing products or services in the existing market for higher market share." }, { "code": null, "e": 41838, "s": 41708, "text": "Market Penetration − Company focuses on selling the existing products or services in the existing market for higher market share." }, { "code": null, "e": 41951, "s": 41838, "text": "Market Development − Company focuses on selling existing products or services to new markets or market segments." }, { "code": null, "e": 42064, "s": 41951, "text": "Market Development − Company focuses on selling existing products or services to new markets or market segments." }, { "code": null, "e": 42188, "s": 42064, "text": "Product Development − Company works on innovations in existing products or developing new products for the existing market." }, { "code": null, "e": 42312, "s": 42188, "text": "Product Development − Company works on innovations in existing products or developing new products for the existing market." }, { "code": null, "e": 42400, "s": 42312, "text": "Diversification − Company works on developing new products or services for new markets." }, { "code": null, "e": 42488, "s": 42400, "text": "Diversification − Company works on developing new products or services for new markets." }, { "code": null, "e": 42533, "s": 42488, "text": "Silicon valley is a mindset; not a location." }, { "code": null, "e": 42571, "s": 42533, "text": "− Reid Hoffman (Co-Founder, LinkedIn)" }, { "code": null, "e": 42694, "s": 42571, "text": "Before visiting a mall or a shop, the first question that arises in consumers’ mind is, “How far do I have to walk/drive?”" }, { "code": null, "e": 43020, "s": 42694, "text": "In populous cities such as Mumbai, Delhi, Tokyo, and Shanghai to name a few, consumers face rush-hour traffic jams or jams because of road structure. In such cases, to access a retail outlet to procure day-to-day needs becomes very difficult. It is very important for the consumers to have retail stores near where they stay." }, { "code": null, "e": 43170, "s": 43020, "text": "Retail store location is also an important factor for the marketing team to consider while setting retail marketing strategy. Here are some reasons −" }, { "code": null, "e": 43296, "s": 43170, "text": "Business location is a unique factor which the competitors cannot imitate. Hence, it can give a strong competitive advantage." }, { "code": null, "e": 43422, "s": 43296, "text": "Business location is a unique factor which the competitors cannot imitate. Hence, it can give a strong competitive advantage." }, { "code": null, "e": 43476, "s": 43422, "text": "Selection of retail location is a long-term decision." }, { "code": null, "e": 43530, "s": 43476, "text": "Selection of retail location is a long-term decision." }, { "code": null, "e": 43572, "s": 43530, "text": "It requires long-term capital investment." }, { "code": null, "e": 43614, "s": 43572, "text": "It requires long-term capital investment." }, { "code": null, "e": 43687, "s": 43614, "text": "Good location is the key element for attracting customers to the outlet." }, { "code": null, "e": 43760, "s": 43687, "text": "Good location is the key element for attracting customers to the outlet." }, { "code": null, "e": 43819, "s": 43760, "text": "A well-located store makes supply and distribution easier." }, { "code": null, "e": 43878, "s": 43819, "text": "A well-located store makes supply and distribution easier." }, { "code": null, "e": 43933, "s": 43878, "text": "Locations can help to change customers’ buying habits." }, { "code": null, "e": 43988, "s": 43933, "text": "Locations can help to change customers’ buying habits." }, { "code": null, "e": 44130, "s": 43988, "text": "A trade area is an area where the retailer attracts customers. It is also called catchment area. There are three basic types of trade areas −" }, { "code": null, "e": 44447, "s": 44130, "text": "These are single, free standing shops/outlets, which are isolated from other retailers. They are positioned on roads or near other retailers or shopping centers. They are mainly used for food and non-food retailing, or as convenience shops. For example, kiosks, mom-andpop stores (similar to kirana stores in India)." }, { "code": null, "e": 44533, "s": 44447, "text": "Advantages − Less occupancy cost, away from competition, less operation restrictions." }, { "code": null, "e": 44588, "s": 44533, "text": "Disadvantages − No pedestrian traffic, low visibility." }, { "code": null, "e": 44719, "s": 44588, "text": "These are retail locations that have evolved over time and have multiple outlets in close proximity. They are further divided as −" }, { "code": null, "e": 44800, "s": 44719, "text": "Central business districts such as traditional “downtown” areas in cities/towns." }, { "code": null, "e": 44888, "s": 44800, "text": "Secondary business districts in larger cities and main street or high street locations." }, { "code": null, "e": 44912, "s": 44888, "text": "Neighborhood districts." }, { "code": null, "e": 44968, "s": 44912, "text": "Locations along a street or motorway (Strip locations)." }, { "code": null, "e": 45073, "s": 44968, "text": "Advantages − High pedestrian traffic during business hours, high resident traffic, nearby transport hub." }, { "code": null, "e": 45161, "s": 45073, "text": "Disadvantages − High security required, threat of shoplifting, Poor parking facilities." }, { "code": null, "e": 45596, "s": 45161, "text": "These are retail locations that are architecturally well-planned to provide a number of outlets preferably under a theme. These sites have large, key retail brand stores (also called “anchor stores”) and a few small stores to add diversity and elevate customers’ interest. There are various types of planned shopping centers such as neighborhood or strip/community centers, malls, lifestyle centers, specialty centers, outlet centers." }, { "code": null, "e": 45679, "s": 45596, "text": "Advantages − High visibility, high customer traffic, excellent parking facilities." }, { "code": null, "e": 45743, "s": 45679, "text": "Disadvantages − High security required, high cost of occupancy." }, { "code": null, "e": 45830, "s": 45743, "text": "The marketing team must analyze retail location with respect to the following issues −" }, { "code": null, "e": 45987, "s": 45830, "text": "Size of Catchment Area − Primary (with 60 to 80% customers), Secondary (15 to 25% customers), and Tertiary (with remaining customers who shop occasionally)." }, { "code": null, "e": 46144, "s": 45987, "text": "Size of Catchment Area − Primary (with 60 to 80% customers), Secondary (15 to 25% customers), and Tertiary (with remaining customers who shop occasionally)." }, { "code": null, "e": 46262, "s": 46144, "text": "Occupancy Costs − Costs of lease/owning are different in different areas, property taxes, location maintenance costs." }, { "code": null, "e": 46380, "s": 46262, "text": "Occupancy Costs − Costs of lease/owning are different in different areas, property taxes, location maintenance costs." }, { "code": null, "e": 46544, "s": 46380, "text": "Customer Traffic − Number of customers visiting the location, number of private vehicles passing through the location, number of pedestrians visiting the location." }, { "code": null, "e": 46708, "s": 46544, "text": "Customer Traffic − Number of customers visiting the location, number of private vehicles passing through the location, number of pedestrians visiting the location." }, { "code": null, "e": 46828, "s": 46708, "text": "Restrictions Placed on Store Operations − Restrictions on working hours, noise intensity during media promotion events." }, { "code": null, "e": 46948, "s": 46828, "text": "Restrictions Placed on Store Operations − Restrictions on working hours, noise intensity during media promotion events." }, { "code": null, "e": 47043, "s": 46948, "text": "Location Convenience − Proximity to residential areas, proximity to public transport facility." }, { "code": null, "e": 47138, "s": 47043, "text": "Location Convenience − Proximity to residential areas, proximity to public transport facility." }, { "code": null, "e": 47221, "s": 47138, "text": "A retail company needs to follow the given steps for choosing the right location −" }, { "code": null, "e": 47547, "s": 47221, "text": "Step 1 - Analyze the market in terms of industry, product, and competitors − How old is the company in this business? How many similar businesses are there in this location? What the new location is supposed to provide: new products or new market? How far is the competitor’s location from the company’s prospective location?" }, { "code": null, "e": 47698, "s": 47547, "text": "Step 2 – Understand the Demographics − Literacy of customers in the prospective location, age groups, profession, income groups, lifestyles, religion." }, { "code": null, "e": 47905, "s": 47698, "text": "Step 3 – Evaluate the Market Potential − Density of population in the prospective location, anticipation of competition impact, estimation of product demand, knowledge of laws and regulations in operations." }, { "code": null, "e": 48088, "s": 47905, "text": "Step 4 - Identify Alternative Locations − Is there any other potential location? What is its cost of occupancy? Which factors can be compromised if there is a better location around?" }, { "code": null, "e": 48165, "s": 48088, "text": "Step 5 – Finalize the best and most suitable Location for the retail outlet." }, { "code": null, "e": 48389, "s": 48165, "text": "Once the retail outlet is opened at the selected location, it is important to keep track of how feasible was the choice of the location. To understand this, the retail company carries out two types of location assessments −" }, { "code": null, "e": 48553, "s": 48389, "text": "It is conducted at a national level when the company wants to start a retail business internationally. Under this assessment, the following steps are carried out −" }, { "code": null, "e": 48687, "s": 48553, "text": "Detailed external audit of the market by analyzing locations as macro environment such as political, social, economic, and technical." }, { "code": null, "e": 48821, "s": 48687, "text": "Detailed external audit of the market by analyzing locations as macro environment such as political, social, economic, and technical." }, { "code": null, "e": 49069, "s": 48821, "text": "Most important factors are listed such as customer’s level of spending, degree of competition, Personal Disposable Income (PDI), availability of locations, etc., and minimum acceptable level for each factor is defined and the countries are ranked." }, { "code": null, "e": 49317, "s": 49069, "text": "Most important factors are listed such as customer’s level of spending, degree of competition, Personal Disposable Income (PDI), availability of locations, etc., and minimum acceptable level for each factor is defined and the countries are ranked." }, { "code": null, "e": 49439, "s": 49317, "text": "The same factors listed above are considered for local regions within the selected countries to find a reliable location." }, { "code": null, "e": 49561, "s": 49439, "text": "The same factors listed above are considered for local regions within the selected countries to find a reliable location." }, { "code": null, "e": 49645, "s": 49561, "text": "At this level of evaluation, the location is assessed against four factors namely −" }, { "code": null, "e": 49712, "s": 49645, "text": "Population − Desirable number of suitable customers who will shop." }, { "code": null, "e": 49779, "s": 49712, "text": "Population − Desirable number of suitable customers who will shop." }, { "code": null, "e": 49868, "s": 49779, "text": "Infrastructure − The degree to which the store is accessible to the potential customers." }, { "code": null, "e": 49957, "s": 49868, "text": "Infrastructure − The degree to which the store is accessible to the potential customers." }, { "code": null, "e": 50149, "s": 49957, "text": "Store Outlet − Identifying the level of competing stores (those which the decrease attractiveness of a location) as well as complementary stores (which increase attractiveness of a location)." }, { "code": null, "e": 50341, "s": 50149, "text": "Store Outlet − Identifying the level of competing stores (those which the decrease attractiveness of a location) as well as complementary stores (which increase attractiveness of a location)." }, { "code": null, "e": 50458, "s": 50341, "text": "Cost − Costs of development and operation. High startup and ongoing costs affect the performance of retail business." }, { "code": null, "e": 50575, "s": 50458, "text": "Cost − Costs of development and operation. High startup and ongoing costs affect the performance of retail business." }, { "code": null, "e": 50655, "s": 50575, "text": "Advertising moves people toward goods; merchandising moves goods toward people." }, { "code": null, "e": 50699, "s": 50655, "text": "− Morris Hite (American Advertising Expert)" }, { "code": null, "e": 50928, "s": 50699, "text": "In the fierce competition of retail, it is very crucial to attract new customers and to keep the existing customers happy by offering them excellent service. Merchandising helps in achieving far more than just sales can achieve." }, { "code": null, "e": 51095, "s": 50928, "text": "Merchandising is critical for a retail business. The retail managers must employ their skills and tools to streamline the merchandising process as smooth as possible." }, { "code": null, "e": 51336, "s": 51095, "text": "Merchandising is the sequence of various activities performed by the retailer such as planning, buying, and selling of products to the customers for their use. It is an integral part of handling store operations and e-commerce of retailing." }, { "code": null, "e": 51439, "s": 51336, "text": "Merchandising presents the products in retail environment to influence the customer’s buying decision." }, { "code": null, "e": 51482, "s": 51439, "text": "There are two basic types of merchandise −" }, { "code": null, "e": 51536, "s": 51482, "text": "The following factors influence retail merchandising:" }, { "code": null, "e": 51880, "s": 51536, "text": "This includes issues such as how large is the retail business? What is the demographic scope of business: local, national, or international? What is the scope of operations: direct, online with multilingual option, television, telephonic? How large is the storage space? What is the daily number of customers the business is required to serve?" }, { "code": null, "e": 52120, "s": 51880, "text": "Today’s customers have various shopping channels such as in-store, via electronic media such as Internet, television, or telephone, catalogue reference, to name a few. Every option demands different sets of merchandising tasks and experts." }, { "code": null, "e": 52376, "s": 52120, "text": "Depending on the size of retail business, there are workforces for handling each stage of merchandising from planning, buying, and selling the product or service. The small retailers might employ a couple of persons to execute all duties of merchandising." }, { "code": null, "e": 52430, "s": 52376, "text": "A merchandising manager is typically responsible to −" }, { "code": null, "e": 52459, "s": 52430, "text": "Lead the merchandising team." }, { "code": null, "e": 52514, "s": 52459, "text": "Ensure the merchandising process is smooth and timely." }, { "code": null, "e": 52557, "s": 52514, "text": "Coordinate and communicate with suppliers." }, { "code": null, "e": 52616, "s": 52557, "text": "Participate in budgeting, setting and meeting sales goals." }, { "code": null, "e": 52649, "s": 52616, "text": "Train the employees in the team." }, { "code": null, "e": 52806, "s": 52649, "text": "Merchandise planning is a strategic process in order to increase profits. This includes long-term planning of setting sales goals, margin goals, and stocks." }, { "code": null, "e": 53029, "s": 52806, "text": "Step 1 - Define merchandise policy. Get a bird’s eye view of existing and potential customers, retail store image, merchandise quality and customer service levels, marketing approach, and finally desired sales and profits." }, { "code": null, "e": 53164, "s": 53029, "text": "Step 2 – Collect historical information. Gather data about any carry-forward inventory, total merchandise purchases and sales figures." }, { "code": null, "e": 53206, "s": 53164, "text": "Step 3 – Identify Components of Planning." }, { "code": null, "e": 53277, "s": 53206, "text": "Customers − Loyal customers, their buying behavior and spending power." }, { "code": null, "e": 53348, "s": 53277, "text": "Customers − Loyal customers, their buying behavior and spending power." }, { "code": null, "e": 53431, "s": 53348, "text": "Departments − What departments are there in the retail business, their subclasses?" }, { "code": null, "e": 53514, "s": 53431, "text": "Departments − What departments are there in the retail business, their subclasses?" }, { "code": null, "e": 53633, "s": 53514, "text": "Vendors − Who delivered the right product on time? Who gave discounts? Vendor’s overall performance with the business." }, { "code": null, "e": 53752, "s": 53633, "text": "Vendors − Who delivered the right product on time? Who gave discounts? Vendor’s overall performance with the business." }, { "code": null, "e": 53938, "s": 53752, "text": "Current Trends − Finding trend information from sources including trade publications, merchandise suppliers, competition, other stores located in foreign lands, and from own experience." }, { "code": null, "e": 54124, "s": 53938, "text": "Current Trends − Finding trend information from sources including trade publications, merchandise suppliers, competition, other stores located in foreign lands, and from own experience." }, { "code": null, "e": 54256, "s": 54124, "text": "Advertising − Pairing buying and advertising activities together, idea about last successful promotions, budget allocation for Ads." }, { "code": null, "e": 54388, "s": 54256, "text": "Advertising − Pairing buying and advertising activities together, idea about last successful promotions, budget allocation for Ads." }, { "code": null, "e": 54530, "s": 54388, "text": "Step 4 – Create a long-term plan. Analyze historical information, predict forecast of sales, and create a long-term plan, say for six months." }, { "code": null, "e": 54569, "s": 54530, "text": "This activity includes the following −" }, { "code": null, "e": 54837, "s": 54569, "text": "Step 1 - Collect Information − Gather information on consumer demand, current trends, and market requirements. It can be received internally from employees, feedback/complaint boxes, demand slips, or externally by vendors, suppliers, competitors, or via the Internet." }, { "code": null, "e": 55105, "s": 54837, "text": "Step 1 - Collect Information − Gather information on consumer demand, current trends, and market requirements. It can be received internally from employees, feedback/complaint boxes, demand slips, or externally by vendors, suppliers, competitors, or via the Internet." }, { "code": null, "e": 55373, "s": 55105, "text": "Step 2 - Determine Merchandise Sources − Know who all can satisfy the demand: vendors, suppliers, and producers. Compare them on the basis of prices, timeliness, guarantee/warranty offerings, payment terms, and performance and selecting the best feasible resource(s)." }, { "code": null, "e": 55641, "s": 55373, "text": "Step 2 - Determine Merchandise Sources − Know who all can satisfy the demand: vendors, suppliers, and producers. Compare them on the basis of prices, timeliness, guarantee/warranty offerings, payment terms, and performance and selecting the best feasible resource(s)." }, { "code": null, "e": 55783, "s": 55641, "text": "Step 3 - Evaluate the Merchandise Items − By going through sample products, or the complete lot of products, assess the products for quality." }, { "code": null, "e": 55925, "s": 55783, "text": "Step 3 - Evaluate the Merchandise Items − By going through sample products, or the complete lot of products, assess the products for quality." }, { "code": null, "e": 56030, "s": 55925, "text": "Step 4 - Negotiate the Prices − Realize a good deal of purchase by negotiating prices for bulk purchase." }, { "code": null, "e": 56135, "s": 56030, "text": "Step 4 - Negotiate the Prices − Realize a good deal of purchase by negotiating prices for bulk purchase." }, { "code": null, "e": 56258, "s": 56135, "text": "Step 5 - Finalize the Purchase − Finalizing the product prices and buying the merchandise by executing buying transaction." }, { "code": null, "e": 56381, "s": 56258, "text": "Step 5 - Finalize the Purchase − Finalizing the product prices and buying the merchandise by executing buying transaction." }, { "code": null, "e": 56580, "s": 56381, "text": "Step 6 - Handle and Store the Merchandise − Deciding on how the vendor will deliver the products, examining product packing, acquiring the product, and stocking a part of products in the storehouse." }, { "code": null, "e": 56779, "s": 56580, "text": "Step 6 - Handle and Store the Merchandise − Deciding on how the vendor will deliver the products, examining product packing, acquiring the product, and stocking a part of products in the storehouse." }, { "code": null, "e": 57020, "s": 56779, "text": "Step 7 - Record the Buying Figures − Recording details of transactions, number of unit pieces of products according to product categories and sub-classes, and respective unit prices in the inventory management system of the retail business." }, { "code": null, "e": 57261, "s": 57020, "text": "Step 7 - Record the Buying Figures − Recording details of transactions, number of unit pieces of products according to product categories and sub-classes, and respective unit prices in the inventory management system of the retail business." }, { "code": null, "e": 57381, "s": 57261, "text": "Cordial relationship with the vendor can be a great asset for the business. A strong rapport with vendors can lead to −" }, { "code": null, "e": 57477, "s": 57381, "text": "Purchasing products when required and paying the vendor for it later according to credit terms." }, { "code": null, "e": 57573, "s": 57477, "text": "Purchasing products when required and paying the vendor for it later according to credit terms." }, { "code": null, "e": 57679, "s": 57573, "text": "Getting the latest new products in the market at discount prices or before other retailers can sell them." }, { "code": null, "e": 57785, "s": 57679, "text": "Getting the latest new products in the market at discount prices or before other retailers can sell them." }, { "code": null, "e": 57891, "s": 57785, "text": "Having a great service of delivery, timeliness of delivery, returning faulty products with exchange, etc." }, { "code": null, "e": 57997, "s": 57891, "text": "Having a great service of delivery, timeliness of delivery, returning faulty products with exchange, etc." }, { "code": null, "e": 58079, "s": 57997, "text": "The following methods are commonly practiced to analyze merchandise performance −" }, { "code": null, "e": 58190, "s": 58079, "text": "It is a process of inventory classification in which the total inventory is classified into three categories −" }, { "code": null, "e": 58353, "s": 58190, "text": "A – Extremely Important Items − Very crucial inventory control on order scheduling, safety, prompt inspection, consumption pattern, stock balance, refill demands." }, { "code": null, "e": 58516, "s": 58353, "text": "A – Extremely Important Items − Very crucial inventory control on order scheduling, safety, prompt inspection, consumption pattern, stock balance, refill demands." }, { "code": null, "e": 58584, "s": 58516, "text": "B – Moderately Important Items − Average attention is paid to them." }, { "code": null, "e": 58652, "s": 58584, "text": "B – Moderately Important Items − Average attention is paid to them." }, { "code": null, "e": 58724, "s": 58652, "text": "C – Less important Items − Inventory control is completely stress free." }, { "code": null, "e": 58796, "s": 58724, "text": "C – Less important Items − Inventory control is completely stress free." }, { "code": null, "e": 59085, "s": 58796, "text": "This approach of segregation gives importance to each item in the inventory. For example, the telescope retailing company might be having small market share but each telescope is an expensive item in its inventory. This way, a company can decide its investment policy in particular items." }, { "code": null, "e": 59302, "s": 59085, "text": "In this method, the actual sales and forecast sales are compared and the difference is analyzed to determine whether to apply markdown or to place a fresh request for additional merchandise to satisfy current demand." }, { "code": null, "e": 59377, "s": 59302, "text": "This method is very helpful in evaluating fashion merchandise performance." }, { "code": null, "e": 59643, "s": 59377, "text": "This method is based on the concept that the customers consider a retailer or a product as a set of features and attributes. It is used to analyze various alternatives available with regard to vendors and select the best one, which satisfies the store requirements." }, { "code": null, "e": 59717, "s": 59643, "text": "Customers remember the service a lot longer than they remember the price." }, { "code": null, "e": 59764, "s": 59717, "text": "− Lauren Freedman (President, E-tailing Group)" }, { "code": null, "e": 60143, "s": 59764, "text": "The retail business operations include all the activities that the employers perform to keep the store functioning smoothly. The shopping experience of a customer is planned before the customer enters, shops, and leaves the store with a smile or with agony by carrying a perception about the store. This experience drives the customer’s decision of visiting the store in future." }, { "code": null, "e": 60273, "s": 60143, "text": "Let us see, what efforts retail business operations executives put in to make the shopping experience memorable for the customer." }, { "code": null, "e": 60395, "s": 60273, "text": "The retail store being the fundamental source of revenue and the place of customer\ninteraction, is vital to the retailer." }, { "code": null, "e": 60484, "s": 60395, "text": "The store manager may not himself perform, but is responsible for the following duties −" }, { "code": null, "e": 60522, "s": 60484, "text": "Maintaining cleanliness in the store." }, { "code": null, "e": 60560, "s": 60522, "text": "Maintaining cleanliness in the store." }, { "code": null, "e": 60613, "s": 60560, "text": "Ensuring adequate stock of merchandise in the store." }, { "code": null, "e": 60666, "s": 60613, "text": "Ensuring adequate stock of merchandise in the store." }, { "code": null, "e": 60784, "s": 60666, "text": "Appropriate planning, scheduling, and organization of staff, inventory and expenses, for short and long-term success." }, { "code": null, "e": 60902, "s": 60784, "text": "Appropriate planning, scheduling, and organization of staff, inventory and expenses, for short and long-term success." }, { "code": null, "e": 61012, "s": 60902, "text": "Monitoring the loss and taking preventive measures to protect the company’s assets and products in the store." }, { "code": null, "e": 61122, "s": 61012, "text": "Monitoring the loss and taking preventive measures to protect the company’s assets and products in the store." }, { "code": null, "e": 61172, "s": 61122, "text": "Upgrading store to reflect high profitable image." }, { "code": null, "e": 61222, "s": 61172, "text": "Upgrading store to reflect high profitable image." }, { "code": null, "e": 61284, "s": 61222, "text": "Communicating with head office/regional office when required." }, { "code": null, "e": 61346, "s": 61284, "text": "Communicating with head office/regional office when required." }, { "code": null, "e": 61459, "s": 61346, "text": "Conducting constructive meetings with staff to boost their morale and motivate the staff to achieve sales goals." }, { "code": null, "e": 61572, "s": 61459, "text": "Conducting constructive meetings with staff to boost their morale and motivate the staff to achieve sales goals." }, { "code": null, "e": 61654, "s": 61572, "text": "Communicating with customers to identify their needs, grievances, and complaints." }, { "code": null, "e": 61736, "s": 61654, "text": "Communicating with customers to identify their needs, grievances, and complaints." }, { "code": null, "e": 61864, "s": 61736, "text": "Ensuring that the store is in compliance with employment laws regarding salary, work hours, and equal employment opportunities." }, { "code": null, "e": 61992, "s": 61864, "text": "Ensuring that the store is in compliance with employment laws regarding salary, work hours, and equal employment opportunities." }, { "code": null, "e": 62044, "s": 61992, "text": "Writing performance appraisals for assisting staff." }, { "code": null, "e": 62096, "s": 62044, "text": "Writing performance appraisals for assisting staff." }, { "code": null, "e": 62202, "s": 62096, "text": "The store manager ensures that these duties are performed according to the guidelines\nset by the company." }, { "code": null, "e": 62315, "s": 62202, "text": "The store premises are as important as the retail store itself. Managing premises includes the following tasks −" }, { "code": null, "e": 62435, "s": 62315, "text": "Determining Working Hours of Store. It majorly depends upon the target audience, retailed products, and store location." }, { "code": null, "e": 62674, "s": 62435, "text": "For example, a grocery store near residential area should open earlier than a fashion store. Also, a solitary store can be open as long as the owner wants to but a store in a mall has to adhere to working hours set by the mall management." }, { "code": null, "e": 63079, "s": 62674, "text": "Managing Store Security. It helps avoiding inventory shrinkage. It depends upon the size of store, the product, and the location of store. Some retailers attach electronic tags on products, which are sensed at store entrance and exits by sensors for theft detection. Some stores install video cameras to monitor movement and some provide separate entry and exit for personnel so that they can be checked." }, { "code": null, "e": 63193, "s": 63079, "text": "For example, a large departmental store needs high security than the grocery store located near residential area." }, { "code": null, "e": 63253, "s": 63193, "text": "Here are some basic formulae used while managing premises −" }, { "code": null, "e": 63313, "s": 63253, "text": "Transaction per Hour = No. of Transactions/Number of Hours\n" }, { "code": null, "e": 63439, "s": 63313, "text": "The retailer keeps track of the number of transactions per hour, which helps in determining store hours and staff scheduling." }, { "code": null, "e": 63498, "s": 63439, "text": "Sales per Transaction = Net Sales/Number of Transactions \n" }, { "code": null, "e": 63609, "s": 63498, "text": "The result gives the value of the average sales and net return, which is used to study sales trends over time." }, { "code": null, "e": 63672, "s": 63609, "text": "Hourly Customer Traffic = Customer Traffic In/Number of Hours\n" }, { "code": null, "e": 63817, "s": 63672, "text": "This measure is used to track total number of customer traffic per unit time. It is then applied to schedule hours and determine staff strength." }, { "code": null, "e": 63928, "s": 63817, "text": "Merchandise manager, category manager, and other staff handle the inventory. It includes the following tasks −" }, { "code": null, "e": 63964, "s": 63928, "text": "Receiving products from the vendor." }, { "code": null, "e": 64000, "s": 63964, "text": "Receiving products from the vendor." }, { "code": null, "e": 64040, "s": 64000, "text": "Recording inward entry of the products." }, { "code": null, "e": 64080, "s": 64040, "text": "Recording inward entry of the products." }, { "code": null, "e": 64269, "s": 64080, "text": "Checking the products against quality norms laid by the retail company and for details such as colors, sizes, and styles. In case of large stores, this task is automated to a large extent." }, { "code": null, "e": 64458, "s": 64269, "text": "Checking the products against quality norms laid by the retail company and for details such as colors, sizes, and styles. In case of large stores, this task is automated to a large extent." }, { "code": null, "e": 64531, "s": 64458, "text": "Separating and documenting the faulty or damaged products for returning." }, { "code": null, "e": 64604, "s": 64531, "text": "Separating and documenting the faulty or damaged products for returning." }, { "code": null, "e": 64929, "s": 64604, "text": "Displaying the products appropriately to gain customers’ attention. Heavy products are kept at the lower level. Most accessed products are kept at the eye-level and the less accessed products are kept at high level of shelves. On-the-fly-purchased products such as chocolates, candies, etc. are placed near payment counters." }, { "code": null, "e": 65254, "s": 64929, "text": "Displaying the products appropriately to gain customers’ attention. Heavy products are kept at the lower level. Most accessed products are kept at the eye-level and the less accessed products are kept at high level of shelves. On-the-fly-purchased products such as chocolates, candies, etc. are placed near payment counters." }, { "code": null, "e": 65306, "s": 65254, "text": "Here are some formulae used for inventory control −" }, { "code": null, "e": 65377, "s": 65306, "text": "Inventory Turnover Rate = Net Sales/Average Retail Value of Inventory\n" }, { "code": null, "e": 65502, "s": 65377, "text": "It is expressed in number of times and indicates how often the inventory is sold and replaced during a given period of time." }, { "code": null, "e": 65557, "s": 65502, "text": "Cost of Goods Sold/Average Value of Inventory at Cost\n" }, { "code": null, "e": 65646, "s": 65557, "text": "When either of these ratio declines, there is a possibility that inventory is excessive." }, { "code": null, "e": 65718, "s": 65646, "text": "% Inventory Carrying Cost = (Inventory Carrying Cost/Net Sales) * 100 \n" }, { "code": null, "e": 65867, "s": 65718, "text": "This measure has gained importance due to rise in inventory carrying cost because of high interest rates. This prevents blockage of working capital." }, { "code": null, "e": 65951, "s": 65867, "text": "Gross Margin Return on Inventory (GMROI) = Gross Margin/Average Value of Inventory\n" }, { "code": null, "e": 66077, "s": 65951, "text": "The GMROI compares the margin on sales on the original cost value of merchandise to\nyield a return on merchandise investment." }, { "code": null, "e": 66238, "s": 66077, "text": "Managing receipt is nothing but determining the manner in which the retailer is going to get the payment for the sold products. The basic modes of receipt are −" }, { "code": null, "e": 66243, "s": 66238, "text": "Cash" }, { "code": null, "e": 66255, "s": 66243, "text": "Credit card" }, { "code": null, "e": 66266, "s": 66255, "text": "Debit card" }, { "code": null, "e": 66276, "s": 66266, "text": "Gift card" }, { "code": null, "e": 66515, "s": 66276, "text": "Large stores have the facility of paying by the modes listed above but small retailers generally prefer accepting cash. The retailer pays card fees depending upon the volume of transactions with the suppliers, manufacturers, or producers." }, { "code": null, "e": 66673, "s": 66515, "text": "The staff responsible for accepting payment needs to clearly understand the procedure for accepting payment by cards and collecting the amount from the bank." }, { "code": null, "e": 66942, "s": 66673, "text": "Supply Chain Management (SCM) is the management of materials, information, and finances while they move from manufacturer to wholesaler to retailer to consumer. It involves the activities of coordinating and integrating these flows within and out of a retail business." }, { "code": null, "e": 67303, "s": 66942, "text": "Most supply chains operate in collaboration if the suppliers and retail businesses are dealing with each other for a long time. Retailers depend upon supply chain members to a great extent. If the retailers develop a strong partnership with supply chain members, it can be beneficial for suppliers to create seamless procedures, which are difficult to imitate." }, { "code": null, "e": 67604, "s": 67303, "text": "The top management of a retail business decides the customer service policy. The entire\nretail store staff is trained for customer service. Each employer in the retail store ensures that the service starts with smile and the interacting customer is comfortable and has a pleasant shopping experience." }, { "code": null, "e": 67891, "s": 67604, "text": "The promptness and politeness of the retail store staff, their knowledge about the product and language, ability to overcome challenges, and rapidness at the billing counter; everything is noted by the customer. These aspects build a great deal of customer’s perception about the store." }, { "code": null, "e": 68128, "s": 67891, "text": "Many retail stores train staff members to handle the cash counter. They have also introduced a concept of express billing where customers buying less than 10 products can bill faster without having to stand in the regular payment queue." }, { "code": null, "e": 68200, "s": 68128, "text": "During festivals and markdown periods, the trend of shopping increases." }, { "code": null, "e": 68277, "s": 68200, "text": "Customer Conversion Ratio = (Number of Transactions/Customer Traffic) * 100\n" }, { "code": null, "e": 68534, "s": 68277, "text": "The result is the retailer’s ability to turn a potential customer into a buyer. It is also called “walk to buy ratio”. Low results mean that promotional activities are not being converted into sales and the overall sales efforts need to be assessed afresh." }, { "code": null, "e": 68860, "s": 68534, "text": "Space management is one of the crucial challenges faced by today’s retail managers. A well-organized shopping place increases productivity of inventory, enhances customers’ shopping experience, reduces operating costs, and increases financial performance of the retail store. It also elevates the chances of customer loyalty." }, { "code": null, "e": 68935, "s": 68860, "text": "Let us see, how space management is important and how retailers manage it." }, { "code": null, "e": 69115, "s": 68935, "text": "It is the process of managing the floor space adequately to facilitate the customers and to increase the sale. Since store space is a limited resource, it needs to be used wisely." }, { "code": null, "e": 69263, "s": 69115, "text": "Space management is very crucial in retail as the sales volume and gross profitability depends on the amount of space used to generate those sales." }, { "code": null, "e": 69364, "s": 69263, "text": "While allocating the space to various products, the managers need to consider the\nfollowing points −" }, { "code": null, "e": 69811, "s": 69364, "text": "Product Category −\n\nProfit builders − High profit margins-low sales products. Allocate quality space rather than quantity.\nStar performers − Products exceeding sales and profit margins. Allocate large amount of quality space.\nSpace wasters − Low sales-low profit margins products. Put them at the top or bottom of shelves.\nTraffic builders − High sales-low profit margins products. These products need to be displayed close to impulse products.\n\n" }, { "code": null, "e": 69830, "s": 69811, "text": "Product Category −" }, { "code": null, "e": 69933, "s": 69830, "text": "Profit builders − High profit margins-low sales products. Allocate quality space rather than quantity." }, { "code": null, "e": 70036, "s": 69933, "text": "Profit builders − High profit margins-low sales products. Allocate quality space rather than quantity." }, { "code": null, "e": 70139, "s": 70036, "text": "Star performers − Products exceeding sales and profit margins. Allocate large amount of quality space." }, { "code": null, "e": 70242, "s": 70139, "text": "Star performers − Products exceeding sales and profit margins. Allocate large amount of quality space." }, { "code": null, "e": 70339, "s": 70242, "text": "Space wasters − Low sales-low profit margins products. Put them at the top or bottom of shelves." }, { "code": null, "e": 70436, "s": 70339, "text": "Space wasters − Low sales-low profit margins products. Put them at the top or bottom of shelves." }, { "code": null, "e": 70558, "s": 70436, "text": "Traffic builders − High sales-low profit margins products. These products need to be displayed close to impulse products." }, { "code": null, "e": 70680, "s": 70558, "text": "Traffic builders − High sales-low profit margins products. These products need to be displayed close to impulse products." }, { "code": null, "e": 70720, "s": 70680, "text": "Size, shape, and weight of the product." }, { "code": null, "e": 70760, "s": 70720, "text": "Size, shape, and weight of the product." }, { "code": null, "e": 70830, "s": 70760, "text": "Product adjacencies − It means which products can coexist on display?" }, { "code": null, "e": 70900, "s": 70830, "text": "Product adjacencies − It means which products can coexist on display?" }, { "code": null, "e": 70927, "s": 70900, "text": "Product life on the shelf." }, { "code": null, "e": 70954, "s": 70927, "text": "Product life on the shelf." }, { "code": null, "e": 71036, "s": 70954, "text": "Here are the steps to take into consideration for using floor space effectively −" }, { "code": null, "e": 71079, "s": 71036, "text": "Measure the total area of space available." }, { "code": null, "e": 71122, "s": 71079, "text": "Measure the total area of space available." }, { "code": null, "e": 71306, "s": 71122, "text": "Divide this area into selling and non-selling areas such as aisle, storage, promotional displays, customer support cell, (trial rooms in case of clothing retail) and billing counters." }, { "code": null, "e": 71490, "s": 71306, "text": "Divide this area into selling and non-selling areas such as aisle, storage, promotional displays, customer support cell, (trial rooms in case of clothing retail) and billing counters." }, { "code": null, "e": 71655, "s": 71490, "text": "Create a Planogram, a pictorial diagram that depicts how and where to place specific retail products on shelves or displays in order to increase customer purchases." }, { "code": null, "e": 71820, "s": 71655, "text": "Create a Planogram, a pictorial diagram that depicts how and where to place specific retail products on shelves or displays in order to increase customer purchases." }, { "code": null, "e": 72203, "s": 71820, "text": "Allocate the selling space to each product category. Determine the amount of space for a particular category by considering historical and forecasted sales data. Determine the space for billing counter by referring historical customer volume data. In case of clothing retail, allocate a separate space for trial rooms that is near the product display but away from the billing area." }, { "code": null, "e": 72586, "s": 72203, "text": "Allocate the selling space to each product category. Determine the amount of space for a particular category by considering historical and forecasted sales data. Determine the space for billing counter by referring historical customer volume data. In case of clothing retail, allocate a separate space for trial rooms that is near the product display but away from the billing area." }, { "code": null, "e": 72717, "s": 72586, "text": "Determine the location of the product categories within the space. This helps the customers to locate the required product easily." }, { "code": null, "e": 72848, "s": 72717, "text": "Determine the location of the product categories within the space. This helps the customers to locate the required product easily." }, { "code": null, "e": 73000, "s": 72848, "text": "Decide product adjacencies logically. This facilitates multiple product purchase. For example, pasta sauces and spices are kept near raw pasta packets." }, { "code": null, "e": 73152, "s": 73000, "text": "Decide product adjacencies logically. This facilitates multiple product purchase. For example, pasta sauces and spices are kept near raw pasta packets." }, { "code": null, "e": 73293, "s": 73152, "text": "Make use of irregular shaped corner space wisely. Some products such as domestic cleaning devices or garden furniture can stand in a corner." }, { "code": null, "e": 73434, "s": 73293, "text": "Make use of irregular shaped corner space wisely. Some products such as domestic cleaning devices or garden furniture can stand in a corner." }, { "code": null, "e": 73590, "s": 73434, "text": "Allocate space for promotional displays and schemes facing towards road to notify\nand attract the customers. Use glass walls or doors wisely for promotion." }, { "code": null, "e": 73746, "s": 73590, "text": "Allocate space for promotional displays and schemes facing towards road to notify\nand attract the customers. Use glass walls or doors wisely for promotion." }, { "code": null, "e": 73888, "s": 73746, "text": "Customer buying behavior is an important point of consideration while designing store\nlayout. The objectives of store layout and design are −" }, { "code": null, "e": 73917, "s": 73888, "text": "It should attract customers." }, { "code": null, "e": 73983, "s": 73917, "text": "It should help the customers to locate the products effortlessly." }, { "code": null, "e": 74044, "s": 73983, "text": "It should help the customers spend longer time in the store." }, { "code": null, "e": 74113, "s": 74044, "text": "It should motivate customers to make unplanned, impulsive purchases." }, { "code": null, "e": 74165, "s": 74113, "text": "It should influence the customers’ buying behavior." }, { "code": null, "e": 74300, "s": 74165, "text": "The retail store layouts are designed in way to use the space efficiently. There are broadly three popular layouts for retail stores −" }, { "code": null, "e": 74345, "s": 74300, "text": "Grid Layout − Mainly used in grocery stores." }, { "code": null, "e": 74398, "s": 74345, "text": "Loop Layout − Used in malls and departmental stores." }, { "code": null, "e": 74464, "s": 74398, "text": "Free Layout − Followed mainly in luxury retail or fashion stores." }, { "code": null, "e": 74537, "s": 74464, "text": "Both internal and external factors matter when it comes to store design." }, { "code": null, "e": 74722, "s": 74537, "text": "The store interior is the area where customers actually look for products and make purchases. It directly contributes to influence customer decision making. In includes the following −" }, { "code": null, "e": 74792, "s": 74722, "text": "Clear and adequate walking space, separate from product display area." }, { "code": null, "e": 74862, "s": 74792, "text": "Clear and adequate walking space, separate from product display area." }, { "code": null, "e": 74998, "s": 74862, "text": "Free standing displays: Fixtures, rotary displays, or mannequins installed to attract customers’ attention and bring them to the store." }, { "code": null, "e": 75134, "s": 74998, "text": "Free standing displays: Fixtures, rotary displays, or mannequins installed to attract customers’ attention and bring them to the store." }, { "code": null, "e": 75227, "s": 75134, "text": "End caps: These displays at the end of the aisles can be used to display promotional offers." }, { "code": null, "e": 75320, "s": 75227, "text": "End caps: These displays at the end of the aisles can be used to display promotional offers." }, { "code": null, "e": 75393, "s": 75320, "text": "Windows and doors can provide visual messages about merchandise on sale." }, { "code": null, "e": 75466, "s": 75393, "text": "Windows and doors can provide visual messages about merchandise on sale." }, { "code": null, "e": 75561, "s": 75466, "text": "Proper lighting at the product display. For example, jewelry retail needs more acute lighting." }, { "code": null, "e": 75656, "s": 75561, "text": "Proper lighting at the product display. For example, jewelry retail needs more acute lighting." }, { "code": null, "e": 75900, "s": 75656, "text": "Relevant signage with readable typefaces and limited text for product categories, for promotional schemes, and at Point of Sale (POS) that guides customers’ decision-making process. It can also include hanging signage for enhancing visibility." }, { "code": null, "e": 76144, "s": 75900, "text": "Relevant signage with readable typefaces and limited text for product categories, for promotional schemes, and at Point of Sale (POS) that guides customers’ decision-making process. It can also include hanging signage for enhancing visibility." }, { "code": null, "e": 76212, "s": 76144, "text": "Sitting area for a few differently abled people or senior citizens." }, { "code": null, "e": 76280, "s": 76212, "text": "Sitting area for a few differently abled people or senior citizens." }, { "code": null, "e": 76464, "s": 76280, "text": "This area outside the store is as much important as the interior of the store. It communicates with the customer on who the retailer is and what it stands for. The exterior includes −" }, { "code": null, "e": 76623, "s": 76464, "text": "Name of the store, which tells the world that it exists. It can be a plain painted board or as fancy as an aesthetically designed digital board of the outlet." }, { "code": null, "e": 76782, "s": 76623, "text": "Name of the store, which tells the world that it exists. It can be a plain painted board or as fancy as an aesthetically designed digital board of the outlet." }, { "code": null, "e": 76871, "s": 76782, "text": "The store entrance: Standard or automatic, glass, wood, or metal? Width of the entrance." }, { "code": null, "e": 76960, "s": 76871, "text": "The store entrance: Standard or automatic, glass, wood, or metal? Width of the entrance." }, { "code": null, "e": 77006, "s": 76960, "text": "The cleanliness of the area around the store." }, { "code": null, "e": 77052, "s": 77006, "text": "The cleanliness of the area around the store." }, { "code": null, "e": 77112, "s": 77052, "text": "The aesthetics used to draw the customers inside the store." }, { "code": null, "e": 77172, "s": 77112, "text": "The aesthetics used to draw the customers inside the store." }, { "code": null, "e": 77248, "s": 77172, "text": "The bitterness of poor quality remains a long after low price is forgotten." }, { "code": null, "e": 77267, "s": 77248, "text": "− Leon M. Cautillo" }, { "code": null, "e": 77544, "s": 77267, "text": "We as customers, often get to read advertisements from various retailers saying, “Quality product for right price!” This leads to following questions such as what is the right price and who sets it? What are the factors and strategies that determine the price for what we buy?" }, { "code": null, "e": 77729, "s": 77544, "text": "The core capability of the retailers lies in pricing the products or services in a right manner to keep the customers happy, recover investment for production, and to generate revenue." }, { "code": null, "e": 77964, "s": 77729, "text": "The price at which the product is sold to the end customer is called the retail price of the product. Retail price is the summation of the manufacturing cost and all the costs that retailers incur at the time of charging the customer." }, { "code": null, "e": 78025, "s": 77964, "text": "Retail prices are affected by internal and external factors." }, { "code": null, "e": 78095, "s": 78025, "text": "Internal factors that influence retail prices include the following −" }, { "code": null, "e": 78425, "s": 78095, "text": "Manufacturing Cost − The retail company considers both, fixed and variable costs of manufacturing the product. The fixed costs does not vary depending upon the production volume. For example, property tax. The variable costs include varying costs of raw material and costs depending upon volume of production. For example, labor." }, { "code": null, "e": 78755, "s": 78425, "text": "Manufacturing Cost − The retail company considers both, fixed and variable costs of manufacturing the product. The fixed costs does not vary depending upon the production volume. For example, property tax. The variable costs include varying costs of raw material and costs depending upon volume of production. For example, labor." }, { "code": null, "e": 79040, "s": 78755, "text": "The Predetermined Objectives − The objective of the retail company varies with time and market situations. If the objective is to increase return on investment, then the company may charge a higher price. If the objective is to increase market share, then it may charge a lower price." }, { "code": null, "e": 79325, "s": 79040, "text": "The Predetermined Objectives − The objective of the retail company varies with time and market situations. If the objective is to increase return on investment, then the company may charge a higher price. If the objective is to increase market share, then it may charge a lower price." }, { "code": null, "e": 79520, "s": 79325, "text": "Image of the Firm − The retail company may consider its own image in the market. For example, companies with large goodwill such as Procter & Gamble can demand a higher price for their products." }, { "code": null, "e": 79715, "s": 79520, "text": "Image of the Firm − The retail company may consider its own image in the market. For example, companies with large goodwill such as Procter & Gamble can demand a higher price for their products." }, { "code": null, "e": 80029, "s": 79715, "text": "Product Status − The stage at which the product is in its product life cycle determines its price. At the time of introducing the product in the market, the company may charge lower price for it to attract new customers. When the product is accepted and established in the market, the company increases the price." }, { "code": null, "e": 80343, "s": 80029, "text": "Product Status − The stage at which the product is in its product life cycle determines its price. At the time of introducing the product in the market, the company may charge lower price for it to attract new customers. When the product is accepted and established in the market, the company increases the price." }, { "code": null, "e": 80517, "s": 80343, "text": "Promotional Activity − If the company is spending high cost on advertising and sales promotion, then it keeps product price high in order to recover the cost of investments." }, { "code": null, "e": 80691, "s": 80517, "text": "Promotional Activity − If the company is spending high cost on advertising and sales promotion, then it keeps product price high in order to recover the cost of investments." }, { "code": null, "e": 80760, "s": 80691, "text": "External prices that influence retail prices include the following −" }, { "code": null, "e": 80929, "s": 80760, "text": "Competition − In case of high competition, the prices may be set low to face the competition effectively, and if there is less competition, the prices may be kept high." }, { "code": null, "e": 81098, "s": 80929, "text": "Competition − In case of high competition, the prices may be set low to face the competition effectively, and if there is less competition, the prices may be kept high." }, { "code": null, "e": 81248, "s": 81098, "text": "Buying Power of Consumers − The sensitivity of the customer towards price variation and purchasing power of the customer contribute to setting price." }, { "code": null, "e": 81398, "s": 81248, "text": "Buying Power of Consumers − The sensitivity of the customer towards price variation and purchasing power of the customer contribute to setting price." }, { "code": null, "e": 81547, "s": 81398, "text": "Government Policies − Government rules and regulation about manufacturing and announcement of administered prices can increase the price of product." }, { "code": null, "e": 81696, "s": 81547, "text": "Government Policies − Government rules and regulation about manufacturing and announcement of administered prices can increase the price of product." }, { "code": null, "e": 81850, "s": 81696, "text": "Market Conditions − If market is under recession, the consumers buying pattern changes. To modify their buying behavior, the product prices are set less." }, { "code": null, "e": 82004, "s": 81850, "text": "Market Conditions − If market is under recession, the consumers buying pattern changes. To modify their buying behavior, the product prices are set less." }, { "code": null, "e": 82218, "s": 82004, "text": "Levels of Channels Involved − The retailer has to consider number of channels involved from manufacturing to retail and their expectations. The deeper the level of channels, the higher would be the product prices." }, { "code": null, "e": 82432, "s": 82218, "text": "Levels of Channels Involved − The retailer has to consider number of channels involved from manufacturing to retail and their expectations. The deeper the level of channels, the higher would be the product prices." }, { "code": null, "e": 82604, "s": 82432, "text": "The price charged is high if there is high demand for the product and low if the demand is low. The methods employed while pricing the product on the basis of demand are −" }, { "code": null, "e": 82749, "s": 82604, "text": "Price Skimming − Initially the product is charged at a high price that the customer is willing to pay and then it decreases gradually with time." }, { "code": null, "e": 82894, "s": 82749, "text": "Price Skimming − Initially the product is charged at a high price that the customer is willing to pay and then it decreases gradually with time." }, { "code": null, "e": 82985, "s": 82894, "text": "Odd Even Pricing − The customers perceive prices like 99.99, 11.49 to be cheaper than 100." }, { "code": null, "e": 83076, "s": 82985, "text": "Odd Even Pricing − The customers perceive prices like 99.99, 11.49 to be cheaper than 100." }, { "code": null, "e": 83190, "s": 83076, "text": "Penetration Pricing − Price is reduced to compete with other similar products to allow more customer penetration." }, { "code": null, "e": 83304, "s": 83190, "text": "Penetration Pricing − Price is reduced to compete with other similar products to allow more customer penetration." }, { "code": null, "e": 83373, "s": 83304, "text": "Prestige Pricing − Pricing is done to convey quality of the product." }, { "code": null, "e": 83442, "s": 83373, "text": "Prestige Pricing − Pricing is done to convey quality of the product." }, { "code": null, "e": 83566, "s": 83442, "text": "Price Bundling − The offer of additional product or service is combined with the main product, together with special price." }, { "code": null, "e": 83690, "s": 83566, "text": "Price Bundling − The offer of additional product or service is combined with the main product, together with special price." }, { "code": null, "e": 83842, "s": 83690, "text": "A method of determining prices that takes a retail company’s profit objectives and production costs into account. These methods include the following −" }, { "code": null, "e": 84068, "s": 83842, "text": "Cost plus Pricing − The company sets prices little above the manufacturing cost. For example, if the cost of a product is Rs. 600 per unit and the marketer expects 10 per cent profit, then the selling price is set to Rs. 660." }, { "code": null, "e": 84194, "s": 84068, "text": "Mark-up Pricing − The mark-ups are calculated as a percentage of the selling price and not as a percentage of the cost price." }, { "code": null, "e": 84247, "s": 84194, "text": "The formula used to determine the selling price is −" }, { "code": null, "e": 84296, "s": 84247, "text": "Selling Price = Average unit cost/Selling price\n" }, { "code": null, "e": 84480, "s": 84296, "text": "Break-even Pricing − The retail company determines the level of sales needed to cover all the relevant fixed and variable costs. They break-even when there is neither profit nor loss." }, { "code": null, "e": 84582, "s": 84480, "text": "For example, Fixed cost = Rs. 2, 00,000, Variable cost per unit = Rs. 15, and Selling price = Rs. 20." }, { "code": null, "e": 84831, "s": 84582, "text": "In this case, the company needs to sell (2,00, 000 / (20-15)) = 40,000 units to break even the fixed cost. Hence, the company may plan to sell at least 40,000 units to be profitable. If it is not possible, then it has to increase the selling price." }, { "code": null, "e": 84897, "s": 84831, "text": "The following formula is used to calculate the break-even point −" }, { "code": null, "e": 84952, "s": 84897, "text": "Contribution = Selling price – Variable cost per unit\n" }, { "code": null, "e": 85068, "s": 84952, "text": "Target Return Pricing − The retail company sets prices in order to achieve a particular Return On Investment (ROI)." }, { "code": null, "e": 85121, "s": 85068, "text": "This can be calculated using the following formula −" }, { "code": null, "e": 85206, "s": 85121, "text": "Target return price = Total costs + (Desired % ROI investment)/Total sales in units\n" }, { "code": null, "e": 85250, "s": 85206, "text": "For example, Total investment = Rs. 10,000," }, { "code": null, "e": 85277, "s": 85250, "text": "Desired ROI = 20 per cent," }, { "code": null, "e": 85303, "s": 85277, "text": "Total cost = Rs.5000, and" }, { "code": null, "e": 85338, "s": 85303, "text": "Total expected sales = 1,000 units" }, { "code": null, "e": 85407, "s": 85338, "text": "Then the target return price will be Rs. 7 per unit as shown below −" }, { "code": null, "e": 85467, "s": 85407, "text": "Target Return Price = (5000 + (20% * 10,000))/ 1000 = Rs. 7" }, { "code": null, "e": 85547, "s": 85467, "text": "This method ensures that the price exceeds all costs and contributes to profit." }, { "code": null, "e": 85916, "s": 85547, "text": "Early Cash Recovery Pricing − When market forecasts depict short life, it is essential for the price sensitive product segments such as fashion and technology to recover the investment. Sometimes the company anticipates the entry of a larger company in the market. In these cases, the companies price their products to shorten the risks and maximize short-term profit." }, { "code": null, "e": 86078, "s": 85916, "text": "When a retail company sets the prices for its product depending on how much the competitor is charging for a similar product, it is competition-oriented pricing." }, { "code": null, "e": 86185, "s": 86078, "text": "Competitor’s Parity − The retail company may set the price as close as the giant competitor in the market." }, { "code": null, "e": 86292, "s": 86185, "text": "Competitor’s Parity − The retail company may set the price as close as the giant competitor in the market." }, { "code": null, "e": 86404, "s": 86292, "text": "Discount Pricing − A product is priced at low cost if it is lacking some feature than the competitor’s product." }, { "code": null, "e": 86516, "s": 86404, "text": "Discount Pricing − A product is priced at low cost if it is lacking some feature than the competitor’s product." }, { "code": null, "e": 86589, "s": 86516, "text": "The company may charge different prices for the same product or service." }, { "code": null, "e": 86827, "s": 86589, "text": "Customer Segment Pricing − The price is charged differently for customers from different customer segments. For example, customers who purchase online may be charged less as the cost of service is low for the segment of online customers." }, { "code": null, "e": 87065, "s": 86827, "text": "Customer Segment Pricing − The price is charged differently for customers from different customer segments. For example, customers who purchase online may be charged less as the cost of service is low for the segment of online customers." }, { "code": null, "e": 87249, "s": 87065, "text": "Time Pricing − The retailer charges price depending upon time, season, occasions, etc. For example, many resorts charge more for their vacation packages depending on the time of year." }, { "code": null, "e": 87433, "s": 87249, "text": "Time Pricing − The retailer charges price depending upon time, season, occasions, etc. For example, many resorts charge more for their vacation packages depending on the time of year." }, { "code": null, "e": 87619, "s": 87433, "text": "Location Pricing − The retailer charges the price depending on where the customer is located. For example, front-row seats of a drama theater are charged high price than rear-row seats." }, { "code": null, "e": 87805, "s": 87619, "text": "Location Pricing − The retailer charges the price depending on where the customer is located. For example, front-row seats of a drama theater are charged high price than rear-row seats." }, { "code": null, "e": 87947, "s": 87805, "text": "Retail marketing is the range of activities the retailer does to create awareness about the products or services among customers for selling." }, { "code": null, "e": 88125, "s": 87947, "text": "Retail marketing consists of visual merchandising, sales promotion, advertising, and marketing mix. All these factors are involved in shaping the marketing strategies of retail." }, { "code": null, "e": 88333, "s": 88125, "text": "It is the activity of developing floor plans and three-dimensional displays in order to engage customers and boost sales. Both, products or services can be displayed to highlight their features and benefits." }, { "code": null, "e": 88716, "s": 88333, "text": "It is based on the idea that good looks pay off. It requires creativity and an eye for presenting the products or services aesthetically so that the customers find it appealing and are motivated towards buying. Visual merchandising involves displaying products or services aesthetically using various objects, colors, shapes, materials, designs, and styles to attract the customers." }, { "code": null, "e": 89146, "s": 88716, "text": "It is advertising the product or service on communication media. The retailer can advertise on electronic media such as television, radio, mobile, and Internet. Print media such as newspaper, brochures, handbills, product catalogues, are also popular among retailers to publish Ads. Retail advertising enables the retailer to reach out to a large number of people and create awareness among them about the product’s availability." }, { "code": null, "e": 89263, "s": 89146, "text": "The success of an Ad on a particular media depends upon the literacy level of the customers, their age and location." }, { "code": null, "e": 89526, "s": 89263, "text": "Sales promotion is the communication strategy designed to act directly as an inducement, as added value, or as incentive for the product to the customer. Advertising may create desire to possess the product but sales promotion actually helps conversion to sales." }, { "code": null, "e": 89701, "s": 89526, "text": "Sales promotion drives existing customers’ loyalty, attracts new customers, influences customers’ buying behavior, and increases sales. It includes the following techniques −" }, { "code": null, "e": 89804, "s": 89701, "text": "They are Ads placed near the merchandise to promote the sale where the customer makes buying decision." }, { "code": null, "e": 89937, "s": 89804, "text": "They are Ads placed near the checkout or billing counters to promote on-the-fly purchase that the customer makes at the last minute." }, { "code": null, "e": 90244, "s": 89937, "text": "Some techniques such as Loss Leading (where irrespective of how luxurious the product is, retailer offers steep discount), Markdown (where retailer brings down the prices for wide range of products in the store), and Bundle Pricing (Buy one get one free or Get 3 pay for 1) are used in promotional pricing." }, { "code": null, "e": 90427, "s": 90244, "text": "Retailers conduct loyalty program for the customers who make frequent purchase by offering first access to new products, free coupons, or special discounted price on particular days." }, { "code": null, "e": 90566, "s": 90427, "text": "It is identification, satisfaction, and management of customers’ stated and unstated needs and demands by the retailer for mutual benefit." }, { "code": null, "e": 90601, "s": 90566, "text": "It include four prominent phases −" }, { "code": null, "e": 90738, "s": 90601, "text": "Develop and Customize − Develop products or services to meet customers’ requirements. Customize the same according to customer segments." }, { "code": null, "e": 90875, "s": 90738, "text": "Develop and Customize − Develop products or services to meet customers’ requirements. Customize the same according to customer segments." }, { "code": null, "e": 91007, "s": 90875, "text": "Interact and Deliver − Communicate with existing and prospective customers and deliver the product or service with the added value." }, { "code": null, "e": 91139, "s": 91007, "text": "Interact and Deliver − Communicate with existing and prospective customers and deliver the product or service with the added value." }, { "code": null, "e": 91209, "s": 91139, "text": "Acquire and Retain − Acquire new customers and retain the loyal ones." }, { "code": null, "e": 91279, "s": 91209, "text": "Acquire and Retain − Acquire new customers and retain the loyal ones." }, { "code": null, "e": 91423, "s": 91279, "text": "Understand and Differentiate − Understand customers’ needs, differentiate policies and products depending on customer behavior and preferences." }, { "code": null, "e": 91567, "s": 91423, "text": "Understand and Differentiate − Understand customers’ needs, differentiate policies and products depending on customer behavior and preferences." }, { "code": null, "e": 91779, "s": 91567, "text": "The retail marketing mix is the combination of marketing activities that the retailers carry out to meet the target market’s requirements in the best possible way. Retail marketing mix is a combination of 7 Ps −" }, { "code": null, "e": 91850, "s": 91779, "text": "Product − The quality and range of variants of the product or service." }, { "code": null, "e": 91921, "s": 91850, "text": "Product − The quality and range of variants of the product or service." }, { "code": null, "e": 92092, "s": 91921, "text": "Place − It is the location where the product or service is sold: online, type of store, location of store, time taken and the mode of transport to reach the retail place." }, { "code": null, "e": 92263, "s": 92092, "text": "Place − It is the location where the product or service is sold: online, type of store, location of store, time taken and the mode of transport to reach the retail place." }, { "code": null, "e": 92378, "s": 92263, "text": "Price − Cost of product or service for different customer segments by considering various price affecting factors." }, { "code": null, "e": 92493, "s": 92378, "text": "Price − Cost of product or service for different customer segments by considering various price affecting factors." }, { "code": null, "e": 92639, "s": 92493, "text": "Promotion − It is raising customers’ awareness about the product or service and driving customers to buy the products by offering tempting deals." }, { "code": null, "e": 92785, "s": 92639, "text": "Promotion − It is raising customers’ awareness about the product or service and driving customers to buy the products by offering tempting deals." }, { "code": null, "e": 92959, "s": 92785, "text": "People − This includes internal stakeholders such as customers, sales staff, management staff, and external stakeholders such as suppliers and supply chain management force." }, { "code": null, "e": 93133, "s": 92959, "text": "People − This includes internal stakeholders such as customers, sales staff, management staff, and external stakeholders such as suppliers and supply chain management force." }, { "code": null, "e": 93254, "s": 93133, "text": "Process − It is the range of activities involved in manufacturing and delivering the product or service to the customer." }, { "code": null, "e": 93375, "s": 93254, "text": "Process − It is the range of activities involved in manufacturing and delivering the product or service to the customer." }, { "code": null, "e": 93571, "s": 93375, "text": "Physical Environment − Presenting the products or offering services in a wellorganized and attractive manner, keeping an aesthetic sense in presentation to elevate customers’ shopping experience." }, { "code": null, "e": 93767, "s": 93571, "text": "Physical Environment − Presenting the products or offering services in a wellorganized and attractive manner, keeping an aesthetic sense in presentation to elevate customers’ shopping experience." }, { "code": null, "e": 94010, "s": 93767, "text": "Retailers communicate with the customers about their products or services, new product updates, and upcoming events regarding retail business via print, audio, video, or Internet media. Retail communication involves the following strategies −" }, { "code": null, "e": 94102, "s": 94010, "text": "Providing retail information based on stored data about celebration dates of the\ncustomers." }, { "code": null, "e": 94194, "s": 94102, "text": "Providing retail information based on stored data about celebration dates of the\ncustomers." }, { "code": null, "e": 94257, "s": 94194, "text": "Holding contests to gain new customers and keep existing ones." }, { "code": null, "e": 94320, "s": 94257, "text": "Holding contests to gain new customers and keep existing ones." }, { "code": null, "e": 94389, "s": 94320, "text": "Posting retail information on social websites to increase followers." }, { "code": null, "e": 94458, "s": 94389, "text": "Posting retail information on social websites to increase followers." }, { "code": null, "e": 94573, "s": 94458, "text": "Sending coupons on mobile so that customers can avail the benefits of the schemes right when they enter the store." }, { "code": null, "e": 94688, "s": 94573, "text": "Sending coupons on mobile so that customers can avail the benefits of the schemes right when they enter the store." }, { "code": null, "e": 94764, "s": 94688, "text": "Conducting customer surveys and reviews. Rewarding participating customers." }, { "code": null, "e": 94840, "s": 94764, "text": "Conducting customer surveys and reviews. Rewarding participating customers." }, { "code": null, "e": 94878, "s": 94840, "text": "Using automated retail communication." }, { "code": null, "e": 94916, "s": 94878, "text": "Using automated retail communication." }, { "code": null, "e": 95038, "s": 94916, "text": "Retail is a pretty simple business, but what adds complexity is the size and scale. We couldn’t do it without technology." }, { "code": null, "e": 95076, "s": 95038, "text": "− Bob Nardelli (American businessman)" }, { "code": null, "e": 95449, "s": 95076, "text": "In today’s era, the places in the cities have become congested, infrastructure has changed, transport facilities have increased, and the speed of exchanging information has become extremely fast. Retailers are adopting new technology. Society is changing, consumers are changing and so are the retailers. Retailing has managed to keep itself paced with the changing times." }, { "code": null, "e": 95591, "s": 95449, "text": "Retailers are changing their business formats, store designs, modes of communication\nwith customers and ways of handling commercial dealings." }, { "code": null, "e": 95697, "s": 95591, "text": "Modern retailers are adapting new technology for marketing, retail operations, and business transactions." }, { "code": null, "e": 95803, "s": 95697, "text": "Modern retailers are adapting new technology for marketing, retail operations, and business transactions." }, { "code": null, "e": 95888, "s": 95803, "text": "Forward-thinking retailers are using social media to communicate with the consumers." }, { "code": null, "e": 95973, "s": 95888, "text": "Forward-thinking retailers are using social media to communicate with the consumers." }, { "code": null, "e": 96076, "s": 95973, "text": "With the space crunch, modern retailers have learnt how to use every inch of the floor constructively." }, { "code": null, "e": 96179, "s": 96076, "text": "With the space crunch, modern retailers have learnt how to use every inch of the floor constructively." }, { "code": null, "e": 96340, "s": 96179, "text": "Apart from opening online retail store, the retailers take the help of Augmented Reality such as 3D mock-ups to let the customer try the products on themselves." }, { "code": null, "e": 96501, "s": 96340, "text": "Apart from opening online retail store, the retailers take the help of Augmented Reality such as 3D mock-ups to let the customer try the products on themselves." }, { "code": null, "e": 96606, "s": 96501, "text": "Retailers are working progressively on delivery of orders that customers placed\nthrough online shopping." }, { "code": null, "e": 96711, "s": 96606, "text": "Retailers are working progressively on delivery of orders that customers placed\nthrough online shopping." }, { "code": null, "e": 96919, "s": 96711, "text": "Retailers are bringing something new now and then to charm the customers. Those places where internet is still not accessible, retailers are exploiting the power of mobile phones to advertise their products." }, { "code": null, "e": 97127, "s": 96919, "text": "Retailers are bringing something new now and then to charm the customers. Those places where internet is still not accessible, retailers are exploiting the power of mobile phones to advertise their products." }, { "code": null, "e": 97238, "s": 97127, "text": "Today, the Internet has changed the way products are advertised and the manner of selling-buying transactions." }, { "code": null, "e": 97283, "s": 97238, "text": "Here are some modern innovations in retail −" }, { "code": null, "e": 97496, "s": 97283, "text": "Modern retail businesses such as malls, specialty stores, and hypermarkets are using micro development and contemporary technology to increase customers’ shopping experience and in turn generate business revenue." }, { "code": null, "e": 97709, "s": 97496, "text": "Modern retail businesses such as malls, specialty stores, and hypermarkets are using micro development and contemporary technology to increase customers’ shopping experience and in turn generate business revenue." }, { "code": null, "e": 97819, "s": 97709, "text": "Around the year 2000, online retail startups started changing the face of retail\nbusinesses around the world." }, { "code": null, "e": 97929, "s": 97819, "text": "Around the year 2000, online retail startups started changing the face of retail\nbusinesses around the world." }, { "code": null, "e": 98077, "s": 97929, "text": "Social media websites such as Facebook changed consumer behavior as well as made retailers sweat out to take the benefits and develop their brands." }, { "code": null, "e": 98225, "s": 98077, "text": "Social media websites such as Facebook changed consumer behavior as well as made retailers sweat out to take the benefits and develop their brands." }, { "code": null, "e": 98336, "s": 98225, "text": "Modern e-commerce facilities enable faster transactions and allow purchase on a simple 30-day credit facility." }, { "code": null, "e": 98447, "s": 98336, "text": "Modern e-commerce facilities enable faster transactions and allow purchase on a simple 30-day credit facility." }, { "code": null, "e": 98774, "s": 98447, "text": "It is nothing but E-Retailing. It is the process of selling or purchasing the products using Internet for B2B or B2C transactions. E-tailing process includes the customer’s visit to the website, purchasing products by choosing a mode of payment, product delivery by the retailer and finally, the customer’s review or feedback." }, { "code": null, "e": 98827, "s": 98774, "text": "It does not require floor space to display products." }, { "code": null, "e": 98880, "s": 98827, "text": "It does not require floor space to display products." }, { "code": null, "e": 98954, "s": 98880, "text": "It allows the customer having internet access to shop any time, any place" }, { "code": null, "e": 99028, "s": 98954, "text": "It allows the customer having internet access to shop any time, any place" }, { "code": null, "e": 99124, "s": 99028, "text": "It saves time of the customer otherwise spent travelling to a shopping place in the\nreal world." }, { "code": null, "e": 99220, "s": 99124, "text": "It saves time of the customer otherwise spent travelling to a shopping place in the\nreal world." }, { "code": null, "e": 99348, "s": 99220, "text": "It creates a platform for products from around the world, which are imported by the e-tailer when the customer places an order." }, { "code": null, "e": 99476, "s": 99348, "text": "It creates a platform for products from around the world, which are imported by the e-tailer when the customer places an order." }, { "code": null, "e": 99511, "s": 99476, "text": "\n 20 Lectures \n 3.5 hours \n" }, { "code": null, "e": 99529, "s": 99511, "text": " Richa Maheshwari" }, { "code": null, "e": 99564, "s": 99529, "text": "\n 44 Lectures \n 5.5 hours \n" }, { "code": null, "e": 99579, "s": 99564, "text": " Navdeep Yadav" }, { "code": null, "e": 99586, "s": 99579, "text": " Print" }, { "code": null, "e": 99597, "s": 99586, "text": " Add Notes" } ]
How to check Minlength and Maxlength validation of a property in C# using Fluent Validation?
Ensures that the length of a particular string property is no longer than the specified value. Only valid on string properties String format args: {PropertyName} = The name of the property being validated {MaxLength} = Maximum length {TotalLength} = Number of characters entered {PropertyValue} = The current value of the property Ensures that the length of a particular string property is longer than the specified value. Only valid on string properties {PropertyName} = The name of the property being validated {MinLength} = Minimum length {TotalLength} = Number of characters entered {PropertyValue} = The current value of the property static void Main(string[] args){ List errors = new List(); PersonModel person = new PersonModel(); person.FirstName = "TestUser444"; person.LastName = "TTT"; PersonValidator validator = new PersonValidator(); ValidationResult results = validator.Validate(person); if (results.IsValid == false){ foreach (ValidationFailure failure in results.Errors){ errors.Add(failure.ErrorMessage); } } foreach (var item in errors){ Console.WriteLine(item); } Console.ReadLine(); } } public class PersonModel{ public string FirstName { get; set; } public string LastName { get; set; } } public class PersonValidator : AbstractValidator{ public PersonValidator(){ RuleFor(p => p.FirstName).MaximumLength(7).WithMessage("MaximumLength must be 7 {PropertyName}") ; RuleFor(p => p.LastName).MinimumLength(5).WithMessage("MinimumLength must be 5 {PropertyName}"); } } MaximumLength must be 7 First Name MinimumLength must be 5 Last Name
[ { "code": null, "e": 1157, "s": 1062, "text": "Ensures that the length of a particular string property is no longer than the specified value." }, { "code": null, "e": 1189, "s": 1157, "text": "Only valid on string properties" }, { "code": null, "e": 1209, "s": 1189, "text": "String format args:" }, { "code": null, "e": 1267, "s": 1209, "text": "{PropertyName} = The name of the property being validated" }, { "code": null, "e": 1296, "s": 1267, "text": "{MaxLength} = Maximum length" }, { "code": null, "e": 1341, "s": 1296, "text": "{TotalLength} = Number of characters entered" }, { "code": null, "e": 1393, "s": 1341, "text": "{PropertyValue} = The current value of the property" }, { "code": null, "e": 1485, "s": 1393, "text": "Ensures that the length of a particular string property is longer than the specified value." }, { "code": null, "e": 1517, "s": 1485, "text": "Only valid on string properties" }, { "code": null, "e": 1575, "s": 1517, "text": "{PropertyName} = The name of the property being validated" }, { "code": null, "e": 1604, "s": 1575, "text": "{MinLength} = Minimum length" }, { "code": null, "e": 1649, "s": 1604, "text": "{TotalLength} = Number of characters entered" }, { "code": null, "e": 1701, "s": 1649, "text": "{PropertyValue} = The current value of the property" }, { "code": null, "e": 2640, "s": 1701, "text": "static void Main(string[] args){\n List errors = new List();\n\n PersonModel person = new PersonModel();\n person.FirstName = \"TestUser444\";\n person.LastName = \"TTT\";\n\n PersonValidator validator = new PersonValidator();\n ValidationResult results = validator.Validate(person);\n\n if (results.IsValid == false){\n foreach (ValidationFailure failure in results.Errors){\n errors.Add(failure.ErrorMessage);\n }\n }\n\n foreach (var item in errors){\n Console.WriteLine(item);\n }\n Console.ReadLine();\n }\n}\npublic class PersonModel{\n public string FirstName { get; set; }\n public string LastName { get; set; }\n}\npublic class PersonValidator : AbstractValidator{\n public PersonValidator(){\n RuleFor(p => p.FirstName).MaximumLength(7).WithMessage(\"MaximumLength must be 7 {PropertyName}\") ;\n RuleFor(p => p.LastName).MinimumLength(5).WithMessage(\"MinimumLength must be 5 {PropertyName}\");\n }\n}" }, { "code": null, "e": 2709, "s": 2640, "text": "MaximumLength must be 7 First Name\nMinimumLength must be 5 Last Name" } ]
Solving real-world problem using data science | by Naman Doshi | Towards Data Science
The world of data science is evolving every day. Every professional in this field needs to be updated and constantly learning, or risk being left behind. You must have an appetite to solve problems. So I decided to study and solve a real-world problem which most of us have faced in our professional careers. The technical round in an interview! How many times have you gone through a technical interview where you feel you’re acing it, and then a question comes that leaves you stumped? And from there the entire interview goes downhill because now you have lost confidence and the recruiter has lost interest. But is it fair to judge the technical capabilities of a candidate based entirely on a 3-hour interview? This is a loss at both the ends because now the company has lost a potential candidate and the candidate has lost an opportunity. If only there was a way through which the recruiter can get the gist about the technical capabilities of the candidate outside the interview hall. A scoring system of sorts — that would give an ideal score to gauge the technical knowledge of the candidate, and thereby help the recruiter to make an informed, unbiased decision. Sounds like a dream scenario, right? So I decided to start a project called “Scorey” that aims to crack this challenge. Scorey helps in scraping, aggregating, and assessing the technical ability of a candidate based on publicly available sources. The current interview scenario is biased towards “candidate’s performance during the 3-hour interview” and doesn’t take other factors into account, such as the candidate’s competitive coding abilities, contribution towards the developer community, and so on. Scorey tries to solve this problem by aggregating publicly available data from various websites, such as: Github StackOverflow CodeChef Codebuddy Codeforces Hackerearth SPOJ GitAwards Once the data is collected, the algorithm then defines a comprehensive scoring system that grades the candidates technical capabilities based on the following factors: Ranking Number of Problems Solved Activity Reputation Contribution Followers The candidate is then assigned a scored out of 100. This helps the interviewer get a full view of a candidate’s abilities and hence make an unbiased, informed decision. For the entire scope of this project, we are going to use Python, a Jupyter notebook & scraping libraries. So if you’re someone who likes Notebooks, then this section is for you. If not, feel free to skip this and move on to the next section. def color_negative_red(val): """ Takes a scalar and returns a string with the css property `'color: red'` for negative strings, black otherwise. """ color = 'red' if val > 0 else 'black' return 'color: %s' % color( Set CSS properties for th elements in dataframe)th_props = [ ('font-size', '15px'), ('text-align', 'center'), ('font-weight', 'bold'), ('color', '#00c936'), ('background-color', '##f7f7f7') ]# Set CSS properties for td elements in dataframetd_props = [ ('font-size', '15px'), ('font-weight', 'bold') ]# Set table stylesstyles = [ dict(selector="th", props=th_props), dict(selector="td", props=td_props) ] This will make your dataframe output look neat, tidy, and really good! Now that we have a gist of what we are aiming to solve and how we are going to go about it, let’s code! We need to aggregate the entire “coding presence of a person on the internet”. But where do we start? Duh! His/Her personal website. This is of course assuming we have access and permission to the candidate’s personal website. We can parse all the necessary links from there. from bs4 import BeautifulSoupimport urllibimport urllib.parseimport urllib.requestfrom urllib.request import urlopenurl = input('Enter your personal website - ')html = urlopen(url).read()soup = BeautifulSoup(html, "lxml")tags = soup('a')for tag in tags: print (tag.get('href',None)) When we run this piece of code, we get the below output: Here we are using BeautifulSoup which is a popular scraping library. Using this block of code, we have direct links to a candidate’s online profile. Now where will you begin if you had to assess a coder at a much more granular level? Github Github So first, let us use Github API to get all the info we need of a particular user. For our use case, we only need email, number of repositories, followers, hireable (true or false), current company and last recorded activity. 2. StackOverflow Ah. Devs might not believe in God but StackOverflow is definitely a temple for them. As you may already know, it is very difficult to get a reputation on StackOverflow. For this step, you can use StackExchange’s API — it gives you user data such as reputation, no. of answers, etc. We’ll then add these new attributes to our existing dataframe. Now we are going to target and scrape global competitive programming platforms such as CodeChef, SPOJ, Codebuddy, Hackerearth, CodeForces & GitAwards (for a deeper insight into their projects). All this scraping gave us a LOT of info as you can see. Code is pretty self explanatory. I’ve also documented using comments so that its easy to understand. Without going into the nitty-gritty of the code, I’d like to focus on the process. But you can give me a shout-out if you face any trouble executing the code. :) Now that we have all the data in hand, we will move on to creating a scoring algorithm. The next part is to score the candidates on the following parameters: Rank (25 points) Number of problems solved (25 points) Reputation (25 points) Followers (15 points) Activity (5 points) Contributions (5 points) So if you go through this piece of code, you’d understand how we can create a scoring system. Though its pretty basic at this point, we can use machine learning to create a robust dynamic scoring system. Final Score Based on the point system we saw above, the algorithm will now assign a final score to the candidate’s technical capabilities. So the user poke19962008 has a score of 64 out of 100! Now this will give the recruiters an idea of the technical abilities of the candidate outside the interview room. When you are trying to solve a real world problem and “productivize” the solution, its important to consider the requirements of the end user.In this case, its the recruiter. How can we use power of machine learning to add value to the recruiter? Upon brainstorming, I found the following use cases — 1. Model that predicts whether or not the management will be satisfied by candidate’s skill set2. Model that predicts the probability of a candidate’s churn post hiring3. Using genetic algorithm to link assign the candidate to respective team Let’s try to code the 1st use case — Predicting company’s satisfactionAssuming that the recruiter has been using Scorey to screen candidates for some time and now has a database of 100 candidates.Post recruitment, based on the candidate’s performance, the recruiter updates the database with a new binary attribute “Satisfaction” with values of either 0 or 1.Let’s create a dummy database for now and try to create a model using Scikit-Learn, Pandas, Numpy and build a predictive model. Import data & librariesClean the data — remove duplicates and null valuesUsing label encoder to deal with categorical dataSplit the dataset into train & testUsing kNN classifier to predictCheck Accuracy Import data & libraries Clean the data — remove duplicates and null values Using label encoder to deal with categorical data Split the dataset into train & test Using kNN classifier to predict Check Accuracy Using these steps, you will get a niche model that will be able to predict whether the candidate will fit into the company based on underlying trends.For eg — Candidates who have higher reputation and are contributing to Open source are more likely to retain for a longer period of time. I went ahead and made a dashboard. This its still a work-in-progress and I’ll be happy to share some of the screenshots of the interface. There you have it. Your very own end-to-end product.To summarize — 1. We identified a problem2. Methodical thinking on how we can solve it3. Used Web scraping to gather data4. Build an algorithmic scoring system5. Machine learning to build a predictive model5. Dashboard to communicate results Tech stack that we used — Python: BeautifulSoup, Urllib, Pandas, Sklearn So that’s all for this article. We took a real life problem and tried to use data and algorithms to solve it! Next time you go for an interview, you can pitch this system to the recruiter. :) Code for the entire project can be found on Github — here Integrating Machine learning components for rule generation Handling missing data exceptions dynamically If you think this project is cool and would like to contribute, you are more than welcome! Let’s build something exciting for the community. You can connect with me over LinkedIn or on Twitter to get daily updates on what’s new in data science & machine learning.
[ { "code": null, "e": 518, "s": 172, "text": "The world of data science is evolving every day. Every professional in this field needs to be updated and constantly learning, or risk being left behind. You must have an appetite to solve problems. So I decided to study and solve a real-world problem which most of us have faced in our professional careers. The technical round in an interview!" }, { "code": null, "e": 784, "s": 518, "text": "How many times have you gone through a technical interview where you feel you’re acing it, and then a question comes that leaves you stumped? And from there the entire interview goes downhill because now you have lost confidence and the recruiter has lost interest." }, { "code": null, "e": 1018, "s": 784, "text": "But is it fair to judge the technical capabilities of a candidate based entirely on a 3-hour interview? This is a loss at both the ends because now the company has lost a potential candidate and the candidate has lost an opportunity." }, { "code": null, "e": 1383, "s": 1018, "text": "If only there was a way through which the recruiter can get the gist about the technical capabilities of the candidate outside the interview hall. A scoring system of sorts — that would give an ideal score to gauge the technical knowledge of the candidate, and thereby help the recruiter to make an informed, unbiased decision. Sounds like a dream scenario, right?" }, { "code": null, "e": 1466, "s": 1383, "text": "So I decided to start a project called “Scorey” that aims to crack this challenge." }, { "code": null, "e": 1593, "s": 1466, "text": "Scorey helps in scraping, aggregating, and assessing the technical ability of a candidate based on publicly available sources." }, { "code": null, "e": 1852, "s": 1593, "text": "The current interview scenario is biased towards “candidate’s performance during the 3-hour interview” and doesn’t take other factors into account, such as the candidate’s competitive coding abilities, contribution towards the developer community, and so on." }, { "code": null, "e": 1958, "s": 1852, "text": "Scorey tries to solve this problem by aggregating publicly available data from various websites, such as:" }, { "code": null, "e": 1965, "s": 1958, "text": "Github" }, { "code": null, "e": 1979, "s": 1965, "text": "StackOverflow" }, { "code": null, "e": 1988, "s": 1979, "text": "CodeChef" }, { "code": null, "e": 1998, "s": 1988, "text": "Codebuddy" }, { "code": null, "e": 2009, "s": 1998, "text": "Codeforces" }, { "code": null, "e": 2021, "s": 2009, "text": "Hackerearth" }, { "code": null, "e": 2026, "s": 2021, "text": "SPOJ" }, { "code": null, "e": 2036, "s": 2026, "text": "GitAwards" }, { "code": null, "e": 2204, "s": 2036, "text": "Once the data is collected, the algorithm then defines a comprehensive scoring system that grades the candidates technical capabilities based on the following factors:" }, { "code": null, "e": 2212, "s": 2204, "text": "Ranking" }, { "code": null, "e": 2238, "s": 2212, "text": "Number of Problems Solved" }, { "code": null, "e": 2247, "s": 2238, "text": "Activity" }, { "code": null, "e": 2258, "s": 2247, "text": "Reputation" }, { "code": null, "e": 2271, "s": 2258, "text": "Contribution" }, { "code": null, "e": 2281, "s": 2271, "text": "Followers" }, { "code": null, "e": 2450, "s": 2281, "text": "The candidate is then assigned a scored out of 100. This helps the interviewer get a full view of a candidate’s abilities and hence make an unbiased, informed decision." }, { "code": null, "e": 2693, "s": 2450, "text": "For the entire scope of this project, we are going to use Python, a Jupyter notebook & scraping libraries. So if you’re someone who likes Notebooks, then this section is for you. If not, feel free to skip this and move on to the next section." }, { "code": null, "e": 3348, "s": 2693, "text": "def color_negative_red(val): \"\"\" Takes a scalar and returns a string with the css property `'color: red'` for negative strings, black otherwise. \"\"\" color = 'red' if val > 0 else 'black' return 'color: %s' % color( Set CSS properties for th elements in dataframe)th_props = [ ('font-size', '15px'), ('text-align', 'center'), ('font-weight', 'bold'), ('color', '#00c936'), ('background-color', '##f7f7f7') ]# Set CSS properties for td elements in dataframetd_props = [ ('font-size', '15px'), ('font-weight', 'bold') ]# Set table stylesstyles = [ dict(selector=\"th\", props=th_props), dict(selector=\"td\", props=td_props) ]" }, { "code": null, "e": 3419, "s": 3348, "text": "This will make your dataframe output look neat, tidy, and really good!" }, { "code": null, "e": 3523, "s": 3419, "text": "Now that we have a gist of what we are aiming to solve and how we are going to go about it, let’s code!" }, { "code": null, "e": 3799, "s": 3523, "text": "We need to aggregate the entire “coding presence of a person on the internet”. But where do we start? Duh! His/Her personal website. This is of course assuming we have access and permission to the candidate’s personal website. We can parse all the necessary links from there." }, { "code": null, "e": 4085, "s": 3799, "text": "from bs4 import BeautifulSoupimport urllibimport urllib.parseimport urllib.requestfrom urllib.request import urlopenurl = input('Enter your personal website - ')html = urlopen(url).read()soup = BeautifulSoup(html, \"lxml\")tags = soup('a')for tag in tags: print (tag.get('href',None))" }, { "code": null, "e": 4142, "s": 4085, "text": "When we run this piece of code, we get the below output:" }, { "code": null, "e": 4291, "s": 4142, "text": "Here we are using BeautifulSoup which is a popular scraping library. Using this block of code, we have direct links to a candidate’s online profile." }, { "code": null, "e": 4376, "s": 4291, "text": "Now where will you begin if you had to assess a coder at a much more granular level?" }, { "code": null, "e": 4383, "s": 4376, "text": "Github" }, { "code": null, "e": 4390, "s": 4383, "text": "Github" }, { "code": null, "e": 4472, "s": 4390, "text": "So first, let us use Github API to get all the info we need of a particular user." }, { "code": null, "e": 4615, "s": 4472, "text": "For our use case, we only need email, number of repositories, followers, hireable (true or false), current company and last recorded activity." }, { "code": null, "e": 4632, "s": 4615, "text": "2. StackOverflow" }, { "code": null, "e": 4914, "s": 4632, "text": "Ah. Devs might not believe in God but StackOverflow is definitely a temple for them. As you may already know, it is very difficult to get a reputation on StackOverflow. For this step, you can use StackExchange’s API — it gives you user data such as reputation, no. of answers, etc." }, { "code": null, "e": 4977, "s": 4914, "text": "We’ll then add these new attributes to our existing dataframe." }, { "code": null, "e": 5171, "s": 4977, "text": "Now we are going to target and scrape global competitive programming platforms such as CodeChef, SPOJ, Codebuddy, Hackerearth, CodeForces & GitAwards (for a deeper insight into their projects)." }, { "code": null, "e": 5328, "s": 5171, "text": "All this scraping gave us a LOT of info as you can see. Code is pretty self explanatory. I’ve also documented using comments so that its easy to understand." }, { "code": null, "e": 5578, "s": 5328, "text": "Without going into the nitty-gritty of the code, I’d like to focus on the process. But you can give me a shout-out if you face any trouble executing the code. :) Now that we have all the data in hand, we will move on to creating a scoring algorithm." }, { "code": null, "e": 5648, "s": 5578, "text": "The next part is to score the candidates on the following parameters:" }, { "code": null, "e": 5665, "s": 5648, "text": "Rank (25 points)" }, { "code": null, "e": 5703, "s": 5665, "text": "Number of problems solved (25 points)" }, { "code": null, "e": 5726, "s": 5703, "text": "Reputation (25 points)" }, { "code": null, "e": 5748, "s": 5726, "text": "Followers (15 points)" }, { "code": null, "e": 5768, "s": 5748, "text": "Activity (5 points)" }, { "code": null, "e": 5793, "s": 5768, "text": "Contributions (5 points)" }, { "code": null, "e": 5997, "s": 5793, "text": "So if you go through this piece of code, you’d understand how we can create a scoring system. Though its pretty basic at this point, we can use machine learning to create a robust dynamic scoring system." }, { "code": null, "e": 6009, "s": 5997, "text": "Final Score" }, { "code": null, "e": 6136, "s": 6009, "text": "Based on the point system we saw above, the algorithm will now assign a final score to the candidate’s technical capabilities." }, { "code": null, "e": 6305, "s": 6136, "text": "So the user poke19962008 has a score of 64 out of 100! Now this will give the recruiters an idea of the technical abilities of the candidate outside the interview room." }, { "code": null, "e": 6552, "s": 6305, "text": "When you are trying to solve a real world problem and “productivize” the solution, its important to consider the requirements of the end user.In this case, its the recruiter. How can we use power of machine learning to add value to the recruiter?" }, { "code": null, "e": 6849, "s": 6552, "text": "Upon brainstorming, I found the following use cases — 1. Model that predicts whether or not the management will be satisfied by candidate’s skill set2. Model that predicts the probability of a candidate’s churn post hiring3. Using genetic algorithm to link assign the candidate to respective team" }, { "code": null, "e": 7336, "s": 6849, "text": "Let’s try to code the 1st use case — Predicting company’s satisfactionAssuming that the recruiter has been using Scorey to screen candidates for some time and now has a database of 100 candidates.Post recruitment, based on the candidate’s performance, the recruiter updates the database with a new binary attribute “Satisfaction” with values of either 0 or 1.Let’s create a dummy database for now and try to create a model using Scikit-Learn, Pandas, Numpy and build a predictive model." }, { "code": null, "e": 7539, "s": 7336, "text": "Import data & librariesClean the data — remove duplicates and null valuesUsing label encoder to deal with categorical dataSplit the dataset into train & testUsing kNN classifier to predictCheck Accuracy" }, { "code": null, "e": 7563, "s": 7539, "text": "Import data & libraries" }, { "code": null, "e": 7614, "s": 7563, "text": "Clean the data — remove duplicates and null values" }, { "code": null, "e": 7664, "s": 7614, "text": "Using label encoder to deal with categorical data" }, { "code": null, "e": 7700, "s": 7664, "text": "Split the dataset into train & test" }, { "code": null, "e": 7732, "s": 7700, "text": "Using kNN classifier to predict" }, { "code": null, "e": 7747, "s": 7732, "text": "Check Accuracy" }, { "code": null, "e": 8035, "s": 7747, "text": "Using these steps, you will get a niche model that will be able to predict whether the candidate will fit into the company based on underlying trends.For eg — Candidates who have higher reputation and are contributing to Open source are more likely to retain for a longer period of time." }, { "code": null, "e": 8173, "s": 8035, "text": "I went ahead and made a dashboard. This its still a work-in-progress and I’ll be happy to share some of the screenshots of the interface." }, { "code": null, "e": 8467, "s": 8173, "text": "There you have it. Your very own end-to-end product.To summarize — 1. We identified a problem2. Methodical thinking on how we can solve it3. Used Web scraping to gather data4. Build an algorithmic scoring system5. Machine learning to build a predictive model5. Dashboard to communicate results" }, { "code": null, "e": 8540, "s": 8467, "text": "Tech stack that we used — Python: BeautifulSoup, Urllib, Pandas, Sklearn" }, { "code": null, "e": 8650, "s": 8540, "text": "So that’s all for this article. We took a real life problem and tried to use data and algorithms to solve it!" }, { "code": null, "e": 8732, "s": 8650, "text": "Next time you go for an interview, you can pitch this system to the recruiter. :)" }, { "code": null, "e": 8790, "s": 8732, "text": "Code for the entire project can be found on Github — here" }, { "code": null, "e": 8850, "s": 8790, "text": "Integrating Machine learning components for rule generation" }, { "code": null, "e": 8895, "s": 8850, "text": "Handling missing data exceptions dynamically" }, { "code": null, "e": 9036, "s": 8895, "text": "If you think this project is cool and would like to contribute, you are more than welcome! Let’s build something exciting for the community." } ]
DML Full Form - GeeksforGeeks
12 Jun, 2020 DML stands for Data Manipulation Language. Tables and formulas are helpful when communicating with data stored up to a point in a database through SQL, but a time comes when we actually want to execute some fairly complicated data interactions. We will also need the Data Manipulation Language in that situation. DML is a way to inform a database precisely what we want it to do by conversing in a manner that it has been built to comprehend from the scratch. When it comes to interacting within existing data, whether adding, moving, or deleting data, it provides a convenient way to do so. The Database Management System offers a framework of functions or dialects to modify or alter the data, called the Data Manipulation Language. Data manipulation could be done perhaps by typing SQL queries or by using, a typically called Query-by-Example (QBE) graphical interface. These declarations are used to modify the data found in the tables. These declarations are going to work on results. There is no relation with the structure of the tables for these statements. Data manipulation includes introducing data into tables, altering the table’s data and deleting the data from the table. Transaction control is required for the DML statements. Any modification that a DML statement makes to the database will be called as a transaction. Any adjustment made by DML statement must therefore, be controlled by TCL statements (Transaction Control Language). DML is a subset of SQL statements which alter the information stored in tables. As, it mainly concentrates on database performance, as well as it utilizes HDFS (Hadoop Distributed File System) storage’s append-only nature. Types of Data Manipulation Language: It is also labelled as set-at-a-time or series oriented DML. It is also labelled as track-at-a-time DML. It can be used on its own for precisely specifying complex operations in the database. It must be integrated to a general-purpose programming language. It is prescriptive in nature. It is indispensable in nature. It demands that a user must clearly state which data is needed without clarifying how and when to obtain those data. It demands that a user must clearly state which data is needed and how to obtain those data. For Example: Every SQL statement is a prescriptive command. For Example: DB2’s SQL PL, Oracle’s PL/SQL. Characteristics :It performs interpret-only data queries. It is used in a database schema to recall and manipulate the information. DML It is a dialect which is used to select, insert, delete and update data in a database. Data Manipulation Language (DML) commands are as follows: SELECT Command –This command is used to get data out of the database. It helps users of the database to access from an operating system, the significant data they need. It sends a track result set from one tables or more.Syntax :SELECT * FROM <table_name>; Example :SELECT * FROM students; OR SELECT * FROM students where due_fees <=20000;INSERT Command –This command is used to enter the information or values into a row. We can connect one or more records to a single table within a repository using this instruction. This is often used to connect an unused tag to the documents.Syntax :INSERT INTO <table_name> ('column_name1' <datatype>, 'column_name2' <datatype>) VALUES ('value1', 'value2'); Example :INSERT INTO students ('stu_id' int, 'stu_name' varchar(20), 'city' varchar(20)) VALUES ('1', 'Nirmit', 'Gorakhpur'); UPDATE Command –This command is used to alter existing table records. Within a table, it modifies data from one or more records. This command is used to alter the data which is already present in a table.Syntax :UPDATE <table_name> SET <column_name = value> WHERE condition; Example :UPDATE students SET due_fees = 20000 WHERE stu_name = 'Mini'; DELETE Command –It deletes all archives from a table. This command is used to erase some or all of the previous table’s records. If we do not specify the ‘WHERE’ condition then all the rows would be erased or deleted.Syntax :DELETE FROM <table_name> WHERE <condition>; Example :DELETE FROM students WHERE stu_id = '001'; SELECT Command –This command is used to get data out of the database. It helps users of the database to access from an operating system, the significant data they need. It sends a track result set from one tables or more.Syntax :SELECT * FROM <table_name>; Example :SELECT * FROM students; OR SELECT * FROM students where due_fees <=20000; Syntax : SELECT * FROM <table_name>; Example : SELECT * FROM students; OR SELECT * FROM students where due_fees <=20000; INSERT Command –This command is used to enter the information or values into a row. We can connect one or more records to a single table within a repository using this instruction. This is often used to connect an unused tag to the documents.Syntax :INSERT INTO <table_name> ('column_name1' <datatype>, 'column_name2' <datatype>) VALUES ('value1', 'value2'); Example :INSERT INTO students ('stu_id' int, 'stu_name' varchar(20), 'city' varchar(20)) VALUES ('1', 'Nirmit', 'Gorakhpur'); Syntax : INSERT INTO <table_name> ('column_name1' <datatype>, 'column_name2' <datatype>) VALUES ('value1', 'value2'); Example : INSERT INTO students ('stu_id' int, 'stu_name' varchar(20), 'city' varchar(20)) VALUES ('1', 'Nirmit', 'Gorakhpur'); UPDATE Command –This command is used to alter existing table records. Within a table, it modifies data from one or more records. This command is used to alter the data which is already present in a table.Syntax :UPDATE <table_name> SET <column_name = value> WHERE condition; Example :UPDATE students SET due_fees = 20000 WHERE stu_name = 'Mini'; Syntax : UPDATE <table_name> SET <column_name = value> WHERE condition; Example : UPDATE students SET due_fees = 20000 WHERE stu_name = 'Mini'; DELETE Command –It deletes all archives from a table. This command is used to erase some or all of the previous table’s records. If we do not specify the ‘WHERE’ condition then all the rows would be erased or deleted.Syntax :DELETE FROM <table_name> WHERE <condition>; Example :DELETE FROM students WHERE stu_id = '001'; Syntax : DELETE FROM <table_name> WHERE <condition>; Example : DELETE FROM students WHERE stu_id = '001'; Advantages : DML statements could alter the data that is contained or stored in the database.It delivers effective human contact with the machine.User could specify what data is required.DML aims to have many different varieties and functionalities between vendors providing databases. DML statements could alter the data that is contained or stored in the database. It delivers effective human contact with the machine. User could specify what data is required. DML aims to have many different varieties and functionalities between vendors providing databases. Disadvantages : We cannot use DML to change the structure of the database.Limit table view i.e., it could conceal some columns in tables.Access the data without having the data stored in the object.Unable to build or erase lists or sections using DML. We cannot use DML to change the structure of the database. Limit table view i.e., it could conceal some columns in tables. Access the data without having the data stored in the object. Unable to build or erase lists or sections using DML. Picked DBMS Full Form GATE CS DBMS Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Types of Functional dependencies in DBMS Introduction of Relational Algebra in DBMS Two Phase Locking Protocol What is Temporary Table in SQL? Conflict Serializability in DBMS DBA Full Form HTTP Full Form RDBMS Full Form CDMA Full Form FDDI Full Form
[ { "code": null, "e": 24304, "s": 24276, "text": "\n12 Jun, 2020" }, { "code": null, "e": 24896, "s": 24304, "text": "DML stands for Data Manipulation Language. Tables and formulas are helpful when communicating with data stored up to a point in a database through SQL, but a time comes when we actually want to execute some fairly complicated data interactions. We will also need the Data Manipulation Language in that situation. DML is a way to inform a database precisely what we want it to do by conversing in a manner that it has been built to comprehend from the scratch. When it comes to interacting within existing data, whether adding, moving, or deleting data, it provides a convenient way to do so." }, { "code": null, "e": 25491, "s": 24896, "text": "The Database Management System offers a framework of functions or dialects to modify or alter the data, called the Data Manipulation Language. Data manipulation could be done perhaps by typing SQL queries or by using, a typically called Query-by-Example (QBE) graphical interface. These declarations are used to modify the data found in the tables. These declarations are going to work on results. There is no relation with the structure of the tables for these statements. Data manipulation includes introducing data into tables, altering the table’s data and deleting the data from the table." }, { "code": null, "e": 25980, "s": 25491, "text": "Transaction control is required for the DML statements. Any modification that a DML statement makes to the database will be called as a transaction. Any adjustment made by DML statement must therefore, be controlled by TCL statements (Transaction Control Language). DML is a subset of SQL statements which alter the information stored in tables. As, it mainly concentrates on database performance, as well as it utilizes HDFS (Hadoop Distributed File System) storage’s append-only nature." }, { "code": null, "e": 26017, "s": 25980, "text": "Types of Data Manipulation Language:" }, { "code": null, "e": 26078, "s": 26017, "text": "It is also labelled as set-at-a-time or series oriented DML." }, { "code": null, "e": 26122, "s": 26078, "text": "It is also labelled as track-at-a-time DML." }, { "code": null, "e": 26209, "s": 26122, "text": "It can be used on its own for precisely specifying complex operations in the database." }, { "code": null, "e": 26274, "s": 26209, "text": "It must be integrated to a general-purpose programming language." }, { "code": null, "e": 26304, "s": 26274, "text": "It is prescriptive in nature." }, { "code": null, "e": 26335, "s": 26304, "text": "It is indispensable in nature." }, { "code": null, "e": 26452, "s": 26335, "text": "It demands that a user must clearly state which data is needed without clarifying how and when to obtain those data." }, { "code": null, "e": 26545, "s": 26452, "text": "It demands that a user must clearly state which data is needed and how to obtain those data." }, { "code": null, "e": 26605, "s": 26545, "text": "For Example: Every SQL statement is a prescriptive command." }, { "code": null, "e": 26649, "s": 26605, "text": "For Example: DB2’s SQL PL, Oracle’s PL/SQL." }, { "code": null, "e": 26872, "s": 26649, "text": "Characteristics :It performs interpret-only data queries. It is used in a database schema to recall and manipulate the information. DML It is a dialect which is used to select, insert, delete and update data in a database." }, { "code": null, "e": 26930, "s": 26872, "text": "Data Manipulation Language (DML) commands are as follows:" }, { "code": null, "e": 28435, "s": 26930, "text": "SELECT Command –This command is used to get data out of the database. It helps users of the database to access from an operating system, the significant data they need. It sends a track result set from one tables or more.Syntax :SELECT * \nFROM <table_name>; Example :SELECT * \nFROM students;\n\nOR\n\nSELECT * \nFROM students\nwhere due_fees <=20000;INSERT Command –This command is used to enter the information or values into a row. We can connect one or more records to a single table within a repository using this instruction. This is often used to connect an unused tag to the documents.Syntax :INSERT INTO <table_name> ('column_name1' <datatype>, 'column_name2' <datatype>)\n\nVALUES ('value1', 'value2'); Example :INSERT INTO students ('stu_id' int, 'stu_name' varchar(20), 'city' varchar(20))\n\nVALUES ('1', 'Nirmit', 'Gorakhpur'); UPDATE Command –This command is used to alter existing table records. Within a table, it modifies data from one or more records. This command is used to alter the data which is already present in a table.Syntax :UPDATE <table_name>\n\nSET <column_name = value>\n\nWHERE condition; Example :UPDATE students\n\nSET due_fees = 20000\n\nWHERE stu_name = 'Mini'; DELETE Command –It deletes all archives from a table. This command is used to erase some or all of the previous table’s records. If we do not specify the ‘WHERE’ condition then all the rows would be erased or deleted.Syntax :DELETE FROM <table_name>\n\nWHERE <condition>; Example :DELETE FROM students\n\nWHERE stu_id = '001'; " }, { "code": null, "e": 28780, "s": 28435, "text": "SELECT Command –This command is used to get data out of the database. It helps users of the database to access from an operating system, the significant data they need. It sends a track result set from one tables or more.Syntax :SELECT * \nFROM <table_name>; Example :SELECT * \nFROM students;\n\nOR\n\nSELECT * \nFROM students\nwhere due_fees <=20000;" }, { "code": null, "e": 28789, "s": 28780, "text": "Syntax :" }, { "code": null, "e": 28819, "s": 28789, "text": "SELECT * \nFROM <table_name>; " }, { "code": null, "e": 28829, "s": 28819, "text": "Example :" }, { "code": null, "e": 28907, "s": 28829, "text": "SELECT * \nFROM students;\n\nOR\n\nSELECT * \nFROM students\nwhere due_fees <=20000;" }, { "code": null, "e": 29395, "s": 28907, "text": "INSERT Command –This command is used to enter the information or values into a row. We can connect one or more records to a single table within a repository using this instruction. This is often used to connect an unused tag to the documents.Syntax :INSERT INTO <table_name> ('column_name1' <datatype>, 'column_name2' <datatype>)\n\nVALUES ('value1', 'value2'); Example :INSERT INTO students ('stu_id' int, 'stu_name' varchar(20), 'city' varchar(20))\n\nVALUES ('1', 'Nirmit', 'Gorakhpur'); " }, { "code": null, "e": 29404, "s": 29395, "text": "Syntax :" }, { "code": null, "e": 29515, "s": 29404, "text": "INSERT INTO <table_name> ('column_name1' <datatype>, 'column_name2' <datatype>)\n\nVALUES ('value1', 'value2'); " }, { "code": null, "e": 29525, "s": 29515, "text": "Example :" }, { "code": null, "e": 29644, "s": 29525, "text": "INSERT INTO students ('stu_id' int, 'stu_name' varchar(20), 'city' varchar(20))\n\nVALUES ('1', 'Nirmit', 'Gorakhpur'); " }, { "code": null, "e": 29995, "s": 29644, "text": "UPDATE Command –This command is used to alter existing table records. Within a table, it modifies data from one or more records. This command is used to alter the data which is already present in a table.Syntax :UPDATE <table_name>\n\nSET <column_name = value>\n\nWHERE condition; Example :UPDATE students\n\nSET due_fees = 20000\n\nWHERE stu_name = 'Mini'; " }, { "code": null, "e": 30004, "s": 29995, "text": "Syntax :" }, { "code": null, "e": 30070, "s": 30004, "text": "UPDATE <table_name>\n\nSET <column_name = value>\n\nWHERE condition; " }, { "code": null, "e": 30080, "s": 30070, "text": "Example :" }, { "code": null, "e": 30145, "s": 30080, "text": "UPDATE students\n\nSET due_fees = 20000\n\nWHERE stu_name = 'Mini'; " }, { "code": null, "e": 30469, "s": 30145, "text": "DELETE Command –It deletes all archives from a table. This command is used to erase some or all of the previous table’s records. If we do not specify the ‘WHERE’ condition then all the rows would be erased or deleted.Syntax :DELETE FROM <table_name>\n\nWHERE <condition>; Example :DELETE FROM students\n\nWHERE stu_id = '001'; " }, { "code": null, "e": 30478, "s": 30469, "text": "Syntax :" }, { "code": null, "e": 30524, "s": 30478, "text": "DELETE FROM <table_name>\n\nWHERE <condition>; " }, { "code": null, "e": 30534, "s": 30524, "text": "Example :" }, { "code": null, "e": 30579, "s": 30534, "text": "DELETE FROM students\n\nWHERE stu_id = '001'; " }, { "code": null, "e": 30592, "s": 30579, "text": "Advantages :" }, { "code": null, "e": 30865, "s": 30592, "text": "DML statements could alter the data that is contained or stored in the database.It delivers effective human contact with the machine.User could specify what data is required.DML aims to have many different varieties and functionalities between vendors providing databases." }, { "code": null, "e": 30946, "s": 30865, "text": "DML statements could alter the data that is contained or stored in the database." }, { "code": null, "e": 31000, "s": 30946, "text": "It delivers effective human contact with the machine." }, { "code": null, "e": 31042, "s": 31000, "text": "User could specify what data is required." }, { "code": null, "e": 31141, "s": 31042, "text": "DML aims to have many different varieties and functionalities between vendors providing databases." }, { "code": null, "e": 31157, "s": 31141, "text": "Disadvantages :" }, { "code": null, "e": 31393, "s": 31157, "text": "We cannot use DML to change the structure of the database.Limit table view i.e., it could conceal some columns in tables.Access the data without having the data stored in the object.Unable to build or erase lists or sections using DML." }, { "code": null, "e": 31452, "s": 31393, "text": "We cannot use DML to change the structure of the database." }, { "code": null, "e": 31516, "s": 31452, "text": "Limit table view i.e., it could conceal some columns in tables." }, { "code": null, "e": 31578, "s": 31516, "text": "Access the data without having the data stored in the object." }, { "code": null, "e": 31632, "s": 31578, "text": "Unable to build or erase lists or sections using DML." }, { "code": null, "e": 31639, "s": 31632, "text": "Picked" }, { "code": null, "e": 31644, "s": 31639, "text": "DBMS" }, { "code": null, "e": 31654, "s": 31644, "text": "Full Form" }, { "code": null, "e": 31662, "s": 31654, "text": "GATE CS" }, { "code": null, "e": 31667, "s": 31662, "text": "DBMS" }, { "code": null, "e": 31765, "s": 31667, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 31806, "s": 31765, "text": "Types of Functional dependencies in DBMS" }, { "code": null, "e": 31849, "s": 31806, "text": "Introduction of Relational Algebra in DBMS" }, { "code": null, "e": 31876, "s": 31849, "text": "Two Phase Locking Protocol" }, { "code": null, "e": 31908, "s": 31876, "text": "What is Temporary Table in SQL?" }, { "code": null, "e": 31941, "s": 31908, "text": "Conflict Serializability in DBMS" }, { "code": null, "e": 31955, "s": 31941, "text": "DBA Full Form" }, { "code": null, "e": 31970, "s": 31955, "text": "HTTP Full Form" }, { "code": null, "e": 31986, "s": 31970, "text": "RDBMS Full Form" }, { "code": null, "e": 32001, "s": 31986, "text": "CDMA Full Form" } ]
Amazon RDS - MS SQL features
Microsoft SQL server is a prominent relational database in the industry. AWS RDS supports multiple versions of MS SQL server. Below list of supported versions and editions. All these versions support point-in-time restores, and automated or manual backups. DB instances running SQL Server can be used inside a VPC. You can also use SSL to connect to a DB instance running SQL Server. Amazon RDS currently supports Multi-AZ deployments for SQL Server using SQL Server Mirroring as a high-availability, failover solution. AWS RDS makes available the majors versions of MS SQL server from 2008 onwards. The details of these versions are as below. SQL Server 2017 RTM SQL Server 2017 RTM SQL Server 2016 SP1 SQL Server 2016 SP1 SQL Server 2014 SP2 SQL Server 2014 SP2 SQL Server 2012 SP4 SQL Server 2012 SP4 SQL Server 2008 R2 SP3 SQL Server 2008 R2 SP3 Below is an example of how to get the supported DB Engine versions using AWS API in a python SDK program. import boto3 client = boto3.client('rds') response = client.describe_db_engine_versions( DBParameterGroupFamily='', DefaultOnly=True, Engine='sqlserver-ee', EngineVersion='', ListSupportedCharacterSets=False, #True, ) print(response) On running the above program, we get the following output − { "ResponseMetadata": { "RetryAttempts": 0, "HTTPStatusCode": 200, "RequestId": "186a9d70-7580-4207-8727-4d29aebb5213", "HTTPHeaders": { "x-amzn-requestid": "186a9d70-7580-4207-8727-4d29aebb5213", "date": "Fri, 14 Sep 2018 05:39:11 GMT", "content-length": "1066", "content-type": "text/xml" } }, "u'DBEngineVersions'": [ { "u'Engine'": "sqlserver-ee", "u'DBParameterGroupFamily'": "sqlserver-ee-14.0", "u'SupportsLogExportsToCloudwatchLogs'": false, "u'SupportsReadReplica'": true, "u'DBEngineDescription'": "MicrosoftSQLServerEnterpriseEdition", "u'EngineVersion'": "14.00.3035.2.v1", "u'DBEngineVersionDescription'": "SQL Server 2017 14.00.3035.2.v1", "u'ValidUpgradeTarget'": [] } ] } The software license for RDS DB instance is included in the pricing for using MS SQL server. The user does not need to bring in any license. Also the pricing includes software license, hardware resources and AWS RDS management features. Following are the MS SQL server editions that are available in the MS SQL Server editions. Enterprise Enterprise Standard Standard Web Web Express Express Unlike oracle, there is no additional licensing requirement for Multi A-Z deployment. Microsoft Server uses SQL server Database Mirroring for such deployment. For instances terminated because of licensing issues, AWS maintains DB snapshots from which the DB can be restored, when the licensing issue is resolved. The database engine of MS SQL server uses a role based security. The master user name used when creating a DB instance is a SQL Server Authentication login that is a member of the processadmin, public, and setupadmin fixed server roles.Any user who creates a database is assigned to the db_owner role for that database and has all database-level permissions except for those that are used for backups. Amazon RDS manages backups for the user. There are quite several features that are not supported by AWS RDS for MS SQL Server. Some of them are listed below. This is important for a scenario when the on-premise database is being taken to the cloud, availability of these features must be evaluated carefully. Always On Always On Backing up to Microsoft Azure Blob Storage Backing up to Microsoft Azure Blob Storage Buffer pool extension Buffer pool extension BULK INSERT and OPENROWSET(BULK...) features BULK INSERT and OPENROWSET(BULK...) features Data Quality Services Data Quality Services Distributed Queries (i.e., Linked Servers) Distributed Queries (i.e., Linked Servers) Distribution Transaction Coordinator (MSDTC) Distribution Transaction Coordinator (MSDTC) File tables File tables FILESTREAM support FILESTREAM support Performance Data Collector Performance Data Collector Policy-Based Management Policy-Based Management SQL Server Audit SQL Server Audit Server-level triggers Server-level triggers T-SQL endpoints (all operations using CREATE ENDPOINT are unavailable) T-SQL endpoints (all operations using CREATE ENDPOINT are unavailable) Print Add Notes Bookmark this page
[ { "code": null, "e": 3105, "s": 2585, "text": "Microsoft SQL server is a prominent relational database in the industry. AWS RDS supports multiple versions of MS SQL server. Below list of supported versions and editions. All these versions support point-in-time restores, and automated or manual backups. DB instances running SQL Server can be used inside a VPC. You can also use SSL to connect to a DB instance running SQL Server. Amazon RDS currently supports Multi-AZ deployments for SQL Server using SQL Server Mirroring as a high-availability, failover solution." }, { "code": null, "e": 3229, "s": 3105, "text": "AWS RDS makes available the majors versions of MS SQL server from 2008 onwards. The details of these versions are as below." }, { "code": null, "e": 3250, "s": 3229, "text": "SQL Server 2017 RTM " }, { "code": null, "e": 3271, "s": 3250, "text": "SQL Server 2017 RTM " }, { "code": null, "e": 3292, "s": 3271, "text": "SQL Server 2016 SP1 " }, { "code": null, "e": 3312, "s": 3292, "text": "SQL Server 2016 SP1" }, { "code": null, "e": 3332, "s": 3312, "text": "SQL Server 2014 SP2" }, { "code": null, "e": 3352, "s": 3332, "text": "SQL Server 2014 SP2" }, { "code": null, "e": 3372, "s": 3352, "text": "SQL Server 2012 SP4" }, { "code": null, "e": 3392, "s": 3372, "text": "SQL Server 2012 SP4" }, { "code": null, "e": 3415, "s": 3392, "text": "SQL Server 2008 R2 SP3" }, { "code": null, "e": 3438, "s": 3415, "text": "SQL Server 2008 R2 SP3" }, { "code": null, "e": 3544, "s": 3438, "text": "Below is an example of how to get the supported DB Engine versions using AWS API in a python SDK program." }, { "code": null, "e": 3801, "s": 3544, "text": "import boto3\n\nclient = boto3.client('rds')\n\nresponse = client.describe_db_engine_versions(\n DBParameterGroupFamily='',\n DefaultOnly=True,\n Engine='sqlserver-ee',\n EngineVersion='',\n ListSupportedCharacterSets=False, #True,\n)\n\nprint(response)" }, { "code": null, "e": 3861, "s": 3801, "text": "On running the above program, we get the following output −" }, { "code": null, "e": 4712, "s": 3861, "text": "{\n \"ResponseMetadata\": {\n \"RetryAttempts\": 0,\n \"HTTPStatusCode\": 200,\n \"RequestId\": \"186a9d70-7580-4207-8727-4d29aebb5213\",\n \"HTTPHeaders\": {\n \"x-amzn-requestid\": \"186a9d70-7580-4207-8727-4d29aebb5213\",\n \"date\": \"Fri, 14 Sep 2018 05:39:11 GMT\",\n \"content-length\": \"1066\",\n \"content-type\": \"text/xml\"\n }\n },\n \"u'DBEngineVersions'\": [\n {\n \"u'Engine'\": \"sqlserver-ee\",\n \"u'DBParameterGroupFamily'\": \"sqlserver-ee-14.0\",\n \"u'SupportsLogExportsToCloudwatchLogs'\": false,\n \"u'SupportsReadReplica'\": true,\n \"u'DBEngineDescription'\": \"MicrosoftSQLServerEnterpriseEdition\",\n \"u'EngineVersion'\": \"14.00.3035.2.v1\",\n \"u'DBEngineVersionDescription'\": \"SQL Server 2017 14.00.3035.2.v1\",\n \"u'ValidUpgradeTarget'\": []\n }\n ]\n}\n" }, { "code": null, "e": 4949, "s": 4712, "text": "The software license for RDS DB instance is included in the pricing for using MS SQL server. The user does not need to bring in any license. Also the pricing includes software license, hardware resources and AWS RDS management features." }, { "code": null, "e": 5040, "s": 4949, "text": "Following are the MS SQL server editions that are available in the MS SQL Server editions." }, { "code": null, "e": 5051, "s": 5040, "text": "Enterprise" }, { "code": null, "e": 5062, "s": 5051, "text": "Enterprise" }, { "code": null, "e": 5071, "s": 5062, "text": "Standard" }, { "code": null, "e": 5080, "s": 5071, "text": "Standard" }, { "code": null, "e": 5085, "s": 5080, "text": "Web " }, { "code": null, "e": 5090, "s": 5085, "text": "Web " }, { "code": null, "e": 5098, "s": 5090, "text": "Express" }, { "code": null, "e": 5106, "s": 5098, "text": "Express" }, { "code": null, "e": 5265, "s": 5106, "text": "Unlike oracle, there is no additional licensing requirement for Multi A-Z deployment. Microsoft Server uses SQL server Database Mirroring for such deployment." }, { "code": null, "e": 5419, "s": 5265, "text": "For instances terminated because of licensing issues, AWS maintains DB snapshots from which the DB can be restored, when the licensing issue is resolved." }, { "code": null, "e": 5485, "s": 5419, "text": "The database engine of MS SQL server uses a role based security. " }, { "code": null, "e": 5863, "s": 5485, "text": "The master user name used when creating a DB instance is a SQL Server Authentication login that is a member of the processadmin, public, and setupadmin fixed server roles.Any user who creates a database is assigned to the db_owner role for that database and has all database-level permissions except for those that are used for backups. Amazon RDS manages backups for the user." }, { "code": null, "e": 6132, "s": 5863, "text": "There are quite several features that are not supported by AWS RDS for MS SQL Server. Some of them are listed below. This is important for a scenario when the on-premise database is being taken to the cloud, availability of these features must be evaluated carefully.\n" }, { "code": null, "e": 6144, "s": 6132, "text": "\tAlways On\t" }, { "code": null, "e": 6156, "s": 6144, "text": "\tAlways On\t" }, { "code": null, "e": 6201, "s": 6156, "text": "\tBacking up to Microsoft Azure Blob Storage\t" }, { "code": null, "e": 6246, "s": 6201, "text": "\tBacking up to Microsoft Azure Blob Storage\t" }, { "code": null, "e": 6270, "s": 6246, "text": "\tBuffer pool extension\t" }, { "code": null, "e": 6294, "s": 6270, "text": "\tBuffer pool extension\t" }, { "code": null, "e": 6341, "s": 6294, "text": "\tBULK INSERT and OPENROWSET(BULK...) features\t" }, { "code": null, "e": 6388, "s": 6341, "text": "\tBULK INSERT and OPENROWSET(BULK...) features\t" }, { "code": null, "e": 6412, "s": 6388, "text": "\tData Quality Services\t" }, { "code": null, "e": 6436, "s": 6412, "text": "\tData Quality Services\t" }, { "code": null, "e": 6481, "s": 6436, "text": "\tDistributed Queries (i.e., Linked Servers)\t" }, { "code": null, "e": 6526, "s": 6481, "text": "\tDistributed Queries (i.e., Linked Servers)\t" }, { "code": null, "e": 6573, "s": 6526, "text": "\tDistribution Transaction Coordinator (MSDTC)\t" }, { "code": null, "e": 6620, "s": 6573, "text": "\tDistribution Transaction Coordinator (MSDTC)\t" }, { "code": null, "e": 6634, "s": 6620, "text": "\tFile tables\t" }, { "code": null, "e": 6648, "s": 6634, "text": "\tFile tables\t" }, { "code": null, "e": 6669, "s": 6648, "text": "\tFILESTREAM support\t" }, { "code": null, "e": 6690, "s": 6669, "text": "\tFILESTREAM support\t" }, { "code": null, "e": 6719, "s": 6690, "text": "\tPerformance Data Collector\t" }, { "code": null, "e": 6748, "s": 6719, "text": "\tPerformance Data Collector\t" }, { "code": null, "e": 6774, "s": 6748, "text": "\tPolicy-Based Management\t" }, { "code": null, "e": 6800, "s": 6774, "text": "\tPolicy-Based Management\t" }, { "code": null, "e": 6819, "s": 6800, "text": "\tSQL Server Audit\t" }, { "code": null, "e": 6838, "s": 6819, "text": "\tSQL Server Audit\t" }, { "code": null, "e": 6862, "s": 6838, "text": "\tServer-level triggers\t" }, { "code": null, "e": 6886, "s": 6862, "text": "\tServer-level triggers\t" }, { "code": null, "e": 6959, "s": 6886, "text": "\tT-SQL endpoints (all operations using CREATE ENDPOINT are unavailable)\t" }, { "code": null, "e": 7032, "s": 6959, "text": "\tT-SQL endpoints (all operations using CREATE ENDPOINT are unavailable)\t" }, { "code": null, "e": 7039, "s": 7032, "text": " Print" }, { "code": null, "e": 7050, "s": 7039, "text": " Add Notes" } ]
How to generate prime numbers using Python?
A prime number is the one that is not divisible by any other number except 1 and itself. In Python % modulo operator is available to test if a number is divisible by other. Assuming we have to find prime numbers between 1 to 100, each number (let us say x) in the range needs to be successively checked for divisibility by 2 to x-1. This is achieved by employing two nested loops. for x in range(1,101): for y in range(2,x): if x%y==0:break else: print (x,sep=' ', end=' ') Above code generates prime numbers between 1-100 1 2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97
[ { "code": null, "e": 1151, "s": 1062, "text": "A prime number is the one that is not divisible by any other number except 1 and itself." }, { "code": null, "e": 1236, "s": 1151, "text": "In Python % modulo operator is available to test if a number is divisible by other. " }, { "code": null, "e": 1444, "s": 1236, "text": "Assuming we have to find prime numbers between 1 to 100, each number (let us say x) in the range needs to be successively checked for divisibility by 2 to x-1. This is achieved by employing two nested loops." }, { "code": null, "e": 1537, "s": 1444, "text": "for x in range(1,101):\nfor y in range(2,x):\nif x%y==0:break\nelse:\nprint (x,sep=' ', end=' ')" }, { "code": null, "e": 1586, "s": 1537, "text": "Above code generates prime numbers between 1-100" }, { "code": null, "e": 1659, "s": 1586, "text": "1 2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97" } ]
How to get current time in milliseconds in Python?
You can get the current time in milliseconds in Python using the time module. You can get the time in seconds using time.time function(as a floating point value). To convert it to milliseconds, you need to multiply it with 1000 and round it off. import time milliseconds = int(round(time.time() * 1000)) print(milliseconds) This will give the output − 1514825676008
[ { "code": null, "e": 1309, "s": 1062, "text": "You can get the current time in milliseconds in Python using the time module. You can get the time in seconds using time.time function(as a floating point value). To convert it to milliseconds, you need to multiply it with 1000 and round it off. " }, { "code": null, "e": 1387, "s": 1309, "text": "import time\nmilliseconds = int(round(time.time() * 1000))\nprint(milliseconds)" }, { "code": null, "e": 1415, "s": 1387, "text": "This will give the output −" }, { "code": null, "e": 1429, "s": 1415, "text": "1514825676008" } ]
BART for Paraphrasing with Simple Transformers | by Thilina Rajapakse | Towards Data Science
BART is a denoising autoencoder for pretraining sequence-to-sequence models. BART is trained by (1) corrupting text with an arbitrary noising function, and (2) learning a model to reconstruct the original text. - BART: Denoising Sequence-to-Sequence Pre-training for Natural Language Generation, Translation, and Comprehension - Don’t worry if that sounds a little complicated; we are going to break it down and see what it all means. To add a little bit of background before we dive into BART, it’s time for the now-customary ode to Transfer Learning with self-supervised models. It’s been said many times over the past couple of years, but Transformers really have achieved incredible success in a wide variety of Natural Language Processing (NLP) tasks. BART uses a standard Transformer architecture (Encoder-Decoder) like the original Transformer model used for neural machine translation but also incorporates some changes from BERT (only uses the encoder) and GPT (only uses the decoder). You can refer to the 2.1 Architecture section of the BART paper for more details. BART is pre-trained by minimizing the cross-entropy loss between the decoder output and the original sequence. MLM models such as BERT are pre-trained to predict masked tokens. This process can be broken down as follows: Replace a random subset of the input with a mask token [MASK]. (Adding noise/corruption)The model predicts the original tokens for each of the [MASK] tokens. (Denoising) Replace a random subset of the input with a mask token [MASK]. (Adding noise/corruption) The model predicts the original tokens for each of the [MASK] tokens. (Denoising) Importantly, BERT models can “see” the full input sequence (with some tokens replaced with [MASK]) when attempting to predict the original tokens. This makes BERT a bidirectional model, i.e. it can “see” the tokens before and after the masked tokens. This is suited for tasks like classification where you can use information from the full sequence to perform the prediction. However, it is less suited for text generation tasks where the prediction depends only on the previous words. Models used for text generation, such as GPT2, are pre-trained to predict the next token given the previous sequence of tokens. This pre-training objective results in models that are well-suited for text generation, but not for tasks like classification. BART has both an encoder (like BERT) and a decoder (like GPT), essentially getting the best of both worlds. The encoder uses a denoising objective similar to BERT while the decoder attempts to reproduce the original sequence (autoencoder), token by token, using the previous (uncorrupted) tokens and the output from the encoder. A significant advantage of this setup is the unlimited flexibility of choosing the corruption scheme; including changing the length of the original input. Or, in fancier terms, the text can be corrupted with an arbitrary noising function. The corruption schemes used in the paper are summarized below. Token Masking — A random subset of the input is replaced with [MASK] tokens, like in BERT.Token Deletion — Random tokens are deleted from the input. The model must decide which positions are missing (as the tokens are simply deleted and not replaced with anything else).Text Infilling — A number of text spans (length can vary) are each replaced with a single [MASK] token.Sentence Permutation — The input is split based on periods (.), and the sentences are shuffled.Document Rotation — A token is chosen at random, and the sequence is rotated so that it starts with the chosen token. Token Masking — A random subset of the input is replaced with [MASK] tokens, like in BERT. Token Deletion — Random tokens are deleted from the input. The model must decide which positions are missing (as the tokens are simply deleted and not replaced with anything else). Text Infilling — A number of text spans (length can vary) are each replaced with a single [MASK] token. Sentence Permutation — The input is split based on periods (.), and the sentences are shuffled. Document Rotation — A token is chosen at random, and the sequence is rotated so that it starts with the chosen token. The authors note that training BART with text infilling yields the most consistently strong performance across many tasks. For the task we are interested in, namely paraphrasing, the pre-trained BART model can be fine-tuned directly using the input sequence (original phrase) and the target sequence (paraphrased sentence) as a Sequence-to-Sequence model. This also works for tasks like summarization and abstractive question answering. We will use the Simple Transformers library, based on the Hugging Face Transformers library, to train the models. 1. Install Anaconda or Miniconda Package Manager from here. 2. Create a new virtual environment and install packages. conda create -n st python pandas tqdmconda activate st 3. If using CUDA: conda install pytorch>=1.6 cudatoolkit=10.2 -c pytorch else: conda install pytorch cpuonly -c pytorch 4. Install simpletransformers. pip install simpletransformers We will be combining three datasets to serve as training data for our BART Paraphrasing Model. Google PAWS-Wiki Labeled (Final)Quora Question Pairs DatasetMicrosoft Research Paraphrase Corpus (MSRP) Google PAWS-Wiki Labeled (Final) Quora Question Pairs Dataset Microsoft Research Paraphrase Corpus (MSRP) The bash script below can be used to easily download and prep the first two datasets, but the MSRP dataset has to be downloaded manually from the link. (Microsoft hasn’t provided a direct link 😞 ) Make sure you place the files in the same directory ( data ) to avoid annoyances with file paths in the example code. We also have a couple of helper functions, one to load data, and one to clean unnecessary spaces in the training data. Both of these functions are defined in utils.py. Some of the data have spaces before punctuation marks that we need to remove. clean_unnecessary_spaces() function is used for this purpose. Once the data is prepared, training the model is quite simple. Note that you can find all the code in the Simple Transformers examples here. First, we import all the necessary stuff and set up logging. Next, we load the datasets. Then, we set up the model and hyperparameter values. Note that we are using the pre-trained facebook/bart-large model, and fine-tuning it on our own dataset. Finally, we’ll generate paraphrases for each of the sentences in the test data. This will write the predictions to the predictions directory. The hyperparameter values are set to general, sensible values without doing hyperparameter optimization. For this task, the ground truth does not represent the only possible correct answer (nor is it necessarily the best answer). Because of this, tuning the hyperparameters to nudge the generated text as close to the ground truth as possible doesn’t make much sense. Our aim is to generate good paraphrased sequences rather than to produce the exact paraphrased sequence from the dataset. If you are interested in Hyperparameter Optimization with Simple Transformers (particularly useful with other models/tasks like classification), do check out my guide here. towardsdatascience.com The decoding algorithm (and the relevant hyperparameters) used has a considerable impact on the quality and nature of the generated text. The values I’ve chosen (shown below) are generally suited to produce “natural” text. For more information, please refer to the excellent Hugging Face guide here. You can use the script below to test the model on any sentence. Let’s look at some of the paraphrased sequences generated by the model for the test data. For each input sequence, the model will generate three ( num_return_sequences ) paraphrased sequences. 1. Orignal:A recording of folk songs done for the Columbia society in 1942 was largely arranged by Pjetër Dungu.Truth:A recording of folk songs made for the Columbia society in 1942 was largely arranged by Pjetër Dungu.Prediction:A recording of folk songs made in 1942 for the Columbia Society was largely arranged by Pjetr Dungu.A recording of folk songs for the Columbia society in 1942 was largely arranged by Pjetr Dungu.A recording of folk songs done for the Columbia Society in 1942 was largely arranged by Pjetr Dungu. 2. Original:In mathematical astronomy, his fame is due to the introduction of the astronomical globe, and his early contributions to understanding the movement of the planets.Truth:His fame is due in mathematical astronomy to the introduction of the astronomical globe and to his early contributions to the understanding of the movement of the planets.Prediction:His fame in mathematical astronomy is due to the introduction of the astronomical globe and his early contributions to understanding the movement of the planets.In mathematical astronomy, his fame is due to the introduction of the astronomical globe and his early contributions to understanding the motion of the planets.In mathematical astronomy his fame is due to the introduction of the astronomical globe and his early contributions to understanding the movement of the planets. 3. Original:Why are people obsessed with Cara Delevingne?Truth:Why are people so obsessed with Cara Delevingne?Prediction:Why do people fall in love with Cara Delevingne?Why is everyone obsessed with Cara Delevingne?Why do people like Cara Delevingne? 4. Original:Earl St Vincent was a British ship that was captured in 1803 and became a French trade man.Truth:Earl St Vincent was a British ship that was captured and became a French merchantman in 1803.Prediction:Earl St Vincent was a British ship captured in 1803 and became a French trader.Earl St Vincent was a British ship captured in 1803 and became a French trade man.Earl St Vincent was a British ship that was captured in 1803 and became a French trade man. 5. Original:Worcester is a town and county city of Worcestershire in England.Truth:Worcester is a city and county town of Worcestershire in England.Prediction:Worcester is a town and county of Worcestershire in England.Worcester is a town and county town in Worcestershire in England.Worcester is a town and county town of Worcestershire in England. 6. Out of domain sentence Original:The goal of any Deep Learning model is to take in an input and generate the correct output.Predictions >>>The goal of any deep learning model is to take an input and generate the correct output.The goal of a deep learning model is to take an input and generate the correct output.Any Deep Learning model the goal of which is to take in an input and generate the correct output. As can be seen from these examples, our BART model has learned to generate paraphrases quite well! The generated paraphrases can sometimes have minor issues, some of which are listed below. The generated sequence is almost identical to the original with only minor differences in a word or two.Incorrect or awkward grammar.Might not be as good on out of domain (from training data) inputs. The generated sequence is almost identical to the original with only minor differences in a word or two. Incorrect or awkward grammar. Might not be as good on out of domain (from training data) inputs. Encouragingly, these issues seem to be quite rare and can most likely be averted by using better training data (the same problems can sometimes be seen in the training data ground truth as well). Sequence-to-Sequence models like BART are another arrow in the quiver of NLP practitioners. They are particularly useful for tasks involving text generation such as paraphrasing, summarization, and abstractive question answering. Paraphrasing can be used for data augmentation where you can create a larger dataset by paraphrasing the available data.
[ { "code": null, "e": 382, "s": 171, "text": "BART is a denoising autoencoder for pretraining sequence-to-sequence models. BART is trained by (1) corrupting text with an arbitrary noising function, and (2) learning a model to reconstruct the original text." }, { "code": null, "e": 500, "s": 382, "text": "- BART: Denoising Sequence-to-Sequence Pre-training for Natural Language Generation, Translation, and Comprehension -" }, { "code": null, "e": 928, "s": 500, "text": "Don’t worry if that sounds a little complicated; we are going to break it down and see what it all means. To add a little bit of background before we dive into BART, it’s time for the now-customary ode to Transfer Learning with self-supervised models. It’s been said many times over the past couple of years, but Transformers really have achieved incredible success in a wide variety of Natural Language Processing (NLP) tasks." }, { "code": null, "e": 1248, "s": 928, "text": "BART uses a standard Transformer architecture (Encoder-Decoder) like the original Transformer model used for neural machine translation but also incorporates some changes from BERT (only uses the encoder) and GPT (only uses the decoder). You can refer to the 2.1 Architecture section of the BART paper for more details." }, { "code": null, "e": 1359, "s": 1248, "text": "BART is pre-trained by minimizing the cross-entropy loss between the decoder output and the original sequence." }, { "code": null, "e": 1469, "s": 1359, "text": "MLM models such as BERT are pre-trained to predict masked tokens. This process can be broken down as follows:" }, { "code": null, "e": 1639, "s": 1469, "text": "Replace a random subset of the input with a mask token [MASK]. (Adding noise/corruption)The model predicts the original tokens for each of the [MASK] tokens. (Denoising)" }, { "code": null, "e": 1728, "s": 1639, "text": "Replace a random subset of the input with a mask token [MASK]. (Adding noise/corruption)" }, { "code": null, "e": 1810, "s": 1728, "text": "The model predicts the original tokens for each of the [MASK] tokens. (Denoising)" }, { "code": null, "e": 2061, "s": 1810, "text": "Importantly, BERT models can “see” the full input sequence (with some tokens replaced with [MASK]) when attempting to predict the original tokens. This makes BERT a bidirectional model, i.e. it can “see” the tokens before and after the masked tokens." }, { "code": null, "e": 2296, "s": 2061, "text": "This is suited for tasks like classification where you can use information from the full sequence to perform the prediction. However, it is less suited for text generation tasks where the prediction depends only on the previous words." }, { "code": null, "e": 2551, "s": 2296, "text": "Models used for text generation, such as GPT2, are pre-trained to predict the next token given the previous sequence of tokens. This pre-training objective results in models that are well-suited for text generation, but not for tasks like classification." }, { "code": null, "e": 2659, "s": 2551, "text": "BART has both an encoder (like BERT) and a decoder (like GPT), essentially getting the best of both worlds." }, { "code": null, "e": 2880, "s": 2659, "text": "The encoder uses a denoising objective similar to BERT while the decoder attempts to reproduce the original sequence (autoencoder), token by token, using the previous (uncorrupted) tokens and the output from the encoder." }, { "code": null, "e": 3119, "s": 2880, "text": "A significant advantage of this setup is the unlimited flexibility of choosing the corruption scheme; including changing the length of the original input. Or, in fancier terms, the text can be corrupted with an arbitrary noising function." }, { "code": null, "e": 3182, "s": 3119, "text": "The corruption schemes used in the paper are summarized below." }, { "code": null, "e": 3768, "s": 3182, "text": "Token Masking — A random subset of the input is replaced with [MASK] tokens, like in BERT.Token Deletion — Random tokens are deleted from the input. The model must decide which positions are missing (as the tokens are simply deleted and not replaced with anything else).Text Infilling — A number of text spans (length can vary) are each replaced with a single [MASK] token.Sentence Permutation — The input is split based on periods (.), and the sentences are shuffled.Document Rotation — A token is chosen at random, and the sequence is rotated so that it starts with the chosen token." }, { "code": null, "e": 3859, "s": 3768, "text": "Token Masking — A random subset of the input is replaced with [MASK] tokens, like in BERT." }, { "code": null, "e": 4040, "s": 3859, "text": "Token Deletion — Random tokens are deleted from the input. The model must decide which positions are missing (as the tokens are simply deleted and not replaced with anything else)." }, { "code": null, "e": 4144, "s": 4040, "text": "Text Infilling — A number of text spans (length can vary) are each replaced with a single [MASK] token." }, { "code": null, "e": 4240, "s": 4144, "text": "Sentence Permutation — The input is split based on periods (.), and the sentences are shuffled." }, { "code": null, "e": 4358, "s": 4240, "text": "Document Rotation — A token is chosen at random, and the sequence is rotated so that it starts with the chosen token." }, { "code": null, "e": 4481, "s": 4358, "text": "The authors note that training BART with text infilling yields the most consistently strong performance across many tasks." }, { "code": null, "e": 4714, "s": 4481, "text": "For the task we are interested in, namely paraphrasing, the pre-trained BART model can be fine-tuned directly using the input sequence (original phrase) and the target sequence (paraphrased sentence) as a Sequence-to-Sequence model." }, { "code": null, "e": 4795, "s": 4714, "text": "This also works for tasks like summarization and abstractive question answering." }, { "code": null, "e": 4909, "s": 4795, "text": "We will use the Simple Transformers library, based on the Hugging Face Transformers library, to train the models." }, { "code": null, "e": 4969, "s": 4909, "text": "1. Install Anaconda or Miniconda Package Manager from here." }, { "code": null, "e": 5027, "s": 4969, "text": "2. Create a new virtual environment and install packages." }, { "code": null, "e": 5082, "s": 5027, "text": "conda create -n st python pandas tqdmconda activate st" }, { "code": null, "e": 5100, "s": 5082, "text": "3. If using CUDA:" }, { "code": null, "e": 5155, "s": 5100, "text": "conda install pytorch>=1.6 cudatoolkit=10.2 -c pytorch" }, { "code": null, "e": 5161, "s": 5155, "text": "else:" }, { "code": null, "e": 5202, "s": 5161, "text": "conda install pytorch cpuonly -c pytorch" }, { "code": null, "e": 5233, "s": 5202, "text": "4. Install simpletransformers." }, { "code": null, "e": 5264, "s": 5233, "text": "pip install simpletransformers" }, { "code": null, "e": 5359, "s": 5264, "text": "We will be combining three datasets to serve as training data for our BART Paraphrasing Model." }, { "code": null, "e": 5463, "s": 5359, "text": "Google PAWS-Wiki Labeled (Final)Quora Question Pairs DatasetMicrosoft Research Paraphrase Corpus (MSRP)" }, { "code": null, "e": 5496, "s": 5463, "text": "Google PAWS-Wiki Labeled (Final)" }, { "code": null, "e": 5525, "s": 5496, "text": "Quora Question Pairs Dataset" }, { "code": null, "e": 5569, "s": 5525, "text": "Microsoft Research Paraphrase Corpus (MSRP)" }, { "code": null, "e": 5766, "s": 5569, "text": "The bash script below can be used to easily download and prep the first two datasets, but the MSRP dataset has to be downloaded manually from the link. (Microsoft hasn’t provided a direct link 😞 )" }, { "code": null, "e": 5884, "s": 5766, "text": "Make sure you place the files in the same directory ( data ) to avoid annoyances with file paths in the example code." }, { "code": null, "e": 6052, "s": 5884, "text": "We also have a couple of helper functions, one to load data, and one to clean unnecessary spaces in the training data. Both of these functions are defined in utils.py." }, { "code": null, "e": 6192, "s": 6052, "text": "Some of the data have spaces before punctuation marks that we need to remove. clean_unnecessary_spaces() function is used for this purpose." }, { "code": null, "e": 6255, "s": 6192, "text": "Once the data is prepared, training the model is quite simple." }, { "code": null, "e": 6333, "s": 6255, "text": "Note that you can find all the code in the Simple Transformers examples here." }, { "code": null, "e": 6394, "s": 6333, "text": "First, we import all the necessary stuff and set up logging." }, { "code": null, "e": 6422, "s": 6394, "text": "Next, we load the datasets." }, { "code": null, "e": 6580, "s": 6422, "text": "Then, we set up the model and hyperparameter values. Note that we are using the pre-trained facebook/bart-large model, and fine-tuning it on our own dataset." }, { "code": null, "e": 6660, "s": 6580, "text": "Finally, we’ll generate paraphrases for each of the sentences in the test data." }, { "code": null, "e": 6722, "s": 6660, "text": "This will write the predictions to the predictions directory." }, { "code": null, "e": 7090, "s": 6722, "text": "The hyperparameter values are set to general, sensible values without doing hyperparameter optimization. For this task, the ground truth does not represent the only possible correct answer (nor is it necessarily the best answer). Because of this, tuning the hyperparameters to nudge the generated text as close to the ground truth as possible doesn’t make much sense." }, { "code": null, "e": 7212, "s": 7090, "text": "Our aim is to generate good paraphrased sequences rather than to produce the exact paraphrased sequence from the dataset." }, { "code": null, "e": 7385, "s": 7212, "text": "If you are interested in Hyperparameter Optimization with Simple Transformers (particularly useful with other models/tasks like classification), do check out my guide here." }, { "code": null, "e": 7408, "s": 7385, "text": "towardsdatascience.com" }, { "code": null, "e": 7631, "s": 7408, "text": "The decoding algorithm (and the relevant hyperparameters) used has a considerable impact on the quality and nature of the generated text. The values I’ve chosen (shown below) are generally suited to produce “natural” text." }, { "code": null, "e": 7708, "s": 7631, "text": "For more information, please refer to the excellent Hugging Face guide here." }, { "code": null, "e": 7772, "s": 7708, "text": "You can use the script below to test the model on any sentence." }, { "code": null, "e": 7965, "s": 7772, "text": "Let’s look at some of the paraphrased sequences generated by the model for the test data. For each input sequence, the model will generate three ( num_return_sequences ) paraphrased sequences." }, { "code": null, "e": 7968, "s": 7965, "text": "1." }, { "code": null, "e": 8493, "s": 7968, "text": "Orignal:A recording of folk songs done for the Columbia society in 1942 was largely arranged by Pjetër Dungu.Truth:A recording of folk songs made for the Columbia society in 1942 was largely arranged by Pjetër Dungu.Prediction:A recording of folk songs made in 1942 for the Columbia Society was largely arranged by Pjetr Dungu.A recording of folk songs for the Columbia society in 1942 was largely arranged by Pjetr Dungu.A recording of folk songs done for the Columbia Society in 1942 was largely arranged by Pjetr Dungu." }, { "code": null, "e": 8496, "s": 8493, "text": "2." }, { "code": null, "e": 9339, "s": 8496, "text": "Original:In mathematical astronomy, his fame is due to the introduction of the astronomical globe, and his early contributions to understanding the movement of the planets.Truth:His fame is due in mathematical astronomy to the introduction of the astronomical globe and to his early contributions to the understanding of the movement of the planets.Prediction:His fame in mathematical astronomy is due to the introduction of the astronomical globe and his early contributions to understanding the movement of the planets.In mathematical astronomy, his fame is due to the introduction of the astronomical globe and his early contributions to understanding the motion of the planets.In mathematical astronomy his fame is due to the introduction of the astronomical globe and his early contributions to understanding the movement of the planets." }, { "code": null, "e": 9342, "s": 9339, "text": "3." }, { "code": null, "e": 9591, "s": 9342, "text": "Original:Why are people obsessed with Cara Delevingne?Truth:Why are people so obsessed with Cara Delevingne?Prediction:Why do people fall in love with Cara Delevingne?Why is everyone obsessed with Cara Delevingne?Why do people like Cara Delevingne?" }, { "code": null, "e": 9594, "s": 9591, "text": "4." }, { "code": null, "e": 10057, "s": 9594, "text": "Original:Earl St Vincent was a British ship that was captured in 1803 and became a French trade man.Truth:Earl St Vincent was a British ship that was captured and became a French merchantman in 1803.Prediction:Earl St Vincent was a British ship captured in 1803 and became a French trader.Earl St Vincent was a British ship captured in 1803 and became a French trade man.Earl St Vincent was a British ship that was captured in 1803 and became a French trade man." }, { "code": null, "e": 10060, "s": 10057, "text": "5." }, { "code": null, "e": 10407, "s": 10060, "text": "Original:Worcester is a town and county city of Worcestershire in England.Truth:Worcester is a city and county town of Worcestershire in England.Prediction:Worcester is a town and county of Worcestershire in England.Worcester is a town and county town in Worcestershire in England.Worcester is a town and county town of Worcestershire in England." }, { "code": null, "e": 10433, "s": 10407, "text": "6. Out of domain sentence" }, { "code": null, "e": 10820, "s": 10433, "text": "Original:The goal of any Deep Learning model is to take in an input and generate the correct output.Predictions >>>The goal of any deep learning model is to take an input and generate the correct output.The goal of a deep learning model is to take an input and generate the correct output.Any Deep Learning model the goal of which is to take in an input and generate the correct output." }, { "code": null, "e": 10919, "s": 10820, "text": "As can be seen from these examples, our BART model has learned to generate paraphrases quite well!" }, { "code": null, "e": 11010, "s": 10919, "text": "The generated paraphrases can sometimes have minor issues, some of which are listed below." }, { "code": null, "e": 11210, "s": 11010, "text": "The generated sequence is almost identical to the original with only minor differences in a word or two.Incorrect or awkward grammar.Might not be as good on out of domain (from training data) inputs." }, { "code": null, "e": 11315, "s": 11210, "text": "The generated sequence is almost identical to the original with only minor differences in a word or two." }, { "code": null, "e": 11345, "s": 11315, "text": "Incorrect or awkward grammar." }, { "code": null, "e": 11412, "s": 11345, "text": "Might not be as good on out of domain (from training data) inputs." }, { "code": null, "e": 11608, "s": 11412, "text": "Encouragingly, these issues seem to be quite rare and can most likely be averted by using better training data (the same problems can sometimes be seen in the training data ground truth as well)." }, { "code": null, "e": 11838, "s": 11608, "text": "Sequence-to-Sequence models like BART are another arrow in the quiver of NLP practitioners. They are particularly useful for tasks involving text generation such as paraphrasing, summarization, and abstractive question answering." } ]
Python | Consecutive characters frequency - GeeksforGeeks
22 Apr, 2020 Sometimes, while working with Python, we can have a problem in which we need to compute the frequency of consecutive characters till character changes. This can have application in many domains. Lets discuss certain ways in which this task can be performed. Method #1 : Using list comprehension + groupby()This is one of the shorthand with the help of which this task can be performed. In this, we employ groupby() to group consecutives together to perform frequency calculations. # Python3 code to demonstrate working of # Consecutive characters frequency# Using list comprehension + groupby()from itertools import groupby # initializing stringtest_str = "geekksforgggeeks" # printing original stringprint("The original string is : " + test_str) # Consecutive characters frequency# Using list comprehension + groupby()res = [len(list(j)) for _, j in groupby(test_str)] # printing result print("The Consecutive characters frequency : " + str(res)) The original string is : geekksforgggeeks The Consecutive characters frequency : [1, 2, 2, 1, 1, 1, 1, 3, 2, 1, 1] Method #2 : Using regexAnother way to solve this problem is using regex. In this we employ regex character finding technique and find count using len(). # Python3 code to demonstrate working of # Consecutive characters frequency# Using regeximport re # initializing stringtest_str = "geekksforgggeeks" # printing original stringprint("The original string is : " + test_str) # Consecutive characters frequency# Using regexres = [len(sub.group()) for sub in re.finditer(r'(.)\1*', test_str)] # printing result print("The Consecutive characters frequency : " + str(res)) The original string is : geekksforgggeeks The Consecutive characters frequency : [1, 2, 2, 1, 1, 1, 1, 3, 2, 1, 1] Python string-programs Python Python Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments How to Install PIP on Windows ? How to drop one or multiple columns in Pandas Dataframe How To Convert Python Dictionary To JSON? Check if element exists in list in Python Python | Pandas dataframe.groupby() Defaultdict in Python Python | Get dictionary keys as a list Python | Split string into list of characters Python program to check whether a number is Prime or not Python | Convert a list to dictionary
[ { "code": null, "e": 23927, "s": 23899, "text": "\n22 Apr, 2020" }, { "code": null, "e": 24185, "s": 23927, "text": "Sometimes, while working with Python, we can have a problem in which we need to compute the frequency of consecutive characters till character changes. This can have application in many domains. Lets discuss certain ways in which this task can be performed." }, { "code": null, "e": 24408, "s": 24185, "text": "Method #1 : Using list comprehension + groupby()This is one of the shorthand with the help of which this task can be performed. In this, we employ groupby() to group consecutives together to perform frequency calculations." }, { "code": "# Python3 code to demonstrate working of # Consecutive characters frequency# Using list comprehension + groupby()from itertools import groupby # initializing stringtest_str = \"geekksforgggeeks\" # printing original stringprint(\"The original string is : \" + test_str) # Consecutive characters frequency# Using list comprehension + groupby()res = [len(list(j)) for _, j in groupby(test_str)] # printing result print(\"The Consecutive characters frequency : \" + str(res)) ", "e": 24880, "s": 24408, "text": null }, { "code": null, "e": 24996, "s": 24880, "text": "The original string is : geekksforgggeeks\nThe Consecutive characters frequency : [1, 2, 2, 1, 1, 1, 1, 3, 2, 1, 1]\n" }, { "code": null, "e": 25151, "s": 24998, "text": "Method #2 : Using regexAnother way to solve this problem is using regex. In this we employ regex character finding technique and find count using len()." }, { "code": "# Python3 code to demonstrate working of # Consecutive characters frequency# Using regeximport re # initializing stringtest_str = \"geekksforgggeeks\" # printing original stringprint(\"The original string is : \" + test_str) # Consecutive characters frequency# Using regexres = [len(sub.group()) for sub in re.finditer(r'(.)\\1*', test_str)] # printing result print(\"The Consecutive characters frequency : \" + str(res)) ", "e": 25571, "s": 25151, "text": null }, { "code": null, "e": 25687, "s": 25571, "text": "The original string is : geekksforgggeeks\nThe Consecutive characters frequency : [1, 2, 2, 1, 1, 1, 1, 3, 2, 1, 1]\n" }, { "code": null, "e": 25710, "s": 25687, "text": "Python string-programs" }, { "code": null, "e": 25717, "s": 25710, "text": "Python" }, { "code": null, "e": 25733, "s": 25717, "text": "Python Programs" }, { "code": null, "e": 25831, "s": 25733, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 25840, "s": 25831, "text": "Comments" }, { "code": null, "e": 25853, "s": 25840, "text": "Old Comments" }, { "code": null, "e": 25885, "s": 25853, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 25941, "s": 25885, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 25983, "s": 25941, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 26025, "s": 25983, "text": "Check if element exists in list in Python" }, { "code": null, "e": 26061, "s": 26025, "text": "Python | Pandas dataframe.groupby()" }, { "code": null, "e": 26083, "s": 26061, "text": "Defaultdict in Python" }, { "code": null, "e": 26122, "s": 26083, "text": "Python | Get dictionary keys as a list" }, { "code": null, "e": 26168, "s": 26122, "text": "Python | Split string into list of characters" }, { "code": null, "e": 26225, "s": 26168, "text": "Python program to check whether a number is Prime or not" } ]
How to add calendar events in Android App?
This example demonstrates how do I add calendar events in android. Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project. Step 2 − Add the following code to res/layout/activity_main.xml. <?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:padding="8dp" tools:context=".MainActivity"> <Button android:layout_width="match_parent" android:layout_height="wrap_content" android:onClick="AddCalendarEvent" android:text="Add Calendar Event" /> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerInParent="true" android:text="Calendar Event In Android" android:textSize="18sp" android:textStyle="bold" /> </RelativeLayout> Step 3 − Add the following code to src/MainActivity.java import androidx.appcompat.app.AppCompatActivity; import android.content.Intent; import android.os.Bundle; import android.view.View; import java.util.Calendar; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } public void AddCalendarEvent(View view) { Calendar calendarEvent = Calendar.getInstance(); Intent i = new Intent(Intent.ACTION_EDIT); i.setType("vnd.android.cursor.item/event"); i.putExtra("beginTime", calendarEvent.getTimeInMillis()); i.putExtra("allDay", true); i.putExtra("rule", "FREQ=YEARLY"); i.putExtra("endTime", calendarEvent.getTimeInMillis() + 60 * 60 * 1000); i.putExtra("title", "Calendar Event"); startActivity(i); } } Step 4 − Add the following code to androidManifest.xml <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="app.com.sample"> <application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:roundIcon="@mipmap/ic_launcher_round" android:supportsRtl="true" android:theme="@style/AppTheme"> <activity android:name=".MainActivity"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> </manifest> Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from the android studio, open one of your project's activity files and click Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen − Click here to download the project code.
[ { "code": null, "e": 1129, "s": 1062, "text": "This example demonstrates how do I add calendar events in android." }, { "code": null, "e": 1258, "s": 1129, "text": "Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project." }, { "code": null, "e": 1323, "s": 1258, "text": "Step 2 − Add the following code to res/layout/activity_main.xml." }, { "code": null, "e": 2075, "s": 1323, "text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<RelativeLayout\nxmlns:android=\"http://schemas.android.com/apk/res/android\"\n xmlns:tools=\"http://schemas.android.com/tools\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"match_parent\"\n android:padding=\"8dp\"\n tools:context=\".MainActivity\">\n <Button\n android:layout_width=\"match_parent\"\n android:layout_height=\"wrap_content\"\n android:onClick=\"AddCalendarEvent\"\n android:text=\"Add Calendar Event\" />\n <TextView\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:layout_centerInParent=\"true\"\n android:text=\"Calendar Event In Android\"\n android:textSize=\"18sp\"\n android:textStyle=\"bold\" />\n</RelativeLayout>" }, { "code": null, "e": 2132, "s": 2075, "text": "Step 3 − Add the following code to src/MainActivity.java" }, { "code": null, "e": 3000, "s": 2132, "text": "import androidx.appcompat.app.AppCompatActivity;\nimport android.content.Intent;\nimport android.os.Bundle;\nimport android.view.View;\nimport java.util.Calendar;\npublic class MainActivity extends AppCompatActivity {\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main);\n }\n public void AddCalendarEvent(View view) {\n Calendar calendarEvent = Calendar.getInstance();\n Intent i = new Intent(Intent.ACTION_EDIT);\n i.setType(\"vnd.android.cursor.item/event\");\n i.putExtra(\"beginTime\", calendarEvent.getTimeInMillis());\n i.putExtra(\"allDay\", true);\n i.putExtra(\"rule\", \"FREQ=YEARLY\");\n i.putExtra(\"endTime\", calendarEvent.getTimeInMillis() + 60 * 60 * 1000);\n i.putExtra(\"title\", \"Calendar Event\");\n startActivity(i);\n }\n}" }, { "code": null, "e": 3055, "s": 3000, "text": "Step 4 − Add the following code to androidManifest.xml" }, { "code": null, "e": 3728, "s": 3055, "text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<manifest xmlns:android=\"http://schemas.android.com/apk/res/android\"\n package=\"app.com.sample\">\n <application\n android:allowBackup=\"true\"\n android:icon=\"@mipmap/ic_launcher\"\n android:label=\"@string/app_name\"\n android:roundIcon=\"@mipmap/ic_launcher_round\"\n android:supportsRtl=\"true\"\n android:theme=\"@style/AppTheme\">\n <activity android:name=\".MainActivity\">\n <intent-filter>\n <action android:name=\"android.intent.action.MAIN\" />\n <category android:name=\"android.intent.category.LAUNCHER\" />\n </intent-filter>\n </activity>\n </application>\n</manifest>" }, { "code": null, "e": 4079, "s": 3728, "text": "Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from the android studio, open one of your project's activity files and click Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen −" }, { "code": null, "e": 4120, "s": 4079, "text": "Click here to download the project code." } ]
Bootstrap .checkbox-inline class
Use .checkbox-inline class to a series of checkboxes for controls to appear on the same line. You can try to run the following code to implement the .checkbox-inline class Live Demo <!DOCTYPE html> <html> <head> <title>Bootstrap Forms</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> <label for = "name">Best IDE (You can select more than one)</label> <div> <label class = "checkbox-inline"> <input type = "checkbox" id = "inlineCheckbox1" value = "option1"> NetBeans IDE </label> <label class = "checkbox-inline"> <input type = "checkbox" id = "inlineCheckbox2" value = "option2"> Eclipse IDE </label> </div> </body> </html>
[ { "code": null, "e": 1157, "s": 1062, "text": "Use .checkbox-inline class to a series of checkboxes for controls to appear on the same line. " }, { "code": null, "e": 1235, "s": 1157, "text": "You can try to run the following code to implement the .checkbox-inline class" }, { "code": null, "e": 1245, "s": 1235, "text": "Live Demo" }, { "code": null, "e": 2154, "s": 1245, "text": "<!DOCTYPE html>\n<html>\n <head>\n <title>Bootstrap Forms</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 <label for = \"name\">Best IDE (You can select more than one)</label>\n <div>\n <label class = \"checkbox-inline\">\n <input type = \"checkbox\" id = \"inlineCheckbox1\" value = \"option1\"> NetBeans IDE\n </label>\n <label class = \"checkbox-inline\">\n <input type = \"checkbox\" id = \"inlineCheckbox2\" value = \"option2\"> Eclipse IDE\n </label>\n </div>\n </body>\n</html>" } ]
Tryit Editor v3.7
CSS Style Images Tryit: Create circled image
[ { "code": null, "e": 26, "s": 9, "text": "CSS Style Images" } ]
An Introduction to the Bootstrap Method | by Lorna Yen | Towards Data Science
Bootstrap is a powerful, computer-based method for statistical inference without relying on too many assumption. The first time I applied the bootstrap method was in an A/B test project. At that time I was like using an powerful magic to form a sampling distribution just from only one sample data. No formula needed for my statistical inference. Not only that, in fact, it is widely applied in other statistical inference such as confidence interval, regression model, even the field of machine learning. That’s lead me go through some studies about bootstrap to supplement the statistical inference knowledge with more practical other than my theory mathematical statistics classes. This article is mainly focus on introducing the core concepts of Bootstrap than its application. But some embed codes will be used as a concept illustrating. We will do a introduction of Bootstrap resampling method, then illustrate the motivation of Bootstrap when it was introduced by Bradley Efron(1979), and illustrate the general idea about bootstrap. The ideas behind bootstrap, in fact, are containing so many statistic topics that needs to be concerned. However, it is a good chance to recap some statistic inference concepts! The related statistic concept covers: Basic Calculus and concept of function Mean, Variance, and Standard Deviation Distribution Function (CDF) and Probability Density Function (PDF) Sampling Distribution Central Limit Theory, Law of Large Number and Convergence in Probability Statistical Functional, Empirical Distribution Function and Plug-in Principle Having some basic knowledge above would help for gaining basic ideas behind bootstrap. Some ideas may cover with advance statistic, but I will use a simple way and not very formal mathematics expressions to illustrate basic idea as simple as I can. Links at the end of the article will be provided if you want to learn more about these concepts. The basic idea of bootstrap is make inference about a estimate(such as sample mean) for a population parameter θ (such as population mean) on sample data. It is a resampling method by independently sampling with replacement from an existing sample data with same sample size n, and performing inference among these resampled data. Generally, bootstrap involves the following steps: A sample from population with sample size n.Draw a sample from the original sample data with replacement with size n, and replicate B times, each re-sampled sample is called a Bootstrap Sample, and there will totally B Bootstrap Samples.Evaluate the statistic of θ for each Bootstrap Sample, and there will be totally B estimates of θ.Construct a sampling distribution with these B Bootstrap statistics and use it to make further statistical inference, such as: A sample from population with sample size n. Draw a sample from the original sample data with replacement with size n, and replicate B times, each re-sampled sample is called a Bootstrap Sample, and there will totally B Bootstrap Samples. Evaluate the statistic of θ for each Bootstrap Sample, and there will be totally B estimates of θ. Construct a sampling distribution with these B Bootstrap statistics and use it to make further statistical inference, such as: Estimating the standard error of statistic for θ. Obtaining a Confidence Interval for θ. We can see we generate new data points by re-sampling from an existing sample, and make inference just based on these new data points. How and why does bootstrap work? In this article, I will divide this big question into three parts: What’s the initial motivation that Efron introduced the bootstrap?Why use the simulation technique? In other word, how can I find a estimated variance of statistic by resampling?What’s the main idea that we need to draw a sample from the original sample with replacement ? What’s the initial motivation that Efron introduced the bootstrap? Why use the simulation technique? In other word, how can I find a estimated variance of statistic by resampling? What’s the main idea that we need to draw a sample from the original sample with replacement ? The core idea of bootstrap technique is for making certain kinds of statistical inference with the help of modern computer power. When Efron introduced the method, it was particularly motivated by evaluating of the accuracy of an estimator in the field of statistic inference. Usually, estimated standard error are an first step toward thinking critically about the accuracy statistical estimates. Now, to illustrate how bootstrap works and how an estimator’s standard error plays an important role, let’s start with a simple case. Imagine that you want to summarize how many times a day do students pick up their smartphone in your lab with totally 100 students. It's hard to summarize the number of pickups in whole lab like a census way. Instead, you make a online survey which also provided the pickup-counting APP. In the next few days, you receive 30 students responses with their number of pickups in a given day. You calculated the mean of these 30 pickups and got an estimate for pickups is 228.06 times. import numpy as np import matplotlib.pyplot as plt # construct a population pickups for our lab np.random.seed(42) pickups = np.random.randint(0,500 , size=100) pickups array([102, 435, 348, 270, 106, 71, 188, 20, 102, 121, 466, 214, 330, 458, 87, 372, 99, 359, 151, 130, 149, 308, 257, 343, 491, 413, 293, 385, 191, 443, 276, 160, 459, 313, 21, 252, 235, 344, 48, 474, 58, 169, 475, 187, 463, 270, 189, 445, 174, 445, 50, 363, 54, 243, 319, 130, 484, 306, 134, 20, 328, 166, 273, 387, 88, 315, 13, 241, 264, 345, 52, 385, 339, 91, 366, 443, 454, 427, 263, 430, 34, 205, 80, 419, 49, 359, 387, 1, 389, 53, 105, 259, 309, 476, 190, 401, 217, 43, 161, 201]) # population mean pickups.mean() 252.7 # population standard deviation pickups.std() 144.25342283634035 # draw a sample from population sample = np.random.choice(pickups, size=30) sample array([166, 201, 458, 190, 445, 87, 385, 427, 387, 166, 474, 49, 430, 205, 54, 343, 413, 389, 20, 58, 191, 87, 463, 88, 389, 52, 102, 1, 102, 20]) # our first sample mean sample_mean = sample.mean() sample_mean 228.06666666666666 # standard deiveation for this sample sample_std = np.std(sample, ddof=1) sample_std 166.96890756052164 # estimated standard error for the sapmle mann sample_std/(30 ** 0.5) 30.48421235763086 In statistic field, the process above is called a point estimate. What we would like to know is the true number of pickups in whole lab. We don’t have census data, what we can do is just evaluate the population parameter through an estimator based on an observed sample, and then get an estimate as the evaluation of average smartphone usage in the lab. Estimator/Statistic: A rule for calculating an estimate. In this case is Sample mean, always denoted as X̄. Population Parameter: Numeric summary about a population. In this case is the average time of phone pickups per day in our lab, always denoted as μ. One key question is — How accurate is this estimate result? Because of the sampling variability, it is virtually never that X̄ = μ occurs. Hence, besides reporting the value of a point estimate, some indication about the precision should be given. The common measure of accuracy is the standard error of the estimate. The standard error of an estimator is it’s standard deviation. It tells us how far your sample estimate deviates from the actual parameter. If the standard error itself involves unknown parameters, we used the estimated standard error by replacing the unknown parameters with an estimate of the parameters. Let’s take an example. In our case, our estimator is sample mean, and for sample mean(and nearly only one!), we have an simple formula to easily obtain it’s standard error. However, the standard deviation of population σ is always unknown in real world, so the most common measurement is the estimated standard error, which use the sample standard deviation S as a estimated standard deviation of the population: In our case, we have sample with 30, and sample mean is 228.06, and the sample standard deviation is 166.97, so our estimated standard error for our sample mean is 166.97/ √30 = 30.48. Now we have got our estimated standard error. How can the standard error be used in the statistic inference? Let’s use a simple example to illustrate. Roughly speaking, if a estimator has a normal distribution or a approximately a normal distributed, then we expect that our estimate to be less than one standard error away from its expectation about 68% of the time, and less than two standard errors away about 95% of the time. In our case, recall that the sample we collected is 30 response sample, which is sufficiently large in thumb rule, the Central Limit Theorem tells us the sampling distribution of X̄ is closely approximated to a normal distribution. Combining the estimated standard error that, we can get: We can be reasonably confident that the true of μ, the the average times a day do students pick up their smartphone in our lab, lies within approximately 2 standard error of X̄, which is (228.06 −2×30.48, 228.06+2×30.48) = (167.1, 289.02). We have made our statistic inference. However, how this inference was going well is under some rigorous assumptions. Let’s recall what assumption or classical theorem we may have used so far: An standard error of our sample mean can be easily estimated, which we have used standard deviation of sample as estimator and a simple formula to obtain the estimated standard error. We assume we know or can estimate about the estimator’s population. In our case is the approximated normal distribution. However, in our real world, sometimes it’s hard to meet assumptions or theorem like above: It’s hard to know the information about population, or it’s distribution. The standard error of a estimate is hard to evaluate in general. Most of time, there is no a precise formula like standard error of sample mean. If now, we want to make a inference for the median of the smart phone pickups, what’s the standard error of sample median? This is why the bootstrap comes in to address these kind of problems. When these assumptions are violated, or when no formula exists for estimating standard errors , bootstrap is the powerful choice. To illustrate the main concepts, following explanation will evolve some mathematics definition and denotation, which are kind of informal in order to provide more intuition and understanding. Assume we want to estimate the standard error of our statistic to make an inference about population parameter, such as for constructing the corresponding confidence interval (just like what we have done before!). And: We don’t know anything about population. There is no precise formula for estimating the standard error of statistic. Let X1, X2, ... , Xn be a random sample from a population P with distribution function F. And let M= g(X1, X2, ..., Xn), be our statistic for parameter of interest, meaning that the statistics a function of sample data X1, X2, ..., Xn. What we want to know is the variance of M, denoted as Var(M). First, since we don’t know anything about population, we can’t determine the value of Var(M) that requires known parameter of population, so we need to estimate Var(M) with a estimated standard error , denoted as EST_Var(M). (Remember the estimated standard error of sample mean?) Second, in real world we always don’t have a simple formula for evaluating the EST_Var(M) other than the sample mean’s. It leads us need to approximate the EST_Var(M). How? Before answer this , let’s introduce an common practical way is simulation, assume we know P. Let’s talk about the idea of simulation. It’s useful for obtaining information about a statistic’s sampling distribution with the aid of computers. But it has an important assumption — Assume we know the population P. Now let X1, X2, ... , Xn be a random sample from a population and assume M= g(X1, X2, ..., Xn) is the statistic of interest, we could approximate mean and variance of statistic M by simulation as follows: Draw random sample with size n from P.Compute statistic for the sample.Replicate B times for process 1. and 2 and get B statistics.Get the mean and variance for these B statistics. Draw random sample with size n from P. Compute statistic for the sample. Replicate B times for process 1. and 2 and get B statistics. Get the mean and variance for these B statistics. Why does this simulation works? Since by a classical theorem, the Law of Large Numbers: The mean of these B statistic converges to the true mean of statistic M as B → ∞. And by Law of Large Numbers and several theorem related to Convergence in Probability: The sample variance of these B statistic converges to the true variance of statistic M as B → ∞. With the aid of computer, we can make B as large as we like to approximate to the sampling distribution of statistic M. Following is the example Python codes for simulation in the previous phone-picks case. I use B=100000, and the simulated mean and standard error for sample mean is very close to the theoretical results in the last two cells. Feel free to check out. We have learned the idea of simulation. Now, can we approximate the EST_Var(M) by simulation? Unfortunately, to do the simulation above, we need to know the information about population P. The truth is that we don’t know anything about the P. For addressing this issue, one of most important component in bootstrap Method is adopted: Using Empirical distribution function to approximate the distribution function of population, and applying Plug-in Principle to get an estimate for Var(M) — the Plug-in estimator. The idea of Empirical distribution function (EDF) is building an distribution function (CDF) from an existing data set. The EDF usually approximates the CDF quite well, especially for large sample size. In fact, it is a common, useful method for estimating a CDF of a random variable in pratical. The EDF is a discrete distribution that gives equal weight to each data point (i.e., it assigns probability 1/ n to each of the original n observations), and form a cumulative distribution function that is a step function that jumps up by 1/n at each of the n data points. Bootstrap use the EDF as an estimator for CDF of population. However, we know the EDF is a type of cumulative distribution function(CDF). To apply the EDF as an estimator for our statistic M, we need to make the form of M as a function of CDF type, even the parameter of interest as well to have the some base line. To do this, a common way is the concept called Statistical Functional. Roughly speaking, a statistical functional is any function of a distribution function. Let’s take an example: Suppose we are interested in parameters of population. In statistic field , there is always a situation where parameters of interest is a function of the distribution function, these are called statistical functionals. Following list that population mean E(X) is a statistical functional: From above we can see the mean of population E(X) can also be expressed as a form of CDF of population F — this is a statistical functional. Of course, this expression can be applied to any function other than mean, such as variance. Statistical functional can be viewed as quantity describing the features of the population. The mean, variance, median, quantiles of F are features of population. Thus, using statistical functional, we have a more rigorous way to define the concepts of population parameters. Therefore, we can say, our statistic M can be : M=g(F), with the population CDF F. We have made our statistic is M= g(X1, X2, ..., Xn)=g(F) be a statistical functional form. However, we don’t know F. So we have to “plug-in” a estimator for F, “into” our M=g(F), in order to make this M can be evaluate. It is called plug-in principle. Generally speaking, the plug-in principle is a method of estimation of statistical functionals from a population distribution by evaluating the same functionals, but with the empirical distribution which is based on the sample. This estimation is called a plug-in estimate for the population parameter of interest. For example, a median of a population distribution can be approximated by the median of the empirical distribution of a sample. The empirical distribution here, is form just by the sample because we don’t know population. Put it simply: If our parameter of interest , say θ, has the statistical function form θ=g(F), which F is population CDF. The plug-in estimator for θ=g(F), is defined to be θ_hat=g(F_hat): From above formula we can see we “plug in” the θ_hat and F_hat for the unknown θ and F. F_hat here, is purely estimated by sample data. Note that both of the θ and θ_hat are determined by the same function g(.). Let’s take an mean example as follows, we can see g(.) for mean is — averaging all data points, and it is also applied for sample mean. F_hat here, is form by sample as an estimator of F. We say the sample mean is a plug-in estimator of the population mean.(A more clear result will be provided soon.) So, what is the F_hat? Remember bootstrap use Empirical distribution function(EDF) as an estimator of CDF of population? In fact, EDF is also a common estimator that be widely used in plug-in principle for F_hat. Let’s take a look what does our estimator M= g(X1, X2, ..., Xn)=g(F) will look like if we plug-in with EDF into it. Let Statistic of interest be M=g(X1, X2, ..., Xn)= g(F) from a population CDF F. We don’t know F, so we build a Plug-in estimator for M, M becomes M_hat= g(F_hat). Let’s rewrite M_hat as follows: We know EDF is a discrete distribution that with probability mass function PMF assigns probability 1/ n to each of the n observations, so according this, M_hat becomes: According this, for our mean example, we can find the plug-in estimator for mean μ is just the sample mean: Hence, we through Plug-in Principle, to make an estimate for M=g(F), say M_hat=g(F_hat). And remember that, what we want to find out is Var(M), and we approximate Var(M) by Var(M_hat). But in general case, there is no precise formula for Var(M_hat) other than sample mean! It leads us to apply a simulation. It’s nearly the last step! Let’s refresh the whole process with the Plug-in Principle concept. Our goal is to estimate the variance of our estimator M, which is Var(M). The Bootstrap principle is as follows: We don’t know the population P with CDF denoted as F, so bootstrap use Empirical distribution function(EDF) as estimate of F.Using our existing sample data to form a EDF as a estimated population.Applied the Plug-in Principle to make M=g(F) can be evaluate with EDF. Hence, M=g(F) becomes M_hat= g(F_hat), it’s the plugged-in estimator with EDF — F_hat.Take simulation to approximate to the Var(M_hat). We don’t know the population P with CDF denoted as F, so bootstrap use Empirical distribution function(EDF) as estimate of F. Using our existing sample data to form a EDF as a estimated population. Applied the Plug-in Principle to make M=g(F) can be evaluate with EDF. Hence, M=g(F) becomes M_hat= g(F_hat), it’s the plugged-in estimator with EDF — F_hat. Take simulation to approximate to the Var(M_hat). Recall that to do the original version of simulation, we need to draw a sample data from population, obtain a statistic M=g(F) from it, and replicate the procedure B times, then get variance of these B statistic to approximate the true variance of statistic. Therefore, to do simulation in step 4, we need to: Draw a sample data from EDF.Obtain a plug-in statistic M_hat= g(F_hat).Replicate the two procedure B times.Get the variance of these B statistic, to approximate the true variance of plug-in statistic.(It’s an easily confused part.) Draw a sample data from EDF. Obtain a plug-in statistic M_hat= g(F_hat). Replicate the two procedure B times. Get the variance of these B statistic, to approximate the true variance of plug-in statistic.(It’s an easily confused part.) What’s the simulation? In fact, it is the bootstrap sampling process that we mentioned in the beginning of this article! Two questions here(I promise these are last two!): How does draw from EDF look like in step 1?How does this simulation work? How does draw from EDF look like in step 1? How does this simulation work? We know EDF builds an CDF from existing sample data X1, ..., Xn, and by definition it puts mass 1/n at each sample data point. Therefore, drawing an random sample from an EDF, can be seen as drawing n observations, with replacement, from our existing sample data X1, ..., Xn. So that’s why the bootstrap sample is sampled with replacement as shown before. The variance of plug-in estimator M_hat=g(F_hat) is what the bootstrap simulation want to simulate. At the beginning of simulation, we draw observations with replacement from our existing sample data X1, ..., Xn. Let’s denote these re-sampled data X1* , ..., Xn*. Now, let’s compare bootstrap simulation with our original simulation version again . Original simulation process for Var(M=g(F)): Original Simulation Version- Approximate EST_Var(M|F) with known FLet X1, X2, ... , Xn be a random sample from a population P and assume M= g(X1, X2, ..., Xn) is the statistic of interest, we could approximate variance of statistic M by simulation as follows:1. Draw random sample with size n from P.2. Compute statistic for the sample.3. Replicate B times for process 1. and 2 and get B statistics.4. Get the variance for these B statistics. Bootstrap Simulation for Var(M_hat=g(F_hat)) Bootstrap Simulation Version- Approximate Var(M_hat|F_hat) with EDFNow let X1, X2, ... , Xn be a random sample from a population P with CDF F, and assume M= g(X1, X2, ..., Xn ;F) is the statistic of interest. But we don't know F, so we:1.Form a EDF from the existing sample data by draw observations with replacement from our existing sample data X1, ..., Xn. These are denote as X1*, X2*, ..., Xn*. We call this is a bootstrap sample.2.Compute statistic M_hat= g(X1*, X2*, ..., Xn* ;F_hat) for the bootstrap sample.3. Replicate B times for steps 2 and 3, and get B statistics M_hat.4. Get the variance for these B statistics to approximate the Var(M_hat). Would you feel familiar with processes above? In fact, it’s the same process with bootstrap sampling method we have mentioned before! Finally, let’s check out how does our simulation will work. What we will get the approximation from this bootstrap simulation is for Var(M_hat), but what we really concern is whether Var(M_hat) can approximate to Var(M). So two question here: Will bootstrap variance simulation result, which is S2, can approximate well for Var(M_hat)?Can Var(M_hat) can approximate to Var(M)? Will bootstrap variance simulation result, which is S2, can approximate well for Var(M_hat)? Can Var(M_hat) can approximate to Var(M)? To answer this ,let’s use a diagram to illustrate the both types simulation error: From bootstrap variance estimation, we will get an estimate for Var(M_hat) — the plug-in estimate for Var(M). And the Law of Large Number tell us, if our simulation times B is large enough, the bootstrap variance estimation S2, is a good approximate for Var(M_hat). Fortunately, we can get a larger B as we like with aid of a computer. So this simulation error can be small.The Variance of M_hat, is the plug-in estimate for variance of M from true F. Is the Var(M_hat; F_hat) a good estimator for Var(M; F)? In other words, does a plug-in estimator approximate well to the estimator of interest ? That’s the key point what we really concern. In fact, the topic of asymptotic properties for plug-in estimators is classified in high level mathematical statistic. But let’s explain the main issues and ideas. From bootstrap variance estimation, we will get an estimate for Var(M_hat) — the plug-in estimate for Var(M). And the Law of Large Number tell us, if our simulation times B is large enough, the bootstrap variance estimation S2, is a good approximate for Var(M_hat). Fortunately, we can get a larger B as we like with aid of a computer. So this simulation error can be small. The Variance of M_hat, is the plug-in estimate for variance of M from true F. Is the Var(M_hat; F_hat) a good estimator for Var(M; F)? In other words, does a plug-in estimator approximate well to the estimator of interest ? That’s the key point what we really concern. In fact, the topic of asymptotic properties for plug-in estimators is classified in high level mathematical statistic. But let’s explain the main issues and ideas. First, We know the empirical distribution will converges to true distribution function well if sample size is large, say F_hat → F. Second, if F_hat → F, and if it’s corresponding statistical function g(.) is a smoothness conditions, then g(F_hat) → g(F). In our case, the statistical function g(.) is Variance, which satisfy the required continuity conditions. Therefore, that explains why the bootstrap variance is a good estimate of the true variance of the estimator M. Generally, the smoothness conditions on some functionals is difficult to verify. Fortunately, most common statistical functions like mean, variance or moments satisfy the required continuity conditions. It provides that bootstrapping works. And of course, make the original sample size not too small as we can. Below is my Bootstrap sample code for pickup case, fell free to check out. Let’s recap the main ideas of bootstrap with following diagram! So far I know it’s not easy with tons of statistical concepts. But understanding basic concepts behind a method can make us in a right direction when apply it. After all, Bootstrap has been applied to a much wider level of practical cases, it is more constructive to learn start from the basic part. Thanks for reading so far and hope this article helps! Leave your comments if I’ve made any mistakes :) ! Most helpful book by Efron, with more general concept of Bootstrap and how it connects to statistical inference. An Introduction to the Bootstrap Also a helpful book, form EDF to Bootstrap method All of Statistics: A Concise Course in Statistical Inference Other book: Bootstrap Methods And Their Application An Introduction to Bootstrap Methods with Applications to R Empirical Distribution Function and Plug-in Principle
[ { "code": null, "e": 857, "s": 172, "text": "Bootstrap is a powerful, computer-based method for statistical inference without relying on too many assumption. The first time I applied the bootstrap method was in an A/B test project. At that time I was like using an powerful magic to form a sampling distribution just from only one sample data. No formula needed for my statistical inference. Not only that, in fact, it is widely applied in other statistical inference such as confidence interval, regression model, even the field of machine learning. That’s lead me go through some studies about bootstrap to supplement the statistical inference knowledge with more practical other than my theory mathematical statistics classes." }, { "code": null, "e": 1213, "s": 857, "text": "This article is mainly focus on introducing the core concepts of Bootstrap than its application. But some embed codes will be used as a concept illustrating. We will do a introduction of Bootstrap resampling method, then illustrate the motivation of Bootstrap when it was introduced by Bradley Efron(1979), and illustrate the general idea about bootstrap." }, { "code": null, "e": 1429, "s": 1213, "text": "The ideas behind bootstrap, in fact, are containing so many statistic topics that needs to be concerned. However, it is a good chance to recap some statistic inference concepts! The related statistic concept covers:" }, { "code": null, "e": 1468, "s": 1429, "text": "Basic Calculus and concept of function" }, { "code": null, "e": 1507, "s": 1468, "text": "Mean, Variance, and Standard Deviation" }, { "code": null, "e": 1574, "s": 1507, "text": "Distribution Function (CDF) and Probability Density Function (PDF)" }, { "code": null, "e": 1596, "s": 1574, "text": "Sampling Distribution" }, { "code": null, "e": 1669, "s": 1596, "text": "Central Limit Theory, Law of Large Number and Convergence in Probability" }, { "code": null, "e": 1747, "s": 1669, "text": "Statistical Functional, Empirical Distribution Function and Plug-in Principle" }, { "code": null, "e": 2093, "s": 1747, "text": "Having some basic knowledge above would help for gaining basic ideas behind bootstrap. Some ideas may cover with advance statistic, but I will use a simple way and not very formal mathematics expressions to illustrate basic idea as simple as I can. Links at the end of the article will be provided if you want to learn more about these concepts." }, { "code": null, "e": 2424, "s": 2093, "text": "The basic idea of bootstrap is make inference about a estimate(such as sample mean) for a population parameter θ (such as population mean) on sample data. It is a resampling method by independently sampling with replacement from an existing sample data with same sample size n, and performing inference among these resampled data." }, { "code": null, "e": 2475, "s": 2424, "text": "Generally, bootstrap involves the following steps:" }, { "code": null, "e": 2937, "s": 2475, "text": "A sample from population with sample size n.Draw a sample from the original sample data with replacement with size n, and replicate B times, each re-sampled sample is called a Bootstrap Sample, and there will totally B Bootstrap Samples.Evaluate the statistic of θ for each Bootstrap Sample, and there will be totally B estimates of θ.Construct a sampling distribution with these B Bootstrap statistics and use it to make further statistical inference, such as:" }, { "code": null, "e": 2982, "s": 2937, "text": "A sample from population with sample size n." }, { "code": null, "e": 3176, "s": 2982, "text": "Draw a sample from the original sample data with replacement with size n, and replicate B times, each re-sampled sample is called a Bootstrap Sample, and there will totally B Bootstrap Samples." }, { "code": null, "e": 3275, "s": 3176, "text": "Evaluate the statistic of θ for each Bootstrap Sample, and there will be totally B estimates of θ." }, { "code": null, "e": 3402, "s": 3275, "text": "Construct a sampling distribution with these B Bootstrap statistics and use it to make further statistical inference, such as:" }, { "code": null, "e": 3452, "s": 3402, "text": "Estimating the standard error of statistic for θ." }, { "code": null, "e": 3491, "s": 3452, "text": "Obtaining a Confidence Interval for θ." }, { "code": null, "e": 3626, "s": 3491, "text": "We can see we generate new data points by re-sampling from an existing sample, and make inference just based on these new data points." }, { "code": null, "e": 3659, "s": 3626, "text": "How and why does bootstrap work?" }, { "code": null, "e": 3726, "s": 3659, "text": "In this article, I will divide this big question into three parts:" }, { "code": null, "e": 3999, "s": 3726, "text": "What’s the initial motivation that Efron introduced the bootstrap?Why use the simulation technique? In other word, how can I find a estimated variance of statistic by resampling?What’s the main idea that we need to draw a sample from the original sample with replacement ?" }, { "code": null, "e": 4066, "s": 3999, "text": "What’s the initial motivation that Efron introduced the bootstrap?" }, { "code": null, "e": 4179, "s": 4066, "text": "Why use the simulation technique? In other word, how can I find a estimated variance of statistic by resampling?" }, { "code": null, "e": 4274, "s": 4179, "text": "What’s the main idea that we need to draw a sample from the original sample with replacement ?" }, { "code": null, "e": 4672, "s": 4274, "text": "The core idea of bootstrap technique is for making certain kinds of statistical inference with the help of modern computer power. When Efron introduced the method, it was particularly motivated by evaluating of the accuracy of an estimator in the field of statistic inference. Usually, estimated standard error are an first step toward thinking critically about the accuracy statistical estimates." }, { "code": null, "e": 4806, "s": 4672, "text": "Now, to illustrate how bootstrap works and how an estimator’s standard error plays an important role, let’s start with a simple case." }, { "code": null, "e": 5288, "s": 4806, "text": "Imagine that you want to summarize how many times a day do students pick up their smartphone in your lab with totally 100 students. It's hard to summarize the number of pickups in whole lab like a census way. Instead, you make a online survey which also provided the pickup-counting APP. In the next few days, you receive 30 students responses with their number of pickups in a given day. You calculated the mean of these 30 pickups and got an estimate for pickups is 228.06 times." }, { "code": null, "e": 5340, "s": 5288, "text": "import numpy as np\nimport matplotlib.pyplot as plt\n" }, { "code": null, "e": 5459, "s": 5340, "text": "# construct a population pickups for our lab\nnp.random.seed(42)\npickups = np.random.randint(0,500 , size=100)\npickups\n" }, { "code": null, "e": 6016, "s": 5459, "text": "array([102, 435, 348, 270, 106, 71, 188, 20, 102, 121, 466, 214, 330,\n 458, 87, 372, 99, 359, 151, 130, 149, 308, 257, 343, 491, 413,\n 293, 385, 191, 443, 276, 160, 459, 313, 21, 252, 235, 344, 48,\n 474, 58, 169, 475, 187, 463, 270, 189, 445, 174, 445, 50, 363,\n 54, 243, 319, 130, 484, 306, 134, 20, 328, 166, 273, 387, 88,\n 315, 13, 241, 264, 345, 52, 385, 339, 91, 366, 443, 454, 427,\n 263, 430, 34, 205, 80, 419, 49, 359, 387, 1, 389, 53, 105,\n 259, 309, 476, 190, 401, 217, 43, 161, 201])" }, { "code": null, "e": 6050, "s": 6016, "text": "# population mean\npickups.mean()\n" }, { "code": null, "e": 6056, "s": 6050, "text": "252.7" }, { "code": null, "e": 6103, "s": 6056, "text": "# population standard deviation\npickups.std()\n" }, { "code": null, "e": 6122, "s": 6103, "text": "144.25342283634035" }, { "code": null, "e": 6206, "s": 6122, "text": "# draw a sample from population\nsample = np.random.choice(pickups, size=30)\nsample\n" }, { "code": null, "e": 6378, "s": 6206, "text": "array([166, 201, 458, 190, 445, 87, 385, 427, 387, 166, 474, 49, 430,\n 205, 54, 343, 413, 389, 20, 58, 191, 87, 463, 88, 389, 52,\n 102, 1, 102, 20])" }, { "code": null, "e": 6443, "s": 6378, "text": "# our first sample mean\nsample_mean = sample.mean()\nsample_mean\n" }, { "code": null, "e": 6462, "s": 6443, "text": "228.06666666666666" }, { "code": null, "e": 6548, "s": 6462, "text": "# standard deiveation for this sample\nsample_std = np.std(sample, ddof=1)\nsample_std\n" }, { "code": null, "e": 6567, "s": 6548, "text": "166.96890756052164" }, { "code": null, "e": 6638, "s": 6567, "text": "# estimated standard error for the sapmle mann\nsample_std/(30 ** 0.5)\n" }, { "code": null, "e": 6656, "s": 6638, "text": "30.48421235763086" }, { "code": null, "e": 7013, "s": 6659, "text": "In statistic field, the process above is called a point estimate. What we would like to know is the true number of pickups in whole lab. We don’t have census data, what we can do is just evaluate the population parameter through an estimator based on an observed sample, and then get an estimate as the evaluation of average smartphone usage in the lab." }, { "code": null, "e": 7121, "s": 7013, "text": "Estimator/Statistic: A rule for calculating an estimate. In this case is Sample mean, always denoted as X̄." }, { "code": null, "e": 7270, "s": 7121, "text": "Population Parameter: Numeric summary about a population. In this case is the average time of phone pickups per day in our lab, always denoted as μ." }, { "code": null, "e": 7330, "s": 7270, "text": "One key question is — How accurate is this estimate result?" }, { "code": null, "e": 7588, "s": 7330, "text": "Because of the sampling variability, it is virtually never that X̄ = μ occurs. Hence, besides reporting the value of a point estimate, some indication about the precision should be given. The common measure of accuracy is the standard error of the estimate." }, { "code": null, "e": 7895, "s": 7588, "text": "The standard error of an estimator is it’s standard deviation. It tells us how far your sample estimate deviates from the actual parameter. If the standard error itself involves unknown parameters, we used the estimated standard error by replacing the unknown parameters with an estimate of the parameters." }, { "code": null, "e": 8068, "s": 7895, "text": "Let’s take an example. In our case, our estimator is sample mean, and for sample mean(and nearly only one!), we have an simple formula to easily obtain it’s standard error." }, { "code": null, "e": 8308, "s": 8068, "text": "However, the standard deviation of population σ is always unknown in real world, so the most common measurement is the estimated standard error, which use the sample standard deviation S as a estimated standard deviation of the population:" }, { "code": null, "e": 8493, "s": 8308, "text": "In our case, we have sample with 30, and sample mean is 228.06, and the sample standard deviation is 166.97, so our estimated standard error for our sample mean is 166.97/ √30 = 30.48." }, { "code": null, "e": 8644, "s": 8493, "text": "Now we have got our estimated standard error. How can the standard error be used in the statistic inference? Let’s use a simple example to illustrate." }, { "code": null, "e": 8923, "s": 8644, "text": "Roughly speaking, if a estimator has a normal distribution or a approximately a normal distributed, then we expect that our estimate to be less than one standard error away from its expectation about 68% of the time, and less than two standard errors away about 95% of the time." }, { "code": null, "e": 9212, "s": 8923, "text": "In our case, recall that the sample we collected is 30 response sample, which is sufficiently large in thumb rule, the Central Limit Theorem tells us the sampling distribution of X̄ is closely approximated to a normal distribution. Combining the estimated standard error that, we can get:" }, { "code": null, "e": 9452, "s": 9212, "text": "We can be reasonably confident that the true of μ, the the average times a day do students pick up their smartphone in our lab, lies within approximately 2 standard error of X̄, which is (228.06 −2×30.48, 228.06+2×30.48) = (167.1, 289.02)." }, { "code": null, "e": 9569, "s": 9452, "text": "We have made our statistic inference. However, how this inference was going well is under some rigorous assumptions." }, { "code": null, "e": 9644, "s": 9569, "text": "Let’s recall what assumption or classical theorem we may have used so far:" }, { "code": null, "e": 9828, "s": 9644, "text": "An standard error of our sample mean can be easily estimated, which we have used standard deviation of sample as estimator and a simple formula to obtain the estimated standard error." }, { "code": null, "e": 9949, "s": 9828, "text": "We assume we know or can estimate about the estimator’s population. In our case is the approximated normal distribution." }, { "code": null, "e": 10040, "s": 9949, "text": "However, in our real world, sometimes it’s hard to meet assumptions or theorem like above:" }, { "code": null, "e": 10114, "s": 10040, "text": "It’s hard to know the information about population, or it’s distribution." }, { "code": null, "e": 10382, "s": 10114, "text": "The standard error of a estimate is hard to evaluate in general. Most of time, there is no a precise formula like standard error of sample mean. If now, we want to make a inference for the median of the smart phone pickups, what’s the standard error of sample median?" }, { "code": null, "e": 10582, "s": 10382, "text": "This is why the bootstrap comes in to address these kind of problems. When these assumptions are violated, or when no formula exists for estimating standard errors , bootstrap is the powerful choice." }, { "code": null, "e": 10774, "s": 10582, "text": "To illustrate the main concepts, following explanation will evolve some mathematics definition and denotation, which are kind of informal in order to provide more intuition and understanding." }, { "code": null, "e": 10993, "s": 10774, "text": "Assume we want to estimate the standard error of our statistic to make an inference about population parameter, such as for constructing the corresponding confidence interval (just like what we have done before!). And:" }, { "code": null, "e": 11034, "s": 10993, "text": "We don’t know anything about population." }, { "code": null, "e": 11110, "s": 11034, "text": "There is no precise formula for estimating the standard error of statistic." }, { "code": null, "e": 11408, "s": 11110, "text": "Let X1, X2, ... , Xn be a random sample from a population P with distribution function F. And let M= g(X1, X2, ..., Xn), be our statistic for parameter of interest, meaning that the statistics a function of sample data X1, X2, ..., Xn. What we want to know is the variance of M, denoted as Var(M)." }, { "code": null, "e": 11689, "s": 11408, "text": "First, since we don’t know anything about population, we can’t determine the value of Var(M) that requires known parameter of population, so we need to estimate Var(M) with a estimated standard error , denoted as EST_Var(M). (Remember the estimated standard error of sample mean?)" }, { "code": null, "e": 11809, "s": 11689, "text": "Second, in real world we always don’t have a simple formula for evaluating the EST_Var(M) other than the sample mean’s." }, { "code": null, "e": 11956, "s": 11809, "text": "It leads us need to approximate the EST_Var(M). How? Before answer this , let’s introduce an common practical way is simulation, assume we know P." }, { "code": null, "e": 12174, "s": 11956, "text": "Let’s talk about the idea of simulation. It’s useful for obtaining information about a statistic’s sampling distribution with the aid of computers. But it has an important assumption — Assume we know the population P." }, { "code": null, "e": 12379, "s": 12174, "text": "Now let X1, X2, ... , Xn be a random sample from a population and assume M= g(X1, X2, ..., Xn) is the statistic of interest, we could approximate mean and variance of statistic M by simulation as follows:" }, { "code": null, "e": 12560, "s": 12379, "text": "Draw random sample with size n from P.Compute statistic for the sample.Replicate B times for process 1. and 2 and get B statistics.Get the mean and variance for these B statistics." }, { "code": null, "e": 12599, "s": 12560, "text": "Draw random sample with size n from P." }, { "code": null, "e": 12633, "s": 12599, "text": "Compute statistic for the sample." }, { "code": null, "e": 12694, "s": 12633, "text": "Replicate B times for process 1. and 2 and get B statistics." }, { "code": null, "e": 12744, "s": 12694, "text": "Get the mean and variance for these B statistics." }, { "code": null, "e": 12832, "s": 12744, "text": "Why does this simulation works? Since by a classical theorem, the Law of Large Numbers:" }, { "code": null, "e": 12914, "s": 12832, "text": "The mean of these B statistic converges to the true mean of statistic M as B → ∞." }, { "code": null, "e": 13001, "s": 12914, "text": "And by Law of Large Numbers and several theorem related to Convergence in Probability:" }, { "code": null, "e": 13098, "s": 13001, "text": "The sample variance of these B statistic converges to the true variance of statistic M as B → ∞." }, { "code": null, "e": 13218, "s": 13098, "text": "With the aid of computer, we can make B as large as we like to approximate to the sampling distribution of statistic M." }, { "code": null, "e": 13467, "s": 13218, "text": "Following is the example Python codes for simulation in the previous phone-picks case. I use B=100000, and the simulated mean and standard error for sample mean is very close to the theoretical results in the last two cells. Feel free to check out." }, { "code": null, "e": 13801, "s": 13467, "text": "We have learned the idea of simulation. Now, can we approximate the EST_Var(M) by simulation? Unfortunately, to do the simulation above, we need to know the information about population P. The truth is that we don’t know anything about the P. For addressing this issue, one of most important component in bootstrap Method is adopted:" }, { "code": null, "e": 13981, "s": 13801, "text": "Using Empirical distribution function to approximate the distribution function of population, and applying Plug-in Principle to get an estimate for Var(M) — the Plug-in estimator." }, { "code": null, "e": 14278, "s": 13981, "text": "The idea of Empirical distribution function (EDF) is building an distribution function (CDF) from an existing data set. The EDF usually approximates the CDF quite well, especially for large sample size. In fact, it is a common, useful method for estimating a CDF of a random variable in pratical." }, { "code": null, "e": 14551, "s": 14278, "text": "The EDF is a discrete distribution that gives equal weight to each data point (i.e., it assigns probability 1/ n to each of the original n observations), and form a cumulative distribution function that is a step function that jumps up by 1/n at each of the n data points." }, { "code": null, "e": 15048, "s": 14551, "text": "Bootstrap use the EDF as an estimator for CDF of population. However, we know the EDF is a type of cumulative distribution function(CDF). To apply the EDF as an estimator for our statistic M, we need to make the form of M as a function of CDF type, even the parameter of interest as well to have the some base line. To do this, a common way is the concept called Statistical Functional. Roughly speaking, a statistical functional is any function of a distribution function. Let’s take an example:" }, { "code": null, "e": 15337, "s": 15048, "text": "Suppose we are interested in parameters of population. In statistic field , there is always a situation where parameters of interest is a function of the distribution function, these are called statistical functionals. Following list that population mean E(X) is a statistical functional:" }, { "code": null, "e": 15571, "s": 15337, "text": "From above we can see the mean of population E(X) can also be expressed as a form of CDF of population F — this is a statistical functional. Of course, this expression can be applied to any function other than mean, such as variance." }, { "code": null, "e": 15930, "s": 15571, "text": "Statistical functional can be viewed as quantity describing the features of the population. The mean, variance, median, quantiles of F are features of population. Thus, using statistical functional, we have a more rigorous way to define the concepts of population parameters. Therefore, we can say, our statistic M can be : M=g(F), with the population CDF F." }, { "code": null, "e": 16150, "s": 15930, "text": "We have made our statistic is M= g(X1, X2, ..., Xn)=g(F) be a statistical functional form. However, we don’t know F. So we have to “plug-in” a estimator for F, “into” our M=g(F), in order to make this M can be evaluate." }, { "code": null, "e": 16734, "s": 16150, "text": "It is called plug-in principle. Generally speaking, the plug-in principle is a method of estimation of statistical functionals from a population distribution by evaluating the same functionals, but with the empirical distribution which is based on the sample. This estimation is called a plug-in estimate for the population parameter of interest. For example, a median of a population distribution can be approximated by the median of the empirical distribution of a sample. The empirical distribution here, is form just by the sample because we don’t know population. Put it simply:" }, { "code": null, "e": 16841, "s": 16734, "text": "If our parameter of interest , say θ, has the statistical function form θ=g(F), which F is population CDF." }, { "code": null, "e": 16908, "s": 16841, "text": "The plug-in estimator for θ=g(F), is defined to be θ_hat=g(F_hat):" }, { "code": null, "e": 17044, "s": 16908, "text": "From above formula we can see we “plug in” the θ_hat and F_hat for the unknown θ and F. F_hat here, is purely estimated by sample data." }, { "code": null, "e": 17120, "s": 17044, "text": "Note that both of the θ and θ_hat are determined by the same function g(.)." }, { "code": null, "e": 17422, "s": 17120, "text": "Let’s take an mean example as follows, we can see g(.) for mean is — averaging all data points, and it is also applied for sample mean. F_hat here, is form by sample as an estimator of F. We say the sample mean is a plug-in estimator of the population mean.(A more clear result will be provided soon.)" }, { "code": null, "e": 17635, "s": 17422, "text": "So, what is the F_hat? Remember bootstrap use Empirical distribution function(EDF) as an estimator of CDF of population? In fact, EDF is also a common estimator that be widely used in plug-in principle for F_hat." }, { "code": null, "e": 17751, "s": 17635, "text": "Let’s take a look what does our estimator M= g(X1, X2, ..., Xn)=g(F) will look like if we plug-in with EDF into it." }, { "code": null, "e": 17832, "s": 17751, "text": "Let Statistic of interest be M=g(X1, X2, ..., Xn)= g(F) from a population CDF F." }, { "code": null, "e": 17947, "s": 17832, "text": "We don’t know F, so we build a Plug-in estimator for M, M becomes M_hat= g(F_hat). Let’s rewrite M_hat as follows:" }, { "code": null, "e": 18116, "s": 17947, "text": "We know EDF is a discrete distribution that with probability mass function PMF assigns probability 1/ n to each of the n observations, so according this, M_hat becomes:" }, { "code": null, "e": 18224, "s": 18116, "text": "According this, for our mean example, we can find the plug-in estimator for mean μ is just the sample mean:" }, { "code": null, "e": 18532, "s": 18224, "text": "Hence, we through Plug-in Principle, to make an estimate for M=g(F), say M_hat=g(F_hat). And remember that, what we want to find out is Var(M), and we approximate Var(M) by Var(M_hat). But in general case, there is no precise formula for Var(M_hat) other than sample mean! It leads us to apply a simulation." }, { "code": null, "e": 18627, "s": 18532, "text": "It’s nearly the last step! Let’s refresh the whole process with the Plug-in Principle concept." }, { "code": null, "e": 18740, "s": 18627, "text": "Our goal is to estimate the variance of our estimator M, which is Var(M). The Bootstrap principle is as follows:" }, { "code": null, "e": 19143, "s": 18740, "text": "We don’t know the population P with CDF denoted as F, so bootstrap use Empirical distribution function(EDF) as estimate of F.Using our existing sample data to form a EDF as a estimated population.Applied the Plug-in Principle to make M=g(F) can be evaluate with EDF. Hence, M=g(F) becomes M_hat= g(F_hat), it’s the plugged-in estimator with EDF — F_hat.Take simulation to approximate to the Var(M_hat)." }, { "code": null, "e": 19269, "s": 19143, "text": "We don’t know the population P with CDF denoted as F, so bootstrap use Empirical distribution function(EDF) as estimate of F." }, { "code": null, "e": 19341, "s": 19269, "text": "Using our existing sample data to form a EDF as a estimated population." }, { "code": null, "e": 19499, "s": 19341, "text": "Applied the Plug-in Principle to make M=g(F) can be evaluate with EDF. Hence, M=g(F) becomes M_hat= g(F_hat), it’s the plugged-in estimator with EDF — F_hat." }, { "code": null, "e": 19549, "s": 19499, "text": "Take simulation to approximate to the Var(M_hat)." }, { "code": null, "e": 19808, "s": 19549, "text": "Recall that to do the original version of simulation, we need to draw a sample data from population, obtain a statistic M=g(F) from it, and replicate the procedure B times, then get variance of these B statistic to approximate the true variance of statistic." }, { "code": null, "e": 19859, "s": 19808, "text": "Therefore, to do simulation in step 4, we need to:" }, { "code": null, "e": 20091, "s": 19859, "text": "Draw a sample data from EDF.Obtain a plug-in statistic M_hat= g(F_hat).Replicate the two procedure B times.Get the variance of these B statistic, to approximate the true variance of plug-in statistic.(It’s an easily confused part.)" }, { "code": null, "e": 20120, "s": 20091, "text": "Draw a sample data from EDF." }, { "code": null, "e": 20164, "s": 20120, "text": "Obtain a plug-in statistic M_hat= g(F_hat)." }, { "code": null, "e": 20201, "s": 20164, "text": "Replicate the two procedure B times." }, { "code": null, "e": 20326, "s": 20201, "text": "Get the variance of these B statistic, to approximate the true variance of plug-in statistic.(It’s an easily confused part.)" }, { "code": null, "e": 20447, "s": 20326, "text": "What’s the simulation? In fact, it is the bootstrap sampling process that we mentioned in the beginning of this article!" }, { "code": null, "e": 20498, "s": 20447, "text": "Two questions here(I promise these are last two!):" }, { "code": null, "e": 20572, "s": 20498, "text": "How does draw from EDF look like in step 1?How does this simulation work?" }, { "code": null, "e": 20616, "s": 20572, "text": "How does draw from EDF look like in step 1?" }, { "code": null, "e": 20647, "s": 20616, "text": "How does this simulation work?" }, { "code": null, "e": 21003, "s": 20647, "text": "We know EDF builds an CDF from existing sample data X1, ..., Xn, and by definition it puts mass 1/n at each sample data point. Therefore, drawing an random sample from an EDF, can be seen as drawing n observations, with replacement, from our existing sample data X1, ..., Xn. So that’s why the bootstrap sample is sampled with replacement as shown before." }, { "code": null, "e": 21352, "s": 21003, "text": "The variance of plug-in estimator M_hat=g(F_hat) is what the bootstrap simulation want to simulate. At the beginning of simulation, we draw observations with replacement from our existing sample data X1, ..., Xn. Let’s denote these re-sampled data X1* , ..., Xn*. Now, let’s compare bootstrap simulation with our original simulation version again ." }, { "code": null, "e": 21397, "s": 21352, "text": "Original simulation process for Var(M=g(F)):" }, { "code": null, "e": 21840, "s": 21397, "text": "Original Simulation Version- Approximate EST_Var(M|F) with known FLet X1, X2, ... , Xn be a random sample from a population P and assume M= g(X1, X2, ..., Xn) is the statistic of interest, we could approximate variance of statistic M by simulation as follows:1. Draw random sample with size n from P.2. Compute statistic for the sample.3. Replicate B times for process 1. and 2 and get B statistics.4. Get the variance for these B statistics." }, { "code": null, "e": 21885, "s": 21840, "text": "Bootstrap Simulation for Var(M_hat=g(F_hat))" }, { "code": null, "e": 22542, "s": 21885, "text": "Bootstrap Simulation Version- Approximate Var(M_hat|F_hat) with EDFNow let X1, X2, ... , Xn be a random sample from a population P with CDF F, and assume M= g(X1, X2, ..., Xn ;F) is the statistic of interest. But we don't know F, so we:1.Form a EDF from the existing sample data by draw observations with replacement from our existing sample data X1, ..., Xn. These are denote as X1*, X2*, ..., Xn*. We call this is a bootstrap sample.2.Compute statistic M_hat= g(X1*, X2*, ..., Xn* ;F_hat) for the bootstrap sample.3. Replicate B times for steps 2 and 3, and get B statistics M_hat.4. Get the variance for these B statistics to approximate the Var(M_hat)." }, { "code": null, "e": 22676, "s": 22542, "text": "Would you feel familiar with processes above? In fact, it’s the same process with bootstrap sampling method we have mentioned before!" }, { "code": null, "e": 22919, "s": 22676, "text": "Finally, let’s check out how does our simulation will work. What we will get the approximation from this bootstrap simulation is for Var(M_hat), but what we really concern is whether Var(M_hat) can approximate to Var(M). So two question here:" }, { "code": null, "e": 23053, "s": 22919, "text": "Will bootstrap variance simulation result, which is S2, can approximate well for Var(M_hat)?Can Var(M_hat) can approximate to Var(M)?" }, { "code": null, "e": 23146, "s": 23053, "text": "Will bootstrap variance simulation result, which is S2, can approximate well for Var(M_hat)?" }, { "code": null, "e": 23188, "s": 23146, "text": "Can Var(M_hat) can approximate to Var(M)?" }, { "code": null, "e": 23271, "s": 23188, "text": "To answer this ,let’s use a diagram to illustrate the both types simulation error:" }, { "code": null, "e": 24078, "s": 23271, "text": "From bootstrap variance estimation, we will get an estimate for Var(M_hat) — the plug-in estimate for Var(M). And the Law of Large Number tell us, if our simulation times B is large enough, the bootstrap variance estimation S2, is a good approximate for Var(M_hat). Fortunately, we can get a larger B as we like with aid of a computer. So this simulation error can be small.The Variance of M_hat, is the plug-in estimate for variance of M from true F. Is the Var(M_hat; F_hat) a good estimator for Var(M; F)? In other words, does a plug-in estimator approximate well to the estimator of interest ? That’s the key point what we really concern. In fact, the topic of asymptotic properties for plug-in estimators is classified in high level mathematical statistic. But let’s explain the main issues and ideas." }, { "code": null, "e": 24453, "s": 24078, "text": "From bootstrap variance estimation, we will get an estimate for Var(M_hat) — the plug-in estimate for Var(M). And the Law of Large Number tell us, if our simulation times B is large enough, the bootstrap variance estimation S2, is a good approximate for Var(M_hat). Fortunately, we can get a larger B as we like with aid of a computer. So this simulation error can be small." }, { "code": null, "e": 24886, "s": 24453, "text": "The Variance of M_hat, is the plug-in estimate for variance of M from true F. Is the Var(M_hat; F_hat) a good estimator for Var(M; F)? In other words, does a plug-in estimator approximate well to the estimator of interest ? That’s the key point what we really concern. In fact, the topic of asymptotic properties for plug-in estimators is classified in high level mathematical statistic. But let’s explain the main issues and ideas." }, { "code": null, "e": 25018, "s": 24886, "text": "First, We know the empirical distribution will converges to true distribution function well if sample size is large, say F_hat → F." }, { "code": null, "e": 25360, "s": 25018, "text": "Second, if F_hat → F, and if it’s corresponding statistical function g(.) is a smoothness conditions, then g(F_hat) → g(F). In our case, the statistical function g(.) is Variance, which satisfy the required continuity conditions. Therefore, that explains why the bootstrap variance is a good estimate of the true variance of the estimator M." }, { "code": null, "e": 25671, "s": 25360, "text": "Generally, the smoothness conditions on some functionals is difficult to verify. Fortunately, most common statistical functions like mean, variance or moments satisfy the required continuity conditions. It provides that bootstrapping works. And of course, make the original sample size not too small as we can." }, { "code": null, "e": 25746, "s": 25671, "text": "Below is my Bootstrap sample code for pickup case, fell free to check out." }, { "code": null, "e": 25810, "s": 25746, "text": "Let’s recap the main ideas of bootstrap with following diagram!" }, { "code": null, "e": 26216, "s": 25810, "text": "So far I know it’s not easy with tons of statistical concepts. But understanding basic concepts behind a method can make us in a right direction when apply it. After all, Bootstrap has been applied to a much wider level of practical cases, it is more constructive to learn start from the basic part. Thanks for reading so far and hope this article helps! Leave your comments if I’ve made any mistakes :) !" }, { "code": null, "e": 26329, "s": 26216, "text": "Most helpful book by Efron, with more general concept of Bootstrap and how it connects to statistical inference." }, { "code": null, "e": 26362, "s": 26329, "text": "An Introduction to the Bootstrap" }, { "code": null, "e": 26412, "s": 26362, "text": "Also a helpful book, form EDF to Bootstrap method" }, { "code": null, "e": 26473, "s": 26412, "text": "All of Statistics: A Concise Course in Statistical Inference" }, { "code": null, "e": 26485, "s": 26473, "text": "Other book:" }, { "code": null, "e": 26525, "s": 26485, "text": "Bootstrap Methods And Their Application" }, { "code": null, "e": 26585, "s": 26525, "text": "An Introduction to Bootstrap Methods with Applications to R" } ]
Merging ONNX graphs. Join, Merge, Split, and concatenate... | by Maurits Kaptein | Towards Data Science
ONNX is getting more and more popular. While initially conceived predominantly as a file-format to simply store AI/ML models, its use has changed in recent years. Nowadays, we see many data scientist use ONNX as means to build and curate complete data processing pipelines. As the usage of ONNX grows, so does the need for good tools for creating, inspecting, and editing ONNX graphs. Luckily, a large ecosystem for ONNX is emerging; in this post we describe the ONNX join, split, merge, and concatenate functionality as offered by the sclblonnx package (curated by Scailable). Note that merging, splitting, and concatenating ONNX graphs is extremely useful when you are actively curating useful “subgraphs” of ONNX: i.e., you might have your preferred pre and post-processing steps in a data pipeline stored in ONNX format, and you want to join these subgraphs with a model you have just trained in TensorFlow or PyTorch. In this post I try to explain how this can be done. Note: I have written about ONNX editing and merging before, see https://towardsdatascience.com/creating-editing-and-merging-onnx-pipelines-897e55e98bb0. However, with the release of sclblonnx 0.1.9 the functionalities have been greatly extended. Before discussing the new merge, concat, split, and join functionalities for ONNX graphs as provided by sclblonnx 0.1.9, it is useful to provide a bit more background about ONNX graphs. At this point in the text I assume you know some of ONNX basics (if not, see this article, or this one). Thus, you know that ONNX provides a description of a directed computational graph which specifies which operations to execute on the (strongly typed) input tensors to produce the desired output tensor. And, you know that ONNX is useful for storing trained AI/ML models, and for creating data science pipelines, in a way that is platform and deployment target independent. I.e., you generally know ONNX is fun stuff. However, to understand how one can merge, slit, join, and concatenate ONNX graphs we need a bit more background. We need to both understand how edges in a graph are created, and we need to understand in a bit more detail the role of the graph’s input and output. Let’s start with the creation of edges. Although an ONNX graph is simply a directed graph, and it could thus be described by its nodes and edges, this is not how we create (nor store) an ONNX graph. When creating an ONNX graph, we do not explicitly create an adjacency matrix to identify the edges between nodes. Rather, we create nodes of some type (the different operators), each with a named input‘s and output's. This is also all that is stored in the ONNX file (which is actually just a protobuf): the file stores a list of operator types, each with their own named input(s) and output(s). The names in the end allow for the construction of the edges in the graph: If node n1 has an output named x1, and node n2 has an input named x1, a (directed)edge between n1 and n2 will be created. If subsequently another node, n3 is added, which also has a named input x1 we end up with the following graph: Thus, when merging, joining, concatenating and splitting ONNX (sub)graphs, it is quite essential to know the — in some way internal, and potentially unknown to you if you have exported to ONNX from one of various training tools — input ant output names present in the graphs that you end up combining. If the same name occurs in both graphs, carelessly merging the graphs will cause potentially unwanted edges to be drawn. If the same name occurs in both graphs, carelessly merging the graphs will cause potentially unwanted edges to be drawn. Another somewhat confusing, but quite essential, concept when merging, splitting, or otherwise editing ONNX graphs is the distinction between the inputs and outputs of a node (which, as we just discussed, are used to create the edges), and the input and output of the graph itself. Graph inputs and outputs represent the tensors that are being fed to the computational graph, and the tensors that result from carrying out the computations respectively. Input and outputs are implicitly connected to a graph in the same way as edges are created. Actually, a reasonable mental model of inputs and outputs to the graph is that they are simply nodes with either only an output (the inputs to the graph) or only an input (the outputs of the graph); the respective in and output of these special nodes, which do not operate on the tensors, are the outside world. Ok, that was a bit cryptic. Let’s give a few examples using the following notation: I1(name) # An input (to the graph) with a specific nameO1(name) # An output (to the graph) with a specific nameN1({name, name, ...}, {name, name, ...}) # A node, with a list of inputs and outputs. Given this notation we can for example denote # A simple graph:I1(x1)I2(x2)O3(x3)N1({x1,x2},{x3}) Which would generate (using orange for inputs and outputs) the following graph: If N1 is the Add operator, this graph would simple encoded adding two tensors. Let’s do a slightly more complex graph: I1(x1)I2(x2)N1({x1, x2}, {x3})N2({x2, x3}, {x4})O1(x3)O2(x4) Which would graphically result in: Ok, so now we are clear on how the internal edges, and the inputs and outputs to the graph are constructed; let’s have a closer look at the tools in the sclblonnx package! From the update to version 0.1.9, the sclblonnx package contains a number of higher level utility functions to combine multiple ONNX (sub) graphs into a single graph. Although earlier versions of the package already contained the merge function to effectively paste two graphs together (more on this later), the update presents merge, join, and split as higher level wrappers around a much more versatile — and harder to use — function called concat. Let’s start with the higher level functions. All the functions described here can be found in python code in the examples presented with the sclblonnx package. These can be found at https://github.com/scailable/sclblonnx/blob/master/examples/example_merge.py. Also, please see the docs of each of the discussed functions: https://github.com/scailable/sclblonnx/blob/master/sclblonnx/merge.py merge effectively takes two graphs (a parent and a child), and paste the identified outputs off the parent to the identified inputs of the child. By default, merge assumes that both graphs are complete (i.e., all edges nicely match up, and all inputs and outputs are defined. The signature of merge is merge(sg1, sg2, io_match) Where sg1 is the parent subgraph, sg2 the child, and io_match present a list of pairs of names of outputs of sg1 that need to be matched to inputs off sg2. Thus, given our developed notation in the previous section, if we have: # Parent (sg1)I1(x1)N1({x1},{x2})O1(x2)# Child (sg2)I2(z1)N2({z1},{z2})O2(z2) A call to merge(sg1, sg2, [(x2,z1)]) would create: I1(x1)N1({x1},{x2})N2({x2},{z2})O2(z2) However, as you can image we can do much more versatile merges using this function. Note that merge assumes there are no “conflicts” in the internal naming of the two graphs; if this is not the case and you would like to control this behavior in more detail, I recommend using concat; merge is merely a user friendly wrapper around concat. Like merge, split and join are also higher level wrappers around concat (which we detail below). The behavior is relatively simple: split takes one “parent” with multiple outputs, and paste one subgraph to a subset of these outputs (by matching the inputs of the subgraph), and another subgraph to another subset of the output of the parent. Thus, effectively, split creates a branch where the parent graph feeds in to two children. join is the converse of split in many ways: it takes two “parents”, and only a single child. The parents are matched by their outputs to inputs off the child. Hence, join effectively joins to branches of subgraphs in a larger tree. The work-horse for the merge, split, and join functions described above is the much more versatile concat function. The easiest way to understand its functioning is perhaps a look at the signature and the docs: def concat( sg1: xpb2.GraphProto, sg2: xpb2.GraphProto, complete: bool = False, rename_nodes: bool = True, io_match: [] = None, rename_io: bool = False, edge_match: [] = None, rename_edges: bool = False, _verbose: bool = False, **kwargs): """ concat concatenates two graphs. Concat is the flexible (but also rather complex) workhorse for the merge, join, and split functions and can be used to pretty flexibly paste together two (sub)graphs. Contrary to merge, join, and split, concat does not by default assume the resulting onnx graph to be complete (i.e., to contain inputs and outputs and to pass check()), and it can thus be used as an intermediate function when constructing larger graphs. Concat is flexible and versatile, but it takes time to master. See example_merge.py in the examples folder for a number of examples. Args: sg1: Subgraph 1, the parent. sg2: Subgraph 2, the child. complete: (Optional) Boolean indicating whether the resulting graph should be checked using so.check(). Default False. rename_nodes: (Optional) Boolean indicating whether the names of the nodes in the graph should be made unique. Default True. io_match: (Optional) Dict containing pairs of outputs of sg1 that should be matched to inputs of sg2. Default []. rename_io: (Optional) Boolean indicating whether the inputs and outputs of the graph should be renamed. Default False. edge_match: (Optional) Dict containing pairs edge names of sg1 (i.e., node outputs) that should be matched to edges of sg2 (i.e., node inputs). Default []. rename_edges: (Optional) Boolean indicating whether the edges should be renamed. Default False _verbose: (Optional) Boolean indicating whether verbose output should be printed (default False) Returns: The concatenated graph g, or False if something goes wrong along the way. """## The implementation... As is clear from the signature, the higher level wrapper merge simply calls concat once, pretty much with its default arguments. The functions split and join functions each call concat twice to achieve their desired result. Note that the argument rename_edges allows one to control whether all edges in the subgraph should be renamed (thus avoiding possibly unwanted implicit edge creation), whereas complete allows one to use merge to operate on partial graphs (i.e., graphs that do not yet have all of their edges defined. I hope the above shed some light on the immense possibilities ONNX has to offer, and on some of the tools to manipulate ONNX graphs manually. We think ONNX is great for storing (sub)graphs that do useful bits otherwise associated with a data science pipeline in a platform independent fashion. Tooling such as the sclblonnx package subsequently enable users to create full pipelines using the subgraphs as building blocks. In this post I have on purpose omitted issues regarding matching dimensions and types of inputs and outputs to nodes; I hope that by focussing on the rough structure of the graph(s) involved the operations are easier to follow; when creating actual functioning graphs obviously the types and dimensions of the various tensors involved are of importance. It’s good to note my own involvement here: I am a professor of Data Science at the Jheronimus Academy of Data Science and one of the cofounders of Scailable. Thus, no doubt, I have a vested interest in Scailable; I have an interest in making it grow such that we can finally bring AI to production and deliver on its promises. The opinions expressed here are my own. Note
[ { "code": null, "e": 1147, "s": 172, "text": "ONNX is getting more and more popular. While initially conceived predominantly as a file-format to simply store AI/ML models, its use has changed in recent years. Nowadays, we see many data scientist use ONNX as means to build and curate complete data processing pipelines. As the usage of ONNX grows, so does the need for good tools for creating, inspecting, and editing ONNX graphs. Luckily, a large ecosystem for ONNX is emerging; in this post we describe the ONNX join, split, merge, and concatenate functionality as offered by the sclblonnx package (curated by Scailable). Note that merging, splitting, and concatenating ONNX graphs is extremely useful when you are actively curating useful “subgraphs” of ONNX: i.e., you might have your preferred pre and post-processing steps in a data pipeline stored in ONNX format, and you want to join these subgraphs with a model you have just trained in TensorFlow or PyTorch. In this post I try to explain how this can be done." }, { "code": null, "e": 1393, "s": 1147, "text": "Note: I have written about ONNX editing and merging before, see https://towardsdatascience.com/creating-editing-and-merging-onnx-pipelines-897e55e98bb0. However, with the release of sclblonnx 0.1.9 the functionalities have been greatly extended." }, { "code": null, "e": 2100, "s": 1393, "text": "Before discussing the new merge, concat, split, and join functionalities for ONNX graphs as provided by sclblonnx 0.1.9, it is useful to provide a bit more background about ONNX graphs. At this point in the text I assume you know some of ONNX basics (if not, see this article, or this one). Thus, you know that ONNX provides a description of a directed computational graph which specifies which operations to execute on the (strongly typed) input tensors to produce the desired output tensor. And, you know that ONNX is useful for storing trained AI/ML models, and for creating data science pipelines, in a way that is platform and deployment target independent. I.e., you generally know ONNX is fun stuff." }, { "code": null, "e": 2363, "s": 2100, "text": "However, to understand how one can merge, slit, join, and concatenate ONNX graphs we need a bit more background. We need to both understand how edges in a graph are created, and we need to understand in a bit more detail the role of the graph’s input and output." }, { "code": null, "e": 3266, "s": 2363, "text": "Let’s start with the creation of edges. Although an ONNX graph is simply a directed graph, and it could thus be described by its nodes and edges, this is not how we create (nor store) an ONNX graph. When creating an ONNX graph, we do not explicitly create an adjacency matrix to identify the edges between nodes. Rather, we create nodes of some type (the different operators), each with a named input‘s and output's. This is also all that is stored in the ONNX file (which is actually just a protobuf): the file stores a list of operator types, each with their own named input(s) and output(s). The names in the end allow for the construction of the edges in the graph: If node n1 has an output named x1, and node n2 has an input named x1, a (directed)edge between n1 and n2 will be created. If subsequently another node, n3 is added, which also has a named input x1 we end up with the following graph:" }, { "code": null, "e": 3689, "s": 3266, "text": "Thus, when merging, joining, concatenating and splitting ONNX (sub)graphs, it is quite essential to know the — in some way internal, and potentially unknown to you if you have exported to ONNX from one of various training tools — input ant output names present in the graphs that you end up combining. If the same name occurs in both graphs, carelessly merging the graphs will cause potentially unwanted edges to be drawn." }, { "code": null, "e": 3810, "s": 3689, "text": "If the same name occurs in both graphs, carelessly merging the graphs will cause potentially unwanted edges to be drawn." }, { "code": null, "e": 4667, "s": 3810, "text": "Another somewhat confusing, but quite essential, concept when merging, splitting, or otherwise editing ONNX graphs is the distinction between the inputs and outputs of a node (which, as we just discussed, are used to create the edges), and the input and output of the graph itself. Graph inputs and outputs represent the tensors that are being fed to the computational graph, and the tensors that result from carrying out the computations respectively. Input and outputs are implicitly connected to a graph in the same way as edges are created. Actually, a reasonable mental model of inputs and outputs to the graph is that they are simply nodes with either only an output (the inputs to the graph) or only an input (the outputs of the graph); the respective in and output of these special nodes, which do not operate on the tensors, are the outside world." }, { "code": null, "e": 4695, "s": 4667, "text": "Ok, that was a bit cryptic." }, { "code": null, "e": 4751, "s": 4695, "text": "Let’s give a few examples using the following notation:" }, { "code": null, "e": 4950, "s": 4751, "text": "I1(name) # An input (to the graph) with a specific nameO1(name) # An output (to the graph) with a specific nameN1({name, name, ...}, {name, name, ...}) # A node, with a list of inputs and outputs." }, { "code": null, "e": 4996, "s": 4950, "text": "Given this notation we can for example denote" }, { "code": null, "e": 5048, "s": 4996, "text": "# A simple graph:I1(x1)I2(x2)O3(x3)N1({x1,x2},{x3})" }, { "code": null, "e": 5128, "s": 5048, "text": "Which would generate (using orange for inputs and outputs) the following graph:" }, { "code": null, "e": 5207, "s": 5128, "text": "If N1 is the Add operator, this graph would simple encoded adding two tensors." }, { "code": null, "e": 5247, "s": 5207, "text": "Let’s do a slightly more complex graph:" }, { "code": null, "e": 5308, "s": 5247, "text": "I1(x1)I2(x2)N1({x1, x2}, {x3})N2({x2, x3}, {x4})O1(x3)O2(x4)" }, { "code": null, "e": 5343, "s": 5308, "text": "Which would graphically result in:" }, { "code": null, "e": 5515, "s": 5343, "text": "Ok, so now we are clear on how the internal edges, and the inputs and outputs to the graph are constructed; let’s have a closer look at the tools in the sclblonnx package!" }, { "code": null, "e": 6011, "s": 5515, "text": "From the update to version 0.1.9, the sclblonnx package contains a number of higher level utility functions to combine multiple ONNX (sub) graphs into a single graph. Although earlier versions of the package already contained the merge function to effectively paste two graphs together (more on this later), the update presents merge, join, and split as higher level wrappers around a much more versatile — and harder to use — function called concat. Let’s start with the higher level functions." }, { "code": null, "e": 6358, "s": 6011, "text": "All the functions described here can be found in python code in the examples presented with the sclblonnx package. These can be found at https://github.com/scailable/sclblonnx/blob/master/examples/example_merge.py. Also, please see the docs of each of the discussed functions: https://github.com/scailable/sclblonnx/blob/master/sclblonnx/merge.py" }, { "code": null, "e": 6660, "s": 6358, "text": "merge effectively takes two graphs (a parent and a child), and paste the identified outputs off the parent to the identified inputs of the child. By default, merge assumes that both graphs are complete (i.e., all edges nicely match up, and all inputs and outputs are defined. The signature of merge is" }, { "code": null, "e": 6686, "s": 6660, "text": "merge(sg1, sg2, io_match)" }, { "code": null, "e": 6914, "s": 6686, "text": "Where sg1 is the parent subgraph, sg2 the child, and io_match present a list of pairs of names of outputs of sg1 that need to be matched to inputs off sg2. Thus, given our developed notation in the previous section, if we have:" }, { "code": null, "e": 6992, "s": 6914, "text": "# Parent (sg1)I1(x1)N1({x1},{x2})O1(x2)# Child (sg2)I2(z1)N2({z1},{z2})O2(z2)" }, { "code": null, "e": 7043, "s": 6992, "text": "A call to merge(sg1, sg2, [(x2,z1)]) would create:" }, { "code": null, "e": 7082, "s": 7043, "text": "I1(x1)N1({x1},{x2})N2({x2},{z2})O2(z2)" }, { "code": null, "e": 7422, "s": 7082, "text": "However, as you can image we can do much more versatile merges using this function. Note that merge assumes there are no “conflicts” in the internal naming of the two graphs; if this is not the case and you would like to control this behavior in more detail, I recommend using concat; merge is merely a user friendly wrapper around concat." }, { "code": null, "e": 7554, "s": 7422, "text": "Like merge, split and join are also higher level wrappers around concat (which we detail below). The behavior is relatively simple:" }, { "code": null, "e": 7855, "s": 7554, "text": "split takes one “parent” with multiple outputs, and paste one subgraph to a subset of these outputs (by matching the inputs of the subgraph), and another subgraph to another subset of the output of the parent. Thus, effectively, split creates a branch where the parent graph feeds in to two children." }, { "code": null, "e": 8087, "s": 7855, "text": "join is the converse of split in many ways: it takes two “parents”, and only a single child. The parents are matched by their outputs to inputs off the child. Hence, join effectively joins to branches of subgraphs in a larger tree." }, { "code": null, "e": 8298, "s": 8087, "text": "The work-horse for the merge, split, and join functions described above is the much more versatile concat function. The easiest way to understand its functioning is perhaps a look at the signature and the docs:" }, { "code": null, "e": 10499, "s": 8298, "text": "def concat( sg1: xpb2.GraphProto, sg2: xpb2.GraphProto, complete: bool = False, rename_nodes: bool = True, io_match: [] = None, rename_io: bool = False, edge_match: [] = None, rename_edges: bool = False, _verbose: bool = False, **kwargs): \"\"\" concat concatenates two graphs. Concat is the flexible (but also rather complex) workhorse for the merge, join, and split functions and can be used to pretty flexibly paste together two (sub)graphs. Contrary to merge, join, and split, concat does not by default assume the resulting onnx graph to be complete (i.e., to contain inputs and outputs and to pass check()), and it can thus be used as an intermediate function when constructing larger graphs. Concat is flexible and versatile, but it takes time to master. See example_merge.py in the examples folder for a number of examples. Args: sg1: Subgraph 1, the parent. sg2: Subgraph 2, the child. complete: (Optional) Boolean indicating whether the resulting graph should be checked using so.check(). Default False. rename_nodes: (Optional) Boolean indicating whether the names of the nodes in the graph should be made unique. Default True. io_match: (Optional) Dict containing pairs of outputs of sg1 that should be matched to inputs of sg2. Default []. rename_io: (Optional) Boolean indicating whether the inputs and outputs of the graph should be renamed. Default False. edge_match: (Optional) Dict containing pairs edge names of sg1 (i.e., node outputs) that should be matched to edges of sg2 (i.e., node inputs). Default []. rename_edges: (Optional) Boolean indicating whether the edges should be renamed. Default False _verbose: (Optional) Boolean indicating whether verbose output should be printed (default False) Returns: The concatenated graph g, or False if something goes wrong along the way. \"\"\"## The implementation..." }, { "code": null, "e": 11024, "s": 10499, "text": "As is clear from the signature, the higher level wrapper merge simply calls concat once, pretty much with its default arguments. The functions split and join functions each call concat twice to achieve their desired result. Note that the argument rename_edges allows one to control whether all edges in the subgraph should be renamed (thus avoiding possibly unwanted implicit edge creation), whereas complete allows one to use merge to operate on partial graphs (i.e., graphs that do not yet have all of their edges defined." }, { "code": null, "e": 11447, "s": 11024, "text": "I hope the above shed some light on the immense possibilities ONNX has to offer, and on some of the tools to manipulate ONNX graphs manually. We think ONNX is great for storing (sub)graphs that do useful bits otherwise associated with a data science pipeline in a platform independent fashion. Tooling such as the sclblonnx package subsequently enable users to create full pipelines using the subgraphs as building blocks." }, { "code": null, "e": 11801, "s": 11447, "text": "In this post I have on purpose omitted issues regarding matching dimensions and types of inputs and outputs to nodes; I hope that by focussing on the rough structure of the graph(s) involved the operations are easier to follow; when creating actual functioning graphs obviously the types and dimensions of the various tensors involved are of importance." } ]
Angular Material - Swipe
The Swipe functionality is meant for mobile devices. The following directives are used to handle swipes. md-swipe-down, an Angular directive is used to specify custom behavior when an element is swiped down. md-swipe-down, an Angular directive is used to specify custom behavior when an element is swiped down. md-swipe-left, an Angular directive is used to specify custom behavior when an element is swiped left. md-swipe-left, an Angular directive is used to specify custom behavior when an element is swiped left. md-swipe-right, an Angular directive is used to specify custom behavior when an element is swiped right. md-swipe-right, an Angular directive is used to specify custom behavior when an element is swiped right. md-swipe-up, an Angular directive is used to specify custom behavior when an element is swiped up. md-swipe-up, an Angular directive is used to specify custom behavior when an element is swiped up. The following example shows the use of md-swipe-* and also the uses of swipe components. am_swipes.htm <html lang = "en"> <head> <link rel = "stylesheet" href = "https://ajax.googleapis.com/ajax/libs/angular_material/1.0.0/angular-material.min.css"> <script src = "https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script> <script src = "https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular-animate.min.js"></script> <script src = "https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular-aria.min.js"></script> <script src = "https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular-messages.min.js"></script> <script src = "https://ajax.googleapis.com/ajax/libs/angular_material/1.0.0/angular-material.min.js"></script> <link rel = "stylesheet" href = "https://fonts.googleapis.com/icon?family=Material+Icons"> <style> .swipeContainer .demo-swipe { padding: 20px 10px; } .swipeContainer .no-select { -webkit-touch-callout: none; -webkit-user-select: none; -khtml-user-select: none; -moz-user-select: none; -ms-user-select: none; user-select: none; } </style> <script language = "javascript"> angular .module('firstApplication', ['ngMaterial']) .controller('swipeController', swipeController); function swipeController ($scope) { $scope.onSwipeLeft = function(ev) { alert('Swiped Left!'); }; $scope.onSwipeRight = function(ev) { alert('Swiped Right!'); }; $scope.onSwipeUp = function(ev) { alert('Swiped Up!'); }; $scope.onSwipeDown = function(ev) { alert('Swiped Down!'); }; } </script> </head> <body ng-app = "firstApplication"> <md-card> <div id = "swipeContainer" ng-controller = "swipeController as ctrl" layout = "row" ng-cloak> <div flex> <div class = "demo-swipe" md-swipe-left = "onSwipeLeft()"> <span class = "no-select">Swipe me to the left</span> <md-icon md-font-icon = "android" aria-label = "android"></md-icon> </div> <md-divider></md-divider> <div class = "demo-swipe" md-swipe-right = "onSwipeRight()"> <span class = "no-select">Swipe me to the right</span> </div> </div> <md-divider></md-divider> <div flex layout = "row"> <div flex layout = "row" layout-align = "center center" class = "demo-swipe" md-swipe-up = "onSwipeUp()"> <span class = "no-select">Swipe me up</span> </div> <md-divider></md-divider> <div flex layout = "row" layout-align = "center center" class = "demo-swipe" md-swipe-down = "onSwipeDown()"> <span class = "no-select">Swipe me down</span> </div> </div> </div> </md-card> </body> </html> Verify the result. 16 Lectures 1.5 hours Anadi Sharma 28 Lectures 2.5 hours Anadi Sharma 11 Lectures 7.5 hours SHIVPRASAD KOIRALA 16 Lectures 2.5 hours Frahaan Hussain 69 Lectures 5 hours Senol Atac 53 Lectures 3.5 hours Senol Atac Print Add Notes Bookmark this page
[ { "code": null, "e": 2295, "s": 2190, "text": "The Swipe functionality is meant for mobile devices. The following directives are used to handle swipes." }, { "code": null, "e": 2398, "s": 2295, "text": "md-swipe-down, an Angular directive is used to specify custom behavior when an element is swiped down." }, { "code": null, "e": 2501, "s": 2398, "text": "md-swipe-down, an Angular directive is used to specify custom behavior when an element is swiped down." }, { "code": null, "e": 2604, "s": 2501, "text": "md-swipe-left, an Angular directive is used to specify custom behavior when an element is swiped left." }, { "code": null, "e": 2707, "s": 2604, "text": "md-swipe-left, an Angular directive is used to specify custom behavior when an element is swiped left." }, { "code": null, "e": 2812, "s": 2707, "text": "md-swipe-right, an Angular directive is used to specify custom behavior when an element is swiped right." }, { "code": null, "e": 2917, "s": 2812, "text": "md-swipe-right, an Angular directive is used to specify custom behavior when an element is swiped right." }, { "code": null, "e": 3016, "s": 2917, "text": "md-swipe-up, an Angular directive is used to specify custom behavior when an element is swiped up." }, { "code": null, "e": 3115, "s": 3016, "text": "md-swipe-up, an Angular directive is used to specify custom behavior when an element is swiped up." }, { "code": null, "e": 3204, "s": 3115, "text": "The following example shows the use of md-swipe-* and also the uses of swipe components." }, { "code": null, "e": 3218, "s": 3204, "text": "am_swipes.htm" }, { "code": null, "e": 6512, "s": 3218, "text": "<html lang = \"en\">\n <head>\n <link rel = \"stylesheet\"\n href = \"https://ajax.googleapis.com/ajax/libs/angular_material/1.0.0/angular-material.min.css\">\n <script src = \"https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js\"></script>\n <script src = \"https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular-animate.min.js\"></script>\n <script src = \"https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular-aria.min.js\"></script>\n <script src = \"https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular-messages.min.js\"></script>\n <script src = \"https://ajax.googleapis.com/ajax/libs/angular_material/1.0.0/angular-material.min.js\"></script>\n <link rel = \"stylesheet\" href = \"https://fonts.googleapis.com/icon?family=Material+Icons\">\n \n <style>\n .swipeContainer .demo-swipe {\n padding: 20px 10px; \t\t\t\n }\n \n .swipeContainer .no-select {\n -webkit-touch-callout: none;\n -webkit-user-select: none;\n -khtml-user-select: none;\n -moz-user-select: none;\n -ms-user-select: none;\n user-select: none; \n }\n </style>\n \n <script language = \"javascript\">\n angular\n .module('firstApplication', ['ngMaterial'])\n .controller('swipeController', swipeController);\n\n function swipeController ($scope) {\n $scope.onSwipeLeft = function(ev) {\n alert('Swiped Left!');\n };\n \n $scope.onSwipeRight = function(ev) {\n alert('Swiped Right!');\n };\n \n $scope.onSwipeUp = function(ev) {\n alert('Swiped Up!');\n };\n \n $scope.onSwipeDown = function(ev) {\n alert('Swiped Down!');\n };\n }\t \n </script> \n </head>\n \n <body ng-app = \"firstApplication\"> \n <md-card>\n <div id = \"swipeContainer\" ng-controller = \"swipeController as ctrl\"\n layout = \"row\" ng-cloak>\n <div flex>\n <div class = \"demo-swipe\" md-swipe-left = \"onSwipeLeft()\">\n <span class = \"no-select\">Swipe me to the left</span>\n <md-icon md-font-icon = \"android\" aria-label = \"android\"></md-icon>\n </div>\n \n <md-divider></md-divider>\n <div class = \"demo-swipe\" md-swipe-right = \"onSwipeRight()\">\n <span class = \"no-select\">Swipe me to the right</span>\n </div>\n </div>\n\n <md-divider></md-divider>\n <div flex layout = \"row\">\n <div flex layout = \"row\" layout-align = \"center center\"\n class = \"demo-swipe\" md-swipe-up = \"onSwipeUp()\">\n <span class = \"no-select\">Swipe me up</span>\n </div>\n \n <md-divider></md-divider>\n <div flex layout = \"row\" layout-align = \"center center\"\n class = \"demo-swipe\" md-swipe-down = \"onSwipeDown()\">\n <span class = \"no-select\">Swipe me down</span>\n </div>\n </div>\n \n </div>\n </md-card>\n </body>\n</html>" }, { "code": null, "e": 6531, "s": 6512, "text": "Verify the result." }, { "code": null, "e": 6566, "s": 6531, "text": "\n 16 Lectures \n 1.5 hours \n" }, { "code": null, "e": 6580, "s": 6566, "text": " Anadi Sharma" }, { "code": null, "e": 6615, "s": 6580, "text": "\n 28 Lectures \n 2.5 hours \n" }, { "code": null, "e": 6629, "s": 6615, "text": " Anadi Sharma" }, { "code": null, "e": 6664, "s": 6629, "text": "\n 11 Lectures \n 7.5 hours \n" }, { "code": null, "e": 6684, "s": 6664, "text": " SHIVPRASAD KOIRALA" }, { "code": null, "e": 6719, "s": 6684, "text": "\n 16 Lectures \n 2.5 hours \n" }, { "code": null, "e": 6736, "s": 6719, "text": " Frahaan Hussain" }, { "code": null, "e": 6769, "s": 6736, "text": "\n 69 Lectures \n 5 hours \n" }, { "code": null, "e": 6781, "s": 6769, "text": " Senol Atac" }, { "code": null, "e": 6816, "s": 6781, "text": "\n 53 Lectures \n 3.5 hours \n" }, { "code": null, "e": 6828, "s": 6816, "text": " Senol Atac" }, { "code": null, "e": 6835, "s": 6828, "text": " Print" }, { "code": null, "e": 6846, "s": 6835, "text": " Add Notes" } ]
C++ do...while loop
Unlike for and while loops, which test the loop condition at the top of the loop, the do...while loop checks its condition at the bottom of the loop. A do...while loop is similar to a while loop, except that a do...while loop is guaranteed to execute at least one time. The syntax of a do...while loop in C++ is − do { statement(s); } while( condition ); Notice that the conditional expression appears at the end of the loop, so the statement(s) in the loop execute once before the condition is tested. If the condition is true, the flow of control jumps back up to do, and the statement(s) in the loop execute again. This process repeats until the given condition becomes false. #include <iostream> using namespace std; int main () { // Local variable declaration: int a = 10; // do loop execution do { cout << "value of a: " << a << endl; a = a + 1; } while( a < 20 ); return 0; } When the above code is compiled and executed, it produces the following result − value of a: 10 value of a: 11 value of a: 12 value of a: 13 value of a: 14 value of a: 15 value of a: 16 value of a: 17 value of a: 18 value of a: 19 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": 2468, "s": 2318, "text": "Unlike for and while loops, which test the loop condition at the top of the loop, the do...while loop checks its condition at the bottom of the loop." }, { "code": null, "e": 2588, "s": 2468, "text": "A do...while loop is similar to a while loop, except that a do...while loop is guaranteed to execute at least one time." }, { "code": null, "e": 2632, "s": 2588, "text": "The syntax of a do...while loop in C++ is −" }, { "code": null, "e": 2678, "s": 2632, "text": "do {\n statement(s);\n} \nwhile( condition );\n" }, { "code": null, "e": 2826, "s": 2678, "text": "Notice that the conditional expression appears at the end of the loop, so the statement(s) in the loop execute once before the condition is tested." }, { "code": null, "e": 3004, "s": 2826, "text": "If the condition is true, the flow of control jumps back up to do, and the statement(s) in the loop execute again. This process repeats until the given condition becomes false." }, { "code": null, "e": 3242, "s": 3004, "text": "#include <iostream>\nusing namespace std;\n \nint main () {\n // Local variable declaration:\n int a = 10;\n\n // do loop execution\n do {\n cout << \"value of a: \" << a << endl;\n a = a + 1;\n } while( a < 20 );\n \n return 0;\n}" }, { "code": null, "e": 3323, "s": 3242, "text": "When the above code is compiled and executed, it produces the following result −" }, { "code": null, "e": 3474, "s": 3323, "text": "value of a: 10\nvalue of a: 11\nvalue of a: 12\nvalue of a: 13\nvalue of a: 14\nvalue of a: 15\nvalue of a: 16\nvalue of a: 17\nvalue of a: 18\nvalue of a: 19\n" }, { "code": null, "e": 3511, "s": 3474, "text": "\n 154 Lectures \n 11.5 hours \n" }, { "code": null, "e": 3530, "s": 3511, "text": " Arnab Chakraborty" }, { "code": null, "e": 3562, "s": 3530, "text": "\n 14 Lectures \n 57 mins\n" }, { "code": null, "e": 3585, "s": 3562, "text": " Kaushik Roy Chowdhury" }, { "code": null, "e": 3621, "s": 3585, "text": "\n 30 Lectures \n 12.5 hours \n" }, { "code": null, "e": 3638, "s": 3621, "text": " Frahaan Hussain" }, { "code": null, "e": 3673, "s": 3638, "text": "\n 54 Lectures \n 3.5 hours \n" }, { "code": null, "e": 3690, "s": 3673, "text": " Frahaan Hussain" }, { "code": null, "e": 3725, "s": 3690, "text": "\n 77 Lectures \n 5.5 hours \n" }, { "code": null, "e": 3742, "s": 3725, "text": " Frahaan Hussain" }, { "code": null, "e": 3777, "s": 3742, "text": "\n 12 Lectures \n 3.5 hours \n" }, { "code": null, "e": 3794, "s": 3777, "text": " Frahaan Hussain" }, { "code": null, "e": 3801, "s": 3794, "text": " Print" }, { "code": null, "e": 3812, "s": 3801, "text": " Add Notes" } ]
Deep dive into Analytical Hierarchy Process using Python | by Anirudh Chandra | Towards Data Science
Through the course of a lifetime, a human makes a number of decisions, ranging from the most trivial ones that have almost no impact, to those that have life changing consequences. And almost always, these situations involve X number of options and Y number of criteria that they are judged on. Imagine you are out at the supermarket and you want to buy breakfast cereals. You are standing in front of rows and rows of cereals and not sure which one to buy. So what are you looking for? Price: The cereal must not be too priceyFlavor: Maybe something with chocolate in it?Nutrition: Something with mixed fruits or oats. Price: The cereal must not be too pricey Flavor: Maybe something with chocolate in it? Nutrition: Something with mixed fruits or oats. These are some of the criteria you think of when you browse through the products. Let’s say you pick up Fruit Loops, Frosted Flakes and Lucky Charm. You mentally run each of them through the criteria and compare them against each other. Then you make a decision and put Frosted Flakes in your cart. You are running a meeting at a town hall in a little village in Ghana. As the head of The Water Project delegation, you have been tasked to install a series of water pumps in the village. In front of you are the various stakeholders — village elders, geologists and engineers. In this meeting you would like to select spots for setting up the water pumps and you list out a set of criteria — Groundwater level: The spot must have a groundwater level that is reasonably high;Population: There must be a minimum number of people living nearby to make the installation useful;Cost: The cost of running materials and supplies must be within the project funds. Groundwater level: The spot must have a groundwater level that is reasonably high; Population: There must be a minimum number of people living nearby to make the installation useful; Cost: The cost of running materials and supplies must be within the project funds. You talk to the village elders, geologists and engineers and draw up a set of 15 possible locations to build the water pumps. After much discussion and weighing of opinions, you narrow it down to 5 spots that rank high in the list of selection criteria. Although these two examples were vastly different in their scale of impact and domain of application, the problem was pretty much the same — Making a decision in the face of multiple, often conflicting, criteria. In this post, I will provide a high level explanation of Analytical Hierarchy Process — one possible technique of solving such multi-criteria decision making problems. And in the process, I will also show you how to implement this technique, from scratch, in Python. Analytical Hierarchy Process is a multi-criteria decision making method introduced by Prof. Thomas Saaty in the 1970s. It is a way to help decision makers make informed decisions by quantifying subjective beliefs within a mathematical framework. AHP is all about relative measurements of different quantities and is at the intersection of the field of decision analysis and operational research. AHP is popular in a number of fields, ranging from supply chain, to sustainable systems, environmental management, portfolio selection etc. Its popularity stems from the fact that it is highly intuitive and allows the decision maker(s) to codify their subjective beliefs in a transparent manner. AHP, essentially, is the process of assigning different weights to different options and summing them up. However, the beauty is in the way these weights are arrived at and therein lies the quantification of subjective beliefs. Let me briefly present to you the highly intuitive process of AHP — Step 1: Define the ultimate goal of the process. In the examples shared above, the goals were buying a breakfast cereal and selecting suitable installation spots respectively; Step 2: List the various options you have in hand to fulfill the goal. These options are called ‘alternatives’. Step 3: List out the different criteria by which you assess the above alternatives. These can involve sub-levels of criteria and is totally dependent on the amount of scrutiny you want, especially when the options are very similar to each other. Step 4: Build the Hierarchy from Steps 1 to 3. If you are familiar with graph theory, then you can imagine this to be a directed acyclic graph. The connections between each node implies their consideration in the assessment. Step 5: Pair-wise comparison of each criteria and sub-criteria to establish their weights. Step 6: Pair-wise comparison of each alternatives against each sub-criteria to establish their weights. Step 7: Global summation of all these weights (weighted arithmetic sum) for each alternative and ordering them on the basis of this weighted sum. Step 8: Calculate the consistency ratio. This is a measure of how consistent the subjective assessment is, when compared to a table of critical values. If found inconsistent, go back to Step 5. So from these steps, you can see how the process got its name and why it is so popular in terms of its application. Now, let’s have a look at the heart of this process — the quantification of subjective beliefs. The key-word of AHP is pair-wise comparison. We all know how difficult it is to compare more than three options at a time. To eliminate this difficulty, Prof. Saaty suggested a pair-wise comparison of alternatives/criteria. And this comparison/evaluation is done by assigning intensities that represent various degree of importance, which he defined linguistically [3]. The evaluated/assessed alternatives are compiled into a n x n pair-wise comparison matrix A,for each criteria/sub-criteria/goal [1]. Here, the wi and wj are the weights or intensities of importance from the previous table. You can immediately see that the assessment matrix is symmetric, making computation easier. Once you create the assessment matrix, the next step is to convert it into vector. This vector encodes the information present in the matrix and is called the priority vector. There are a few ways in which you can calculate this priority vector. One way is to obtain the Perron-Frobenius eigenvector [4], or simply the normalized eigenvector of the matrix. The other way is to calculate the geometric mean of the elements on the respective row divided by a normalization term so that the components of the priority vector eventually add up to 1 [1]. This method is an approximation of the normalized eigenvector method. The final step of the assessment is the weighted arithmetic sum of the priority vectors generated for each sub-criterion and ordering them to rank the alternatives. The underlying assumption in AHP is that the decision makers are rational. This basically means that the decision maker is assumed to apply the same subjective beliefs every time for the same problem. However, in reality, this may not be the case. Prof. Saaty took care of this uncertainty by proposing a consistency index, CI Where lambda_max is the maximum eigen value of the pair-wise comparison matrix and n is the number of alternatives. To scale for different size matrices, the Consistency Ratio was developed, CR Where, RI_n is an average estimate of the CI obtained from a large enough set of randomly generated matrices of size n. The look-up table for RI_n are given by Prof. Saaty as, How to use the CR? — According to Prof. Saaty, in practice, one should accept matrices with CR ≤ 0.1 and reject values greater than 0.1. A value of CR = 0.1 basically means that the judgments are 10% as inconsistent as if they had been given randomly. By choosing a lower CR, one could try to reduce this inconsistency, and the only way to do that is to go back and re-evaluate the subjective weights. Phew, that was a lot of theory, so let’s get on with its implementation in Python for a simple use-case As far as I know there is only one well developed python library out there for AHP — pyAHP, but let’s write the code from scratch using the process described before. Here, I will use a typical use-case from [1] to illustrate the process. (Truth be told, it is pretty easy to implement in Excel!) Code can be found on my GitHub repository Let’s imagine you want to travel to Europe on a holiday and you plan on visiting a few interesting cities. You have a few cities in mind — Madrid, Hamburg and Paris, but your budget only allows you to visit one of those. To help you get maximum bang for your buck, you decide to use AHP to help you narrow down on a suitable city. The overall goal is obviously your personal satisfaction. The alternatives are {Rome, Madrid, Paris} and let us imagine you select the following criteria to assess each city — {Climate, Sightseeing, Environment}. Let us build the Hierarchy - Alright, so let's begin the assessment process by importing just two libraries import numpy as npimport pandas as pd We exploit the symmetric nature of the comparison matrix and take input only for the upper triangular matrix. # Number of optionsn = 3# Creating default matrix of onesA = np.ones([n,n])# Running a for loop to take input from user and populate the upper triangular elementsfor i in range(0,n): for j in range(0,n): if i<j: aij = input('How important is option{} over option{} ?: '.format(i,j)) A[i,j] = float(aij) #Upper triangular elements A[j,i] = 1/float(aij) #Lower triangular elements Remember, our criteria set was {Climate, Sightseeing, Environment}, so option 0 is Climate, option 1 is Sightseeing and option 2 is Environment. We run this piece of code to generate pair-wise comparison matrix for the criteria weights. How important is option0 over option1 ?: 0.5How important is option0 over option2 ?: 0.25How important is option1 over option2 ?: 0.5 This can be interpreted as — ‘Climate is twice as less important than Sightseeing opportunities and four times less important than the Environment in the city. Sightseeing opportunities are twice as less important than the Environment in the city’ Once the matrix is generated, we compute the priority vector by normalizing the eigen vector of the largest eigen value. The elements in this eigen vector are the weights of the criteria. e = np.linalg.eig(A)[1][:,0]p = e/e.sum()>>> array([0.14285714, 0.28571429, 0.57142857]) The two pieces of code are combined into a function def pairwise_matrix(n):A = np.ones([n,n]) for i in range(0,n): for j in range(0,n): if i<j: aij = input('How important is option{} over option{} ?: '.format(i,j)) A[i,j] = float(aij) A[j,i] = 1/float(aij)#Computing the priority vector eig_val = np.linalg.eig(A)[0].max() eig_vec = np.linalg.eig(A)[1][:,0] p = eig_vec/eig_vec.sum() return p, eig_val We call this function for generating pair-wise comparison matrices and priority vectors for assessing each of the alternative against each criterion. Remember our alternatives set was — {Rome, Madrid, Paris}. The priority vectors for each of the matrix are — pr_c = pairwise_matrix(3)[0] #All Criteriapr_c0 = pairwise_matrix(3)[0] #Criteria 0: Climatepr_c1 = pairwise_matrix(3)[0] #Criteria 1: Sightseeingpr_c2 = pairwise_matrix(3)[0] #Criteria 2: Environment#Priority Vector for Criteria 0 pr_c0>>> array([0.44444444, 0.44444444, 0.11111111])#Priority Vector for Criteria 1 pr_c1>>> array([0.6, 0.3, 0.1])#Priority Vector for Criteria 2pr_c2>>> array([0.09090909, 0.18181818, 0.72727273]) We also calculate the Consistency Ratio for each of these comparison matrices. For n= 3, the RI_n would be 0.5247. The maximum eigen value across all the matrices was 3. Therefore, by the earlier formula, the CR would be 0 for each of the matrix, which is < 0.1 and hence acceptable. The final step is to get their weighted arithmetic sum to yield the rank vector r = pr_c0*pr_c[0] + pr_c1*pr_c[1] + pr_c2*pr_c[2]print(r)>>> [0.28686869 0.25310245 0.46002886] The weighted arithmetic sum for Paris is much higher than Rome or Madrid, so it is assigned rank1, followed by Rome and Madrid. There you go! With the help of AHP, you successfully managed to quantify your subjective analysis and decided to fly to Paris! The major flaw with AHP is the rank reversals of alternatives when evaluated by a different group of people. The other issue is with the philosophical basis of including it in operational research. Having said that, AHP is still a popular MCDM method and relatively easy to implement and interpret. Apart from python, there are a few commercial softwares such as SuperDecisions that help you create the hierarchy and perform pairwise evaluations. There are many more MCDM methods to cater to the shortcomings of AHP and are more advanced in terms of their mathematical foundations. Some that come to mind are PROMETHEE, TOPSIS, etc. [1] Brunelli, Matteo. 2015. Introduction to the Analytic Hierarchy Process. SpringerBriefs in Operations Research. P. 83. 978–3–319–12502–2 (electronic).10.1007/978–3–319–12502–2. [2] https://en.wikipedia.org/wiki/Analytic_hierarchy_process_%E2%80%93_car_example [3] T.L. Saaty, Decision making with the analytic hierarchy process. Int. J. Services Sciences, Vol. 1, No1, 2008 [4]https://en.wikipedia.org/wiki/Perron%E2%80%93Frobenius_theorem I hope you found this post helpful and feedback is always appreciated!
[ { "code": null, "e": 467, "s": 172, "text": "Through the course of a lifetime, a human makes a number of decisions, ranging from the most trivial ones that have almost no impact, to those that have life changing consequences. And almost always, these situations involve X number of options and Y number of criteria that they are judged on." }, { "code": null, "e": 659, "s": 467, "text": "Imagine you are out at the supermarket and you want to buy breakfast cereals. You are standing in front of rows and rows of cereals and not sure which one to buy. So what are you looking for?" }, { "code": null, "e": 792, "s": 659, "text": "Price: The cereal must not be too priceyFlavor: Maybe something with chocolate in it?Nutrition: Something with mixed fruits or oats." }, { "code": null, "e": 833, "s": 792, "text": "Price: The cereal must not be too pricey" }, { "code": null, "e": 879, "s": 833, "text": "Flavor: Maybe something with chocolate in it?" }, { "code": null, "e": 927, "s": 879, "text": "Nutrition: Something with mixed fruits or oats." }, { "code": null, "e": 1226, "s": 927, "text": "These are some of the criteria you think of when you browse through the products. Let’s say you pick up Fruit Loops, Frosted Flakes and Lucky Charm. You mentally run each of them through the criteria and compare them against each other. Then you make a decision and put Frosted Flakes in your cart." }, { "code": null, "e": 1503, "s": 1226, "text": "You are running a meeting at a town hall in a little village in Ghana. As the head of The Water Project delegation, you have been tasked to install a series of water pumps in the village. In front of you are the various stakeholders — village elders, geologists and engineers." }, { "code": null, "e": 1618, "s": 1503, "text": "In this meeting you would like to select spots for setting up the water pumps and you list out a set of criteria —" }, { "code": null, "e": 1882, "s": 1618, "text": "Groundwater level: The spot must have a groundwater level that is reasonably high;Population: There must be a minimum number of people living nearby to make the installation useful;Cost: The cost of running materials and supplies must be within the project funds." }, { "code": null, "e": 1965, "s": 1882, "text": "Groundwater level: The spot must have a groundwater level that is reasonably high;" }, { "code": null, "e": 2065, "s": 1965, "text": "Population: There must be a minimum number of people living nearby to make the installation useful;" }, { "code": null, "e": 2148, "s": 2065, "text": "Cost: The cost of running materials and supplies must be within the project funds." }, { "code": null, "e": 2402, "s": 2148, "text": "You talk to the village elders, geologists and engineers and draw up a set of 15 possible locations to build the water pumps. After much discussion and weighing of opinions, you narrow it down to 5 spots that rank high in the list of selection criteria." }, { "code": null, "e": 2615, "s": 2402, "text": "Although these two examples were vastly different in their scale of impact and domain of application, the problem was pretty much the same — Making a decision in the face of multiple, often conflicting, criteria." }, { "code": null, "e": 2882, "s": 2615, "text": "In this post, I will provide a high level explanation of Analytical Hierarchy Process — one possible technique of solving such multi-criteria decision making problems. And in the process, I will also show you how to implement this technique, from scratch, in Python." }, { "code": null, "e": 3001, "s": 2882, "text": "Analytical Hierarchy Process is a multi-criteria decision making method introduced by Prof. Thomas Saaty in the 1970s." }, { "code": null, "e": 3128, "s": 3001, "text": "It is a way to help decision makers make informed decisions by quantifying subjective beliefs within a mathematical framework." }, { "code": null, "e": 3278, "s": 3128, "text": "AHP is all about relative measurements of different quantities and is at the intersection of the field of decision analysis and operational research." }, { "code": null, "e": 3574, "s": 3278, "text": "AHP is popular in a number of fields, ranging from supply chain, to sustainable systems, environmental management, portfolio selection etc. Its popularity stems from the fact that it is highly intuitive and allows the decision maker(s) to codify their subjective beliefs in a transparent manner." }, { "code": null, "e": 3802, "s": 3574, "text": "AHP, essentially, is the process of assigning different weights to different options and summing them up. However, the beauty is in the way these weights are arrived at and therein lies the quantification of subjective beliefs." }, { "code": null, "e": 3870, "s": 3802, "text": "Let me briefly present to you the highly intuitive process of AHP —" }, { "code": null, "e": 4046, "s": 3870, "text": "Step 1: Define the ultimate goal of the process. In the examples shared above, the goals were buying a breakfast cereal and selecting suitable installation spots respectively;" }, { "code": null, "e": 4158, "s": 4046, "text": "Step 2: List the various options you have in hand to fulfill the goal. These options are called ‘alternatives’." }, { "code": null, "e": 4404, "s": 4158, "text": "Step 3: List out the different criteria by which you assess the above alternatives. These can involve sub-levels of criteria and is totally dependent on the amount of scrutiny you want, especially when the options are very similar to each other." }, { "code": null, "e": 4629, "s": 4404, "text": "Step 4: Build the Hierarchy from Steps 1 to 3. If you are familiar with graph theory, then you can imagine this to be a directed acyclic graph. The connections between each node implies their consideration in the assessment." }, { "code": null, "e": 4720, "s": 4629, "text": "Step 5: Pair-wise comparison of each criteria and sub-criteria to establish their weights." }, { "code": null, "e": 4824, "s": 4720, "text": "Step 6: Pair-wise comparison of each alternatives against each sub-criteria to establish their weights." }, { "code": null, "e": 4970, "s": 4824, "text": "Step 7: Global summation of all these weights (weighted arithmetic sum) for each alternative and ordering them on the basis of this weighted sum." }, { "code": null, "e": 5164, "s": 4970, "text": "Step 8: Calculate the consistency ratio. This is a measure of how consistent the subjective assessment is, when compared to a table of critical values. If found inconsistent, go back to Step 5." }, { "code": null, "e": 5376, "s": 5164, "text": "So from these steps, you can see how the process got its name and why it is so popular in terms of its application. Now, let’s have a look at the heart of this process — the quantification of subjective beliefs." }, { "code": null, "e": 5746, "s": 5376, "text": "The key-word of AHP is pair-wise comparison. We all know how difficult it is to compare more than three options at a time. To eliminate this difficulty, Prof. Saaty suggested a pair-wise comparison of alternatives/criteria. And this comparison/evaluation is done by assigning intensities that represent various degree of importance, which he defined linguistically [3]." }, { "code": null, "e": 5879, "s": 5746, "text": "The evaluated/assessed alternatives are compiled into a n x n pair-wise comparison matrix A,for each criteria/sub-criteria/goal [1]." }, { "code": null, "e": 6061, "s": 5879, "text": "Here, the wi and wj are the weights or intensities of importance from the previous table. You can immediately see that the assessment matrix is symmetric, making computation easier." }, { "code": null, "e": 6237, "s": 6061, "text": "Once you create the assessment matrix, the next step is to convert it into vector. This vector encodes the information present in the matrix and is called the priority vector." }, { "code": null, "e": 6681, "s": 6237, "text": "There are a few ways in which you can calculate this priority vector. One way is to obtain the Perron-Frobenius eigenvector [4], or simply the normalized eigenvector of the matrix. The other way is to calculate the geometric mean of the elements on the respective row divided by a normalization term so that the components of the priority vector eventually add up to 1 [1]. This method is an approximation of the normalized eigenvector method." }, { "code": null, "e": 6846, "s": 6681, "text": "The final step of the assessment is the weighted arithmetic sum of the priority vectors generated for each sub-criterion and ordering them to rank the alternatives." }, { "code": null, "e": 7173, "s": 6846, "text": "The underlying assumption in AHP is that the decision makers are rational. This basically means that the decision maker is assumed to apply the same subjective beliefs every time for the same problem. However, in reality, this may not be the case. Prof. Saaty took care of this uncertainty by proposing a consistency index, CI" }, { "code": null, "e": 7289, "s": 7173, "text": "Where lambda_max is the maximum eigen value of the pair-wise comparison matrix and n is the number of alternatives." }, { "code": null, "e": 7367, "s": 7289, "text": "To scale for different size matrices, the Consistency Ratio was developed, CR" }, { "code": null, "e": 7543, "s": 7367, "text": "Where, RI_n is an average estimate of the CI obtained from a large enough set of randomly generated matrices of size n. The look-up table for RI_n are given by Prof. Saaty as," }, { "code": null, "e": 7945, "s": 7543, "text": "How to use the CR? — According to Prof. Saaty, in practice, one should accept matrices with CR ≤ 0.1 and reject values greater than 0.1. A value of CR = 0.1 basically means that the judgments are 10% as inconsistent as if they had been given randomly. By choosing a lower CR, one could try to reduce this inconsistency, and the only way to do that is to go back and re-evaluate the subjective weights." }, { "code": null, "e": 8049, "s": 7945, "text": "Phew, that was a lot of theory, so let’s get on with its implementation in Python for a simple use-case" }, { "code": null, "e": 8345, "s": 8049, "text": "As far as I know there is only one well developed python library out there for AHP — pyAHP, but let’s write the code from scratch using the process described before. Here, I will use a typical use-case from [1] to illustrate the process. (Truth be told, it is pretty easy to implement in Excel!)" }, { "code": null, "e": 8387, "s": 8345, "text": "Code can be found on my GitHub repository" }, { "code": null, "e": 8718, "s": 8387, "text": "Let’s imagine you want to travel to Europe on a holiday and you plan on visiting a few interesting cities. You have a few cities in mind — Madrid, Hamburg and Paris, but your budget only allows you to visit one of those. To help you get maximum bang for your buck, you decide to use AHP to help you narrow down on a suitable city." }, { "code": null, "e": 8960, "s": 8718, "text": "The overall goal is obviously your personal satisfaction. The alternatives are {Rome, Madrid, Paris} and let us imagine you select the following criteria to assess each city — {Climate, Sightseeing, Environment}. Let us build the Hierarchy -" }, { "code": null, "e": 9039, "s": 8960, "text": "Alright, so let's begin the assessment process by importing just two libraries" }, { "code": null, "e": 9077, "s": 9039, "text": "import numpy as npimport pandas as pd" }, { "code": null, "e": 9187, "s": 9077, "text": "We exploit the symmetric nature of the comparison matrix and take input only for the upper triangular matrix." }, { "code": null, "e": 9613, "s": 9187, "text": "# Number of optionsn = 3# Creating default matrix of onesA = np.ones([n,n])# Running a for loop to take input from user and populate the upper triangular elementsfor i in range(0,n): for j in range(0,n): if i<j: aij = input('How important is option{} over option{} ?: '.format(i,j)) A[i,j] = float(aij) #Upper triangular elements A[j,i] = 1/float(aij) #Lower triangular elements" }, { "code": null, "e": 9850, "s": 9613, "text": "Remember, our criteria set was {Climate, Sightseeing, Environment}, so option 0 is Climate, option 1 is Sightseeing and option 2 is Environment. We run this piece of code to generate pair-wise comparison matrix for the criteria weights." }, { "code": null, "e": 9984, "s": 9850, "text": "How important is option0 over option1 ?: 0.5How important is option0 over option2 ?: 0.25How important is option1 over option2 ?: 0.5" }, { "code": null, "e": 10013, "s": 9984, "text": "This can be interpreted as —" }, { "code": null, "e": 10232, "s": 10013, "text": "‘Climate is twice as less important than Sightseeing opportunities and four times less important than the Environment in the city. Sightseeing opportunities are twice as less important than the Environment in the city’" }, { "code": null, "e": 10420, "s": 10232, "text": "Once the matrix is generated, we compute the priority vector by normalizing the eigen vector of the largest eigen value. The elements in this eigen vector are the weights of the criteria." }, { "code": null, "e": 10509, "s": 10420, "text": "e = np.linalg.eig(A)[1][:,0]p = e/e.sum()>>> array([0.14285714, 0.28571429, 0.57142857])" }, { "code": null, "e": 10561, "s": 10509, "text": "The two pieces of code are combined into a function" }, { "code": null, "e": 10990, "s": 10561, "text": "def pairwise_matrix(n):A = np.ones([n,n]) for i in range(0,n): for j in range(0,n): if i<j: aij = input('How important is option{} over option{} ?: '.format(i,j)) A[i,j] = float(aij) A[j,i] = 1/float(aij)#Computing the priority vector eig_val = np.linalg.eig(A)[0].max() eig_vec = np.linalg.eig(A)[1][:,0] p = eig_vec/eig_vec.sum() return p, eig_val" }, { "code": null, "e": 11199, "s": 10990, "text": "We call this function for generating pair-wise comparison matrices and priority vectors for assessing each of the alternative against each criterion. Remember our alternatives set was — {Rome, Madrid, Paris}." }, { "code": null, "e": 11249, "s": 11199, "text": "The priority vectors for each of the matrix are —" }, { "code": null, "e": 11681, "s": 11249, "text": "pr_c = pairwise_matrix(3)[0] #All Criteriapr_c0 = pairwise_matrix(3)[0] #Criteria 0: Climatepr_c1 = pairwise_matrix(3)[0] #Criteria 1: Sightseeingpr_c2 = pairwise_matrix(3)[0] #Criteria 2: Environment#Priority Vector for Criteria 0 pr_c0>>> array([0.44444444, 0.44444444, 0.11111111])#Priority Vector for Criteria 1 pr_c1>>> array([0.6, 0.3, 0.1])#Priority Vector for Criteria 2pr_c2>>> array([0.09090909, 0.18181818, 0.72727273])" }, { "code": null, "e": 11965, "s": 11681, "text": "We also calculate the Consistency Ratio for each of these comparison matrices. For n= 3, the RI_n would be 0.5247. The maximum eigen value across all the matrices was 3. Therefore, by the earlier formula, the CR would be 0 for each of the matrix, which is < 0.1 and hence acceptable." }, { "code": null, "e": 12045, "s": 11965, "text": "The final step is to get their weighted arithmetic sum to yield the rank vector" }, { "code": null, "e": 12141, "s": 12045, "text": "r = pr_c0*pr_c[0] + pr_c1*pr_c[1] + pr_c2*pr_c[2]print(r)>>> [0.28686869 0.25310245 0.46002886]" }, { "code": null, "e": 12269, "s": 12141, "text": "The weighted arithmetic sum for Paris is much higher than Rome or Madrid, so it is assigned rank1, followed by Rome and Madrid." }, { "code": null, "e": 12396, "s": 12269, "text": "There you go! With the help of AHP, you successfully managed to quantify your subjective analysis and decided to fly to Paris!" }, { "code": null, "e": 12594, "s": 12396, "text": "The major flaw with AHP is the rank reversals of alternatives when evaluated by a different group of people. The other issue is with the philosophical basis of including it in operational research." }, { "code": null, "e": 12843, "s": 12594, "text": "Having said that, AHP is still a popular MCDM method and relatively easy to implement and interpret. Apart from python, there are a few commercial softwares such as SuperDecisions that help you create the hierarchy and perform pairwise evaluations." }, { "code": null, "e": 13029, "s": 12843, "text": "There are many more MCDM methods to cater to the shortcomings of AHP and are more advanced in terms of their mathematical foundations. Some that come to mind are PROMETHEE, TOPSIS, etc." }, { "code": null, "e": 13209, "s": 13029, "text": "[1] Brunelli, Matteo. 2015. Introduction to the Analytic Hierarchy Process. SpringerBriefs in Operations Research. P. 83. 978–3–319–12502–2 (electronic).10.1007/978–3–319–12502–2." }, { "code": null, "e": 13292, "s": 13209, "text": "[2] https://en.wikipedia.org/wiki/Analytic_hierarchy_process_%E2%80%93_car_example" }, { "code": null, "e": 13406, "s": 13292, "text": "[3] T.L. Saaty, Decision making with the analytic hierarchy process. Int. J. Services Sciences, Vol. 1, No1, 2008" }, { "code": null, "e": 13472, "s": 13406, "text": "[4]https://en.wikipedia.org/wiki/Perron%E2%80%93Frobenius_theorem" } ]
Python Bokeh – Colors Class
28 Jul, 2020 Bokeh is a Python interactive data visualization. It renders its plots using HTML and JavaScript. It targets modern web browsers for presentation providing elegant, concise construction of novel graphics with high-performance interactivity. In this article, we will learn about colors in Bokeh. There are 5 different classes for colors in Bokeh : bokeh.colors.Colorbokeh.colors.HSLbokeh.colors.RGBbokeh.colors.groupsbokeh.colors.names bokeh.colors.Color bokeh.colors.HSL bokeh.colors.RGB bokeh.colors.groups bokeh.colors.names This is the base class representing the color objects. The methods in this class are : clamp() copy() darken() from_hsl() from_rgb() lighten() to_css() to_hsl() to_rgb() This provides a class to represent colors with HSL format, i.e. Hue, Value and Lightness. Example : We will plot a glyph and use the HSL format to color it. Python3 # importing the modules from bokeh.plotting import figure, output_file, show from bokeh.colors import HSL # file to save the model output_file("gfg.html") # instantiating the figure object graph = figure(title = "Bokeh Color") # the point to be plotted x = 0y = 0 # HSL colorhue = 0saturation = 0.47lightness = 0.58color = HSL(h = hue, s = saturation, l = lightness) # plotting the graph graph.dot(x, y, size = 1000, color = color.to_rgb()) # displaying the model show(graph) Output : This represents colors by specifying their Red, Green, and Blue channels. Example : We will plot a glyph and use the RGB format to color it in light green. Python3 # importing the modules from bokeh.plotting import figure, output_file, show from bokeh.colors import RGB # file to save the model output_file("gfg.html") # instantiating the figure object graph = figure(title = "Bokeh Color") # the point to be plotted x = 0y = 0 # RGB colorred = 144green = 238blue = 144color = RGB(r = red, g = green, b = blue) # plotting the graph graph.dot(x, y, size = 1000, color = color) # displaying the model show(graph) Output : This represents CSS named colors into useful groups according to the general hue. Each color has its own class with multiple colors of different hues. The list of colors present in this class are : black : gainsboro, lightgray, silver, darkgray, gray, dimgray, lightslategray, slategray, darkslategray, blackblue : lightsteelblue, powderblue, lightblue, skyblue, lightskyblue, deepskyblue, dodgerblue, cornflowerblue, steelblue, royalblue, blue, mediumblue, darkblue, navy, midnightbluebrown : cornsilk, blanchedalmond, bisque, navajowhite, wheat, burlywood, tan, rosybrown, sandybrown, goldenrod, darkgoldenrod, peru, chocolate, saddlebrown, sienna, brown, marooncyan : mediumaquamarine, aqua, cyan, lightcyan, paleturquoise, aquamarine, turquoise, mediumturquoise, darkturquoise, lightseagreen, cadetblue, darkcyan, tealgreen : darkolivegreen, olive, olivedrab, yellowgreen, limegreen, lime, lawngreen, chartreuse, greenyellow, springgreen, mediumspringgreen, lightgreen, palegreen, darkseagreen, mediumseagreen, seagreen, forestgreen, green, darkgreenorange : orangered, tomato, coral, darkorange, orangepink : pink, lightpink, hotpink, deeppink, palevioletred, mediumvioletredpurple : lavender, thistle, plum, violet, orchid, fuchsia, magenta, mediumorchid, mediumpurple, blueviolet, darkviolet, darkorchid, darkmagenta, purple, indigo, darkslateblue, slateblue, mediumslatebluered : lightsalmon, salmon, darksalmon, lightcoral, indianred, crimson, firebrick, darkred, redwhite : white, snow, honeydew, mintcream, azure, aliceblue, ghostwhite, whitesmoke, seashell, beige, oldlace, floralwhite, ivory, antiquewhite, linen, lavenderblush, mistyroseyellow : yellow, lightyellow, lemonchiffon, lightgoldenrodyellow, papayawhip, moccasin, peachpuff, palegoldenrod, khaki, darkkhaki, gold black : gainsboro, lightgray, silver, darkgray, gray, dimgray, lightslategray, slategray, darkslategray, black blue : lightsteelblue, powderblue, lightblue, skyblue, lightskyblue, deepskyblue, dodgerblue, cornflowerblue, steelblue, royalblue, blue, mediumblue, darkblue, navy, midnightblue brown : cornsilk, blanchedalmond, bisque, navajowhite, wheat, burlywood, tan, rosybrown, sandybrown, goldenrod, darkgoldenrod, peru, chocolate, saddlebrown, sienna, brown, maroon cyan : mediumaquamarine, aqua, cyan, lightcyan, paleturquoise, aquamarine, turquoise, mediumturquoise, darkturquoise, lightseagreen, cadetblue, darkcyan, teal green : darkolivegreen, olive, olivedrab, yellowgreen, limegreen, lime, lawngreen, chartreuse, greenyellow, springgreen, mediumspringgreen, lightgreen, palegreen, darkseagreen, mediumseagreen, seagreen, forestgreen, green, darkgreen orange : orangered, tomato, coral, darkorange, orange pink : pink, lightpink, hotpink, deeppink, palevioletred, mediumvioletred purple : lavender, thistle, plum, violet, orchid, fuchsia, magenta, mediumorchid, mediumpurple, blueviolet, darkviolet, darkorchid, darkmagenta, purple, indigo, darkslateblue, slateblue, mediumslateblue red : lightsalmon, salmon, darksalmon, lightcoral, indianred, crimson, firebrick, darkred, red white : white, snow, honeydew, mintcream, azure, aliceblue, ghostwhite, whitesmoke, seashell, beige, oldlace, floralwhite, ivory, antiquewhite, linen, lavenderblush, mistyrose yellow : yellow, lightyellow, lemonchiffon, lightgoldenrodyellow, papayawhip, moccasin, peachpuff, palegoldenrod, khaki, darkkhaki, gold Example : We will plot multiple glyphs and use the color groups to color them. Python3 # importing the modules from bokeh.plotting import figure, output_file, show from bokeh.colors.groups import purple, yellow, blue # file to save the model output_file("gfg.html") # instantiating the figure object graph = figure(title = "Bokeh Color") # the point to be plotted x = [-2, 0, 2]y = 0 # color groupscolor = [purple()._colors[purple()._colors.index("Fuchsia")], yellow()._colors[yellow()._colors.index("Khaki")], blue()._colors[blue()._colors.index("RoyalBlue")]] # plotting the graph graph.dot(x, y, size = 1000, color = color) # displaying the model show(graph) Output : This class provides us with all the 147 CSS named colors. Example : We will plot multiple glyphs and use the color names to color them. Python3 # importing the modules from bokeh.plotting import figure, output_file, show from bokeh.colors import named # file to save the model output_file("gfg.html") # instantiating the figure object graph = figure(title = "Bokeh Color") # the point to be plotted x = [-3, 0, 3]y = 0 # color namescolor = ["bisque", "greenyellow", "magenta"] # plotting the graph graph.dot(x, y, size = 1000, color = color) # displaying the model show(graph) Output : Python-Bokeh Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Different ways to create Pandas Dataframe Enumerate() in Python Read a file line by line in Python Python String | replace() How to Install PIP on Windows ? *args and **kwargs in Python Iterate over a list in Python Python Classes and Objects Introduction To PYTHON
[ { "code": null, "e": 28, "s": 0, "text": "\n28 Jul, 2020" }, { "code": null, "e": 269, "s": 28, "text": "Bokeh is a Python interactive data visualization. It renders its plots using HTML and JavaScript. It targets modern web browsers for presentation providing elegant, concise construction of novel graphics with high-performance interactivity." }, { "code": null, "e": 375, "s": 269, "text": "In this article, we will learn about colors in Bokeh. There are 5 different classes for colors in Bokeh :" }, { "code": null, "e": 463, "s": 375, "text": "bokeh.colors.Colorbokeh.colors.HSLbokeh.colors.RGBbokeh.colors.groupsbokeh.colors.names" }, { "code": null, "e": 482, "s": 463, "text": "bokeh.colors.Color" }, { "code": null, "e": 499, "s": 482, "text": "bokeh.colors.HSL" }, { "code": null, "e": 516, "s": 499, "text": "bokeh.colors.RGB" }, { "code": null, "e": 536, "s": 516, "text": "bokeh.colors.groups" }, { "code": null, "e": 555, "s": 536, "text": "bokeh.colors.names" }, { "code": null, "e": 642, "s": 555, "text": "This is the base class representing the color objects. The methods in this class are :" }, { "code": null, "e": 650, "s": 642, "text": "clamp()" }, { "code": null, "e": 657, "s": 650, "text": "copy()" }, { "code": null, "e": 666, "s": 657, "text": "darken()" }, { "code": null, "e": 677, "s": 666, "text": "from_hsl()" }, { "code": null, "e": 688, "s": 677, "text": "from_rgb()" }, { "code": null, "e": 698, "s": 688, "text": "lighten()" }, { "code": null, "e": 707, "s": 698, "text": "to_css()" }, { "code": null, "e": 716, "s": 707, "text": "to_hsl()" }, { "code": null, "e": 725, "s": 716, "text": "to_rgb()" }, { "code": null, "e": 816, "s": 725, "text": "This provides a class to represent colors with HSL format, i.e. Hue, Value and Lightness. " }, { "code": null, "e": 883, "s": 816, "text": "Example : We will plot a glyph and use the HSL format to color it." }, { "code": null, "e": 891, "s": 883, "text": "Python3" }, { "code": "# importing the modules from bokeh.plotting import figure, output_file, show from bokeh.colors import HSL # file to save the model output_file(\"gfg.html\") # instantiating the figure object graph = figure(title = \"Bokeh Color\") # the point to be plotted x = 0y = 0 # HSL colorhue = 0saturation = 0.47lightness = 0.58color = HSL(h = hue, s = saturation, l = lightness) # plotting the graph graph.dot(x, y, size = 1000, color = color.to_rgb()) # displaying the model show(graph)", "e": 1419, "s": 891, "text": null }, { "code": null, "e": 1432, "s": 1423, "text": "Output :" }, { "code": null, "e": 1512, "s": 1438, "text": "This represents colors by specifying their Red, Green, and Blue channels." }, { "code": null, "e": 1596, "s": 1514, "text": "Example : We will plot a glyph and use the RGB format to color it in light green." }, { "code": null, "e": 1606, "s": 1598, "text": "Python3" }, { "code": "# importing the modules from bokeh.plotting import figure, output_file, show from bokeh.colors import RGB # file to save the model output_file(\"gfg.html\") # instantiating the figure object graph = figure(title = \"Bokeh Color\") # the point to be plotted x = 0y = 0 # RGB colorred = 144green = 238blue = 144color = RGB(r = red, g = green, b = blue) # plotting the graph graph.dot(x, y, size = 1000, color = color) # displaying the model show(graph)", "e": 2105, "s": 1606, "text": null }, { "code": null, "e": 2119, "s": 2109, "text": "Output : " }, { "code": null, "e": 2323, "s": 2125, "text": "This represents CSS named colors into useful groups according to the general hue. Each color has its own class with multiple colors of different hues. The list of colors present in this class are :" }, { "code": null, "e": 3915, "s": 2325, "text": "black : gainsboro, lightgray, silver, darkgray, gray, dimgray, lightslategray, slategray, darkslategray, blackblue : lightsteelblue, powderblue, lightblue, skyblue, lightskyblue, deepskyblue, dodgerblue, cornflowerblue, steelblue, royalblue, blue, mediumblue, darkblue, navy, midnightbluebrown : cornsilk, blanchedalmond, bisque, navajowhite, wheat, burlywood, tan, rosybrown, sandybrown, goldenrod, darkgoldenrod, peru, chocolate, saddlebrown, sienna, brown, marooncyan : mediumaquamarine, aqua, cyan, lightcyan, paleturquoise, aquamarine, turquoise, mediumturquoise, darkturquoise, lightseagreen, cadetblue, darkcyan, tealgreen : darkolivegreen, olive, olivedrab, yellowgreen, limegreen, lime, lawngreen, chartreuse, greenyellow, springgreen, mediumspringgreen, lightgreen, palegreen, darkseagreen, mediumseagreen, seagreen, forestgreen, green, darkgreenorange : orangered, tomato, coral, darkorange, orangepink : pink, lightpink, hotpink, deeppink, palevioletred, mediumvioletredpurple : lavender, thistle, plum, violet, orchid, fuchsia, magenta, mediumorchid, mediumpurple, blueviolet, darkviolet, darkorchid, darkmagenta, purple, indigo, darkslateblue, slateblue, mediumslatebluered : lightsalmon, salmon, darksalmon, lightcoral, indianred, crimson, firebrick, darkred, redwhite : white, snow, honeydew, mintcream, azure, aliceblue, ghostwhite, whitesmoke, seashell, beige, oldlace, floralwhite, ivory, antiquewhite, linen, lavenderblush, mistyroseyellow : yellow, lightyellow, lemonchiffon, lightgoldenrodyellow, papayawhip, moccasin, peachpuff, palegoldenrod, khaki, darkkhaki, gold" }, { "code": null, "e": 4026, "s": 3915, "text": "black : gainsboro, lightgray, silver, darkgray, gray, dimgray, lightslategray, slategray, darkslategray, black" }, { "code": null, "e": 4205, "s": 4026, "text": "blue : lightsteelblue, powderblue, lightblue, skyblue, lightskyblue, deepskyblue, dodgerblue, cornflowerblue, steelblue, royalblue, blue, mediumblue, darkblue, navy, midnightblue" }, { "code": null, "e": 4384, "s": 4205, "text": "brown : cornsilk, blanchedalmond, bisque, navajowhite, wheat, burlywood, tan, rosybrown, sandybrown, goldenrod, darkgoldenrod, peru, chocolate, saddlebrown, sienna, brown, maroon" }, { "code": null, "e": 4543, "s": 4384, "text": "cyan : mediumaquamarine, aqua, cyan, lightcyan, paleturquoise, aquamarine, turquoise, mediumturquoise, darkturquoise, lightseagreen, cadetblue, darkcyan, teal" }, { "code": null, "e": 4776, "s": 4543, "text": "green : darkolivegreen, olive, olivedrab, yellowgreen, limegreen, lime, lawngreen, chartreuse, greenyellow, springgreen, mediumspringgreen, lightgreen, palegreen, darkseagreen, mediumseagreen, seagreen, forestgreen, green, darkgreen" }, { "code": null, "e": 4830, "s": 4776, "text": "orange : orangered, tomato, coral, darkorange, orange" }, { "code": null, "e": 4904, "s": 4830, "text": "pink : pink, lightpink, hotpink, deeppink, palevioletred, mediumvioletred" }, { "code": null, "e": 5107, "s": 4904, "text": "purple : lavender, thistle, plum, violet, orchid, fuchsia, magenta, mediumorchid, mediumpurple, blueviolet, darkviolet, darkorchid, darkmagenta, purple, indigo, darkslateblue, slateblue, mediumslateblue" }, { "code": null, "e": 5202, "s": 5107, "text": "red : lightsalmon, salmon, darksalmon, lightcoral, indianred, crimson, firebrick, darkred, red" }, { "code": null, "e": 5378, "s": 5202, "text": "white : white, snow, honeydew, mintcream, azure, aliceblue, ghostwhite, whitesmoke, seashell, beige, oldlace, floralwhite, ivory, antiquewhite, linen, lavenderblush, mistyrose" }, { "code": null, "e": 5515, "s": 5378, "text": "yellow : yellow, lightyellow, lemonchiffon, lightgoldenrodyellow, papayawhip, moccasin, peachpuff, palegoldenrod, khaki, darkkhaki, gold" }, { "code": null, "e": 5596, "s": 5517, "text": "Example : We will plot multiple glyphs and use the color groups to color them." }, { "code": null, "e": 5606, "s": 5598, "text": "Python3" }, { "code": "# importing the modules from bokeh.plotting import figure, output_file, show from bokeh.colors.groups import purple, yellow, blue # file to save the model output_file(\"gfg.html\") # instantiating the figure object graph = figure(title = \"Bokeh Color\") # the point to be plotted x = [-2, 0, 2]y = 0 # color groupscolor = [purple()._colors[purple()._colors.index(\"Fuchsia\")], yellow()._colors[yellow()._colors.index(\"Khaki\")], blue()._colors[blue()._colors.index(\"RoyalBlue\")]] # plotting the graph graph.dot(x, y, size = 1000, color = color) # displaying the model show(graph)", "e": 6227, "s": 5606, "text": null }, { "code": null, "e": 6237, "s": 6227, "text": "Output : " }, { "code": null, "e": 6296, "s": 6237, "text": "This class provides us with all the 147 CSS named colors. " }, { "code": null, "e": 6374, "s": 6296, "text": "Example : We will plot multiple glyphs and use the color names to color them." }, { "code": null, "e": 6382, "s": 6374, "text": "Python3" }, { "code": "# importing the modules from bokeh.plotting import figure, output_file, show from bokeh.colors import named # file to save the model output_file(\"gfg.html\") # instantiating the figure object graph = figure(title = \"Bokeh Color\") # the point to be plotted x = [-3, 0, 3]y = 0 # color namescolor = [\"bisque\", \"greenyellow\", \"magenta\"] # plotting the graph graph.dot(x, y, size = 1000, color = color) # displaying the model show(graph)", "e": 6861, "s": 6382, "text": null }, { "code": null, "e": 6871, "s": 6861, "text": "Output : " }, { "code": null, "e": 6884, "s": 6871, "text": "Python-Bokeh" }, { "code": null, "e": 6891, "s": 6884, "text": "Python" }, { "code": null, "e": 6989, "s": 6891, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 7007, "s": 6989, "text": "Python Dictionary" }, { "code": null, "e": 7049, "s": 7007, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 7071, "s": 7049, "text": "Enumerate() in Python" }, { "code": null, "e": 7106, "s": 7071, "text": "Read a file line by line in Python" }, { "code": null, "e": 7132, "s": 7106, "text": "Python String | replace()" }, { "code": null, "e": 7164, "s": 7132, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 7193, "s": 7164, "text": "*args and **kwargs in Python" }, { "code": null, "e": 7223, "s": 7193, "text": "Iterate over a list in Python" }, { "code": null, "e": 7250, "s": 7223, "text": "Python Classes and Objects" } ]
Multithreading in C++
12 Oct, 2021 Multithreading support was introduced in C+11. Prior to C++11, we had to use POSIX threads or p threads library in C. While this library did the job the lack of any standard language provided feature-set caused serious portability issues. C++ 11 did away with all that and gave us std::thread. The thread classes and related functions are defined in the thread header file. std::thread is the thread class that represents a single thread in C++. To start a thread we simply need to create a new thread object and pass the executing code to be called (i.e, a callable object) into the constructor of the object. Once the object is created a new thread is launched which will execute the code specified in callable. A callable can be either of the three A function pointer A function object A lambda expression After defining callable, pass it to the constructor. #include<thread>std::thread thread_object(callable) Launching thread using function pointerThe following code snippet demonstrates how this is done void foo(param){ // Do something} // The parameters to the function are put after the commastd::thread thread_obj(foo, params); Launching thread using lambda expression The following code snippet demonstrates how this is done // Define a lamda expressionauto f = [](params) { // Do Something}; // Pass f and its parameters to thread // object constructor asstd::thread thread_object(f, params); We can also pass lambda functions directly to the constructor. std::thread thread_object([](params) { // Do Something};, params); Launching threads using function objects The following code snippet demonstrates how this is done // Define the class of function objectclass fn_object_class { // Overload () operator void operator()(params) { // Do Something }} // Create thread objectstd::thread thread_object(fn_object_class(), params) Waiting for threads to finish Once a thread has started we may need to wait for the thread to finish before we can take some action. For instance, if we allocate the task of initializing the GUI of an application to a thread, we need to wait for the thread to finish to ensure that the GUI has loaded properly. To wait for a thread use the std::thread::join() function. This function makes the current thread wait until the thread identified by *this has finished executing.For instance, to block the main thread until thread t1 has finished we would do int main(){ // Start thread t1 std::thread t1(callable); // Wait for t1 to finish t1.join(); // t1 has finished do other stuff ...} A Complete C++ Program A C++ program is given below. It launches three thread from the main function. Each thread is called using one of the callable objects specified above. // CPP program to demonstrate multithreading// using three different callables.#include <iostream>#include <thread>using namespace std; // A dummy functionvoid foo(int Z){ for (int i = 0; i < Z; i++) { cout << "Thread using function" " pointer as callable\n"; }} // A callable objectclass thread_obj {public: void operator()(int x) { for (int i = 0; i < x; i++) cout << "Thread using function" " object as callable\n"; }}; int main(){ cout << "Threads 1 and 2 and 3 " "operating independently" << endl; // This thread is launched by using // function pointer as callable thread th1(foo, 3); // This thread is launched by using // function object as callable thread th2(thread_obj(), 3); // Define a Lambda Expression auto f = [](int x) { for (int i = 0; i < x; i++) cout << "Thread using lambda" " expression as callable\n"; }; // This thread is launched by using // lamda expression as callable thread th3(f, 3); // Wait for the threads to finish // Wait for thread t1 to finish th1.join(); // Wait for thread t2 to finish th2.join(); // Wait for thread t3 to finish th3.join(); return 0;} Output (Machine Dependent) Threads 1 and 2 and 3 operating independently Thread using function pointer as callable Thread using lambda expression as callable Thread using function pointer as callable Thread using lambda expression as callable Thread using function object as callable Thread using lambda expression as callable Thread using function pointer as callable Thread using function object as callable Thread using function object as callable Note:To compile programs with std::thread support use g++ -std=c++11 -pthread Referencescppreference – thread Sayan Mahapatra DarwinHuang barkha chauhan Saksham Sharma 4 cpp-multithreading C++ CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n12 Oct, 2021" }, { "code": null, "e": 426, "s": 52, "text": "Multithreading support was introduced in C+11. Prior to C++11, we had to use POSIX threads or p threads library in C. While this library did the job the lack of any standard language provided feature-set caused serious portability issues. C++ 11 did away with all that and gave us std::thread. The thread classes and related functions are defined in the thread header file." }, { "code": null, "e": 766, "s": 426, "text": "std::thread is the thread class that represents a single thread in C++. To start a thread we simply need to create a new thread object and pass the executing code to be called (i.e, a callable object) into the constructor of the object. Once the object is created a new thread is launched which will execute the code specified in callable." }, { "code": null, "e": 804, "s": 766, "text": "A callable can be either of the three" }, { "code": null, "e": 823, "s": 804, "text": "A function pointer" }, { "code": null, "e": 841, "s": 823, "text": "A function object" }, { "code": null, "e": 861, "s": 841, "text": "A lambda expression" }, { "code": null, "e": 914, "s": 861, "text": "After defining callable, pass it to the constructor." }, { "code": "#include<thread>std::thread thread_object(callable)", "e": 966, "s": 914, "text": null }, { "code": null, "e": 1062, "s": 966, "text": "Launching thread using function pointerThe following code snippet demonstrates how this is done" }, { "code": "void foo(param){ // Do something} // The parameters to the function are put after the commastd::thread thread_obj(foo, params);", "e": 1194, "s": 1062, "text": null }, { "code": null, "e": 1235, "s": 1194, "text": "Launching thread using lambda expression" }, { "code": null, "e": 1292, "s": 1235, "text": "The following code snippet demonstrates how this is done" }, { "code": "// Define a lamda expressionauto f = [](params) { // Do Something}; // Pass f and its parameters to thread // object constructor asstd::thread thread_object(f, params);", "e": 1465, "s": 1292, "text": null }, { "code": null, "e": 1528, "s": 1465, "text": "We can also pass lambda functions directly to the constructor." }, { "code": "std::thread thread_object([](params) { // Do Something};, params);", "e": 1598, "s": 1528, "text": null }, { "code": null, "e": 1639, "s": 1598, "text": "Launching threads using function objects" }, { "code": null, "e": 1696, "s": 1639, "text": "The following code snippet demonstrates how this is done" }, { "code": "// Define the class of function objectclass fn_object_class { // Overload () operator void operator()(params) { // Do Something }} // Create thread objectstd::thread thread_object(fn_object_class(), params)", "e": 1923, "s": 1696, "text": null }, { "code": null, "e": 1953, "s": 1923, "text": "Waiting for threads to finish" }, { "code": null, "e": 2234, "s": 1953, "text": "Once a thread has started we may need to wait for the thread to finish before we can take some action. For instance, if we allocate the task of initializing the GUI of an application to a thread, we need to wait for the thread to finish to ensure that the GUI has loaded properly." }, { "code": null, "e": 2477, "s": 2234, "text": "To wait for a thread use the std::thread::join() function. This function makes the current thread wait until the thread identified by *this has finished executing.For instance, to block the main thread until thread t1 has finished we would do" }, { "code": "int main(){ // Start thread t1 std::thread t1(callable); // Wait for t1 to finish t1.join(); // t1 has finished do other stuff ...}", "e": 2633, "s": 2477, "text": null }, { "code": null, "e": 2656, "s": 2633, "text": "A Complete C++ Program" }, { "code": null, "e": 2808, "s": 2656, "text": "A C++ program is given below. It launches three thread from the main function. Each thread is called using one of the callable objects specified above." }, { "code": "// CPP program to demonstrate multithreading// using three different callables.#include <iostream>#include <thread>using namespace std; // A dummy functionvoid foo(int Z){ for (int i = 0; i < Z; i++) { cout << \"Thread using function\" \" pointer as callable\\n\"; }} // A callable objectclass thread_obj {public: void operator()(int x) { for (int i = 0; i < x; i++) cout << \"Thread using function\" \" object as callable\\n\"; }}; int main(){ cout << \"Threads 1 and 2 and 3 \" \"operating independently\" << endl; // This thread is launched by using // function pointer as callable thread th1(foo, 3); // This thread is launched by using // function object as callable thread th2(thread_obj(), 3); // Define a Lambda Expression auto f = [](int x) { for (int i = 0; i < x; i++) cout << \"Thread using lambda\" \" expression as callable\\n\"; }; // This thread is launched by using // lamda expression as callable thread th3(f, 3); // Wait for the threads to finish // Wait for thread t1 to finish th1.join(); // Wait for thread t2 to finish th2.join(); // Wait for thread t3 to finish th3.join(); return 0;}", "e": 4093, "s": 2808, "text": null }, { "code": null, "e": 4120, "s": 4093, "text": "Output (Machine Dependent)" }, { "code": null, "e": 5070, "s": 4120, "text": "Threads 1 and 2 and 3 operating independently \nThread using function pointer as callable \nThread using lambda expression as callable \nThread using function pointer as callable \nThread using lambda expression as callable \nThread using function object as callable \nThread using lambda expression as callable \nThread using function pointer as callable \nThread using function object as callable \nThread using function object as callable\n" }, { "code": null, "e": 5124, "s": 5070, "text": "Note:To compile programs with std::thread support use" }, { "code": null, "e": 5149, "s": 5124, "text": "g++ -std=c++11 -pthread\n" }, { "code": null, "e": 5181, "s": 5149, "text": "Referencescppreference – thread" }, { "code": null, "e": 5197, "s": 5181, "text": "Sayan Mahapatra" }, { "code": null, "e": 5209, "s": 5197, "text": "DarwinHuang" }, { "code": null, "e": 5224, "s": 5209, "text": "barkha chauhan" }, { "code": null, "e": 5241, "s": 5224, "text": "Saksham Sharma 4" }, { "code": null, "e": 5260, "s": 5241, "text": "cpp-multithreading" }, { "code": null, "e": 5264, "s": 5260, "text": "C++" }, { "code": null, "e": 5268, "s": 5264, "text": "CPP" } ]
Draw circle in C graphics
06 Dec, 2019 The header file graphics.h contains circle() function which draws a circle with center at (x, y) and given radius. Syntax : circle(x, y, radius); where, (x, y) is center of the circle. 'radius' is the Radius of the circle. Examples : Input : x = 250, y = 200, radius = 50 Output : Input : x = 300, y = 150, radius = 90 Output : Below is the implementation to draw circle in C: // C Implementation for drawing circle#include <graphics.h> //driver codeint main(){ // gm is Graphics mode which is // a computer display mode that // generates image using pixels. // DETECT is a macro defined in // "graphics.h" header file int gd = DETECT, gm; // initgraph initializes the // graphics system by loading a // graphics driver from disk initgraph(&gd, &gm, ""); // circle function circle(250, 200, 50); getch(); // closegraph function closes the // graphics mode and deallocates // all memory allocated by // graphics system . closegraph(); return 0;} Output : Akanksha_Rai circle computer-graphics C Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n06 Dec, 2019" }, { "code": null, "e": 167, "s": 52, "text": "The header file graphics.h contains circle() function which draws a circle with center at (x, y) and given radius." }, { "code": null, "e": 176, "s": 167, "text": "Syntax :" }, { "code": null, "e": 277, "s": 176, "text": "circle(x, y, radius);\n\nwhere,\n(x, y) is center of the circle.\n'radius' is the Radius of the circle.\n" }, { "code": null, "e": 288, "s": 277, "text": "Examples :" }, { "code": null, "e": 386, "s": 288, "text": "Input : x = 250, y = 200, radius = 50\nOutput : \n\nInput : x = 300, y = 150, radius = 90\nOutput : \n" }, { "code": null, "e": 435, "s": 386, "text": "Below is the implementation to draw circle in C:" }, { "code": "// C Implementation for drawing circle#include <graphics.h> //driver codeint main(){ // gm is Graphics mode which is // a computer display mode that // generates image using pixels. // DETECT is a macro defined in // \"graphics.h\" header file int gd = DETECT, gm; // initgraph initializes the // graphics system by loading a // graphics driver from disk initgraph(&gd, &gm, \"\"); // circle function circle(250, 200, 50); getch(); // closegraph function closes the // graphics mode and deallocates // all memory allocated by // graphics system . closegraph(); return 0;}", "e": 1071, "s": 435, "text": null }, { "code": null, "e": 1080, "s": 1071, "text": "Output :" }, { "code": null, "e": 1095, "s": 1082, "text": "Akanksha_Rai" }, { "code": null, "e": 1102, "s": 1095, "text": "circle" }, { "code": null, "e": 1120, "s": 1102, "text": "computer-graphics" }, { "code": null, "e": 1131, "s": 1120, "text": "C Language" } ]
Lexicographically smallest array after at-most K consecutive swaps
09 Mar, 2022 Given an array arr[], find the lexicographically smallest array that can be obtained after performing at maximum of k consecutive swaps. Examples : Input: arr[] = {7, 6, 9, 2, 1} k = 3 Output: arr[] = {2, 7, 6, 9, 1} Explanation: Array is: 7, 6, 9, 2, 1 Swap 1: 7, 6, 2, 9, 1 Swap 2: 7, 2, 6, 9, 1 Swap 3: 2, 7, 6, 9, 1 So Our final array after k = 3 swaps : 2, 7, 6, 9, 1 Input: arr[] = {7, 6, 9, 2, 1} k = 1 Output: arr[] = {6, 7, 9, 2, 1} Naive approach is to generate all the permutation of array and pick the smallest one which satisfy the condition of at-most k swaps. Time complexity of this approach is Ω(n!), which will definitely time out for large value of n.An Efficient approach is to think greedily. We first pick the smallest element from array a1, a2, a3...(ak or an) [We consider ak when k is smaller, else n]. We place the smallest element to the a0 position after shifting all these elements by 1 position right. We subtract number of swaps (number of swaps is number of shifts minus 1) from k. If still we are left with k > 0 then we apply the same procedure from the very next starting position i.e., a2, a3,...(ak or an) and then place it to the a1 position. So we keep applying the same process until k becomes 0. C++ Java Python3 C# php Javascript // C++ program to find lexicographically minimum// value after k swaps.#include<bits/stdc++.h>using namespace std ; // Modifies arr[0..n-1] to lexicographically smallest// with k swaps.void minimizeWithKSwaps(int arr[], int n, int k){ for (int i = 0; i<n-1 && k>0; ++i) { // Set the position where we want // to put the smallest integer int pos = i; for (int j = i+1; j<n ; ++j) { // If we exceed the Max swaps // then terminate the loop if (j-i > k) break; // Find the minimum value from i+1 to // max k or n if (arr[j] < arr[pos]) pos = j; } // Swap the elements from Minimum position // we found till now to the i index for (int j = pos; j>i; --j) swap(arr[j], arr[j-1]); // Set the final value after swapping pos-i // elements k -= pos-i; }} // Driver codeint main(){ int arr[] = {7, 6, 9, 2, 1}; int n = sizeof(arr)/sizeof(arr[0]); int k = 3; minimizeWithKSwaps(arr, n, k); //Print the final Array for (int i=0; i<n; ++i) cout << arr[i] <<" ";} // Java program to find lexicographically minimum// value after k swaps.class GFG { // Modifies arr[0..n-1] to lexicographically // smallest with k swaps. static void minimizeWithKSwaps(int arr[], int n, int k) { for (int i = 0; i < n-1 && k > 0; ++i) { // Set the position where we want // to put the smallest integer int pos = i; for (int j = i+1; j < n ; ++j) { // If we exceed the Max swaps // then terminate the loop if (j - i > k) break; // Find the minimum value from i+1 to // max k or n if (arr[j] < arr[pos]) pos = j; } // Swap the elements from Minimum position // we found till now to the i index int temp; for (int j = pos; j>i; --j) { temp=arr[j]; arr[j]=arr[j-1]; arr[j-1]=temp; } // Set the final value after swapping pos-i // elements k -= pos-i; } } // Driver method public static void main(String[] args) { int arr[] = {7, 6, 9, 2, 1}; int n = arr.length; int k = 3; minimizeWithKSwaps(arr, n, k); //Print the final Array for (int i=0; i<n; ++i) System.out.print(arr[i] +" "); }} // This code is contributed by Anant Agarwal. # Python program to find lexicographically minimum# value after k swaps.def minimizeWithKSwaps(arr, n, k): for i in range(n-1): # Set the position where we want # to put the smallest integer pos = i for j in range(i+1, n): # If we exceed the Max swaps # then terminate the loop if (j-i > k): break # Find the minimum value from i+1 to # max (k or n) if (arr[j] < arr[pos]): pos = j # Swap the elements from Minimum position # we found till now to the i index for j in range(pos, i, -1): arr[j],arr[j-1] = arr[j-1], arr[j] # Set the final value after swapping pos-i # elements k -= pos - i # Driver Coden, k = 5, 3arr = [7, 6, 9, 2, 1]minimizeWithKSwaps(arr, n, k) # Print the final Arrayfor i in range(n): print(arr[i], end = " ") // C# program to find lexicographically// minimum value after k swaps.using System; class GFG { // Modifies arr[0..n-1] to lexicographically // smallest with k swaps. static void minimizeWithKSwaps(int []arr, int n, int k) { for (int i = 0; i < n-1 && k > 0; ++i) { // Set the position where we want // to put the smallest integer int pos = i; for (int j = i+1; j < n ; ++j) { // If we exceed the Max swaps // then terminate the loop if (j - i > k) break; // Find the minimum value from // i + 1 to max k or n if (arr[j] < arr[pos]) pos = j; } // Swap the elements from Minimum position // we found till now to the i index int temp; for (int j = pos; j>i; --j) { temp=arr[j]; arr[j]=arr[j-1]; arr[j-1]=temp; } // Set the final value after // swapping pos-i elements k -= pos-i; } } // Driver method public static void Main() { int []arr = {7, 6, 9, 2, 1}; int n = arr.Length; int k = 3; // Function calling minimizeWithKSwaps(arr, n, k); // Print the final Array for (int i=0; i<n; ++i) Console.Write(arr[i] +" "); }} // This code is contributed by nitin mittal. <?php// php program to find lexicographically minimum// value after k swaps. // Modifies arr[0..n-1] to lexicographically// smallest with k swaps.function minimizeWithKSwaps($arr, $n, $k){ for ($i = 0; $i < $n-1 && $k > 0; ++$i) { // Set the position where we want // to put the smallest integer $pos = $i; for ($j = $i+1; $j < $n ; ++$j) { // If we exceed the Max swaps // then terminate the loop if ($j-$i > $k) break; // Find the minimum value from // i+1 to max k or n if ($arr[$j] < $arr[$pos]) $pos = $j; } // Swap the elements from Minimum // position we found till now to // the i index for ($j = $pos; $j > $i; --$j) { $temp = $arr[$j]; $arr[$j] = $arr[$j-1]; $arr[$j-1] = $temp; } // Set the final value after // swapping pos-i elements $k -= $pos-$i; } //Print the final Array for ($i = 0; $i < $n; ++$i) echo $arr[$i] . " ";} // Driver code$arr = array(7, 6, 9, 2, 1);$n = count($arr);$k = 3; minimizeWithKSwaps($arr, $n, $k); // This code is contributed by Sam007?> <script> // Javascript program to find lexicographically // minimum value after k swaps. // Modifies arr[0..n-1] to lexicographically // smallest with k swaps. function minimizeWithKSwaps(arr, n, k) { for (let i = 0; i < n - 1 && k > 0; ++i) { // Set the position where we want // to put the smallest integer let pos = i; for (let j = i+1; j < n ; ++j) { // If we exceed the Max swaps // then terminate the loop if (j - i > k) break; // Find the minimum value from // i + 1 to max k or n if (arr[j] < arr[pos]) pos = j; } // Swap the elements from Minimum position // we found till now to the i index let temp; for (let j = pos; j > i; --j) { temp = arr[j]; arr[j] = arr[j - 1]; arr[j - 1] = temp; } // Set the final value after // swapping pos-i elements k -= pos - i; } } let arr = [7, 6, 9, 2, 1]; let n = arr.length; let k = 3; // Function calling minimizeWithKSwaps(arr, n, k); // Print the final Array document.write("Output: "); for (let i = 0; i < n; ++i) document.write(arr[i] + " "); // This code is contributed by divyesh072019.</script> Output: 2 7 6 9 1 Time complexity: O(N2) Auxiliary space: O(1)Reference: http://stackoverflow.com/questions/25539423/finding-minimal-lexicographical-arrayThis article is contributed by Shubham Bansal. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. nitin mittal Sam007 divyesh072019 amartyaghoshgfg surinderdawra388 lexicographic-ordering Arrays Greedy Arrays Greedy Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n09 Mar, 2022" }, { "code": null, "e": 204, "s": 54, "text": "Given an array arr[], find the lexicographically smallest array that can be obtained after performing at maximum of k consecutive swaps. Examples : " }, { "code": null, "e": 522, "s": 204, "text": "Input: arr[] = {7, 6, 9, 2, 1}\n k = 3\nOutput: arr[] = {2, 7, 6, 9, 1}\nExplanation: Array is: 7, 6, 9, 2, 1\nSwap 1: 7, 6, 2, 9, 1\nSwap 2: 7, 2, 6, 9, 1\nSwap 3: 2, 7, 6, 9, 1\nSo Our final array after k = 3 swaps : \n2, 7, 6, 9, 1\n\nInput: arr[] = {7, 6, 9, 2, 1}\n k = 1\nOutput: arr[] = {6, 7, 9, 2, 1}" }, { "code": null, "e": 1321, "s": 524, "text": "Naive approach is to generate all the permutation of array and pick the smallest one which satisfy the condition of at-most k swaps. Time complexity of this approach is Ω(n!), which will definitely time out for large value of n.An Efficient approach is to think greedily. We first pick the smallest element from array a1, a2, a3...(ak or an) [We consider ak when k is smaller, else n]. We place the smallest element to the a0 position after shifting all these elements by 1 position right. We subtract number of swaps (number of swaps is number of shifts minus 1) from k. If still we are left with k > 0 then we apply the same procedure from the very next starting position i.e., a2, a3,...(ak or an) and then place it to the a1 position. So we keep applying the same process until k becomes 0. " }, { "code": null, "e": 1325, "s": 1321, "text": "C++" }, { "code": null, "e": 1330, "s": 1325, "text": "Java" }, { "code": null, "e": 1338, "s": 1330, "text": "Python3" }, { "code": null, "e": 1341, "s": 1338, "text": "C#" }, { "code": null, "e": 1345, "s": 1341, "text": "php" }, { "code": null, "e": 1356, "s": 1345, "text": "Javascript" }, { "code": "// C++ program to find lexicographically minimum// value after k swaps.#include<bits/stdc++.h>using namespace std ; // Modifies arr[0..n-1] to lexicographically smallest// with k swaps.void minimizeWithKSwaps(int arr[], int n, int k){ for (int i = 0; i<n-1 && k>0; ++i) { // Set the position where we want // to put the smallest integer int pos = i; for (int j = i+1; j<n ; ++j) { // If we exceed the Max swaps // then terminate the loop if (j-i > k) break; // Find the minimum value from i+1 to // max k or n if (arr[j] < arr[pos]) pos = j; } // Swap the elements from Minimum position // we found till now to the i index for (int j = pos; j>i; --j) swap(arr[j], arr[j-1]); // Set the final value after swapping pos-i // elements k -= pos-i; }} // Driver codeint main(){ int arr[] = {7, 6, 9, 2, 1}; int n = sizeof(arr)/sizeof(arr[0]); int k = 3; minimizeWithKSwaps(arr, n, k); //Print the final Array for (int i=0; i<n; ++i) cout << arr[i] <<\" \";}", "e": 2537, "s": 1356, "text": null }, { "code": "// Java program to find lexicographically minimum// value after k swaps.class GFG { // Modifies arr[0..n-1] to lexicographically // smallest with k swaps. static void minimizeWithKSwaps(int arr[], int n, int k) { for (int i = 0; i < n-1 && k > 0; ++i) { // Set the position where we want // to put the smallest integer int pos = i; for (int j = i+1; j < n ; ++j) { // If we exceed the Max swaps // then terminate the loop if (j - i > k) break; // Find the minimum value from i+1 to // max k or n if (arr[j] < arr[pos]) pos = j; } // Swap the elements from Minimum position // we found till now to the i index int temp; for (int j = pos; j>i; --j) { temp=arr[j]; arr[j]=arr[j-1]; arr[j-1]=temp; } // Set the final value after swapping pos-i // elements k -= pos-i; } } // Driver method public static void main(String[] args) { int arr[] = {7, 6, 9, 2, 1}; int n = arr.length; int k = 3; minimizeWithKSwaps(arr, n, k); //Print the final Array for (int i=0; i<n; ++i) System.out.print(arr[i] +\" \"); }} // This code is contributed by Anant Agarwal.", "e": 4116, "s": 2537, "text": null }, { "code": "# Python program to find lexicographically minimum# value after k swaps.def minimizeWithKSwaps(arr, n, k): for i in range(n-1): # Set the position where we want # to put the smallest integer pos = i for j in range(i+1, n): # If we exceed the Max swaps # then terminate the loop if (j-i > k): break # Find the minimum value from i+1 to # max (k or n) if (arr[j] < arr[pos]): pos = j # Swap the elements from Minimum position # we found till now to the i index for j in range(pos, i, -1): arr[j],arr[j-1] = arr[j-1], arr[j] # Set the final value after swapping pos-i # elements k -= pos - i # Driver Coden, k = 5, 3arr = [7, 6, 9, 2, 1]minimizeWithKSwaps(arr, n, k) # Print the final Arrayfor i in range(n): print(arr[i], end = \" \")", "e": 5029, "s": 4116, "text": null }, { "code": "// C# program to find lexicographically// minimum value after k swaps.using System; class GFG { // Modifies arr[0..n-1] to lexicographically // smallest with k swaps. static void minimizeWithKSwaps(int []arr, int n, int k) { for (int i = 0; i < n-1 && k > 0; ++i) { // Set the position where we want // to put the smallest integer int pos = i; for (int j = i+1; j < n ; ++j) { // If we exceed the Max swaps // then terminate the loop if (j - i > k) break; // Find the minimum value from // i + 1 to max k or n if (arr[j] < arr[pos]) pos = j; } // Swap the elements from Minimum position // we found till now to the i index int temp; for (int j = pos; j>i; --j) { temp=arr[j]; arr[j]=arr[j-1]; arr[j-1]=temp; } // Set the final value after // swapping pos-i elements k -= pos-i; } } // Driver method public static void Main() { int []arr = {7, 6, 9, 2, 1}; int n = arr.Length; int k = 3; // Function calling minimizeWithKSwaps(arr, n, k); // Print the final Array for (int i=0; i<n; ++i) Console.Write(arr[i] +\" \"); }} // This code is contributed by nitin mittal.", "e": 6641, "s": 5029, "text": null }, { "code": "<?php// php program to find lexicographically minimum// value after k swaps. // Modifies arr[0..n-1] to lexicographically// smallest with k swaps.function minimizeWithKSwaps($arr, $n, $k){ for ($i = 0; $i < $n-1 && $k > 0; ++$i) { // Set the position where we want // to put the smallest integer $pos = $i; for ($j = $i+1; $j < $n ; ++$j) { // If we exceed the Max swaps // then terminate the loop if ($j-$i > $k) break; // Find the minimum value from // i+1 to max k or n if ($arr[$j] < $arr[$pos]) $pos = $j; } // Swap the elements from Minimum // position we found till now to // the i index for ($j = $pos; $j > $i; --$j) { $temp = $arr[$j]; $arr[$j] = $arr[$j-1]; $arr[$j-1] = $temp; } // Set the final value after // swapping pos-i elements $k -= $pos-$i; } //Print the final Array for ($i = 0; $i < $n; ++$i) echo $arr[$i] . \" \";} // Driver code$arr = array(7, 6, 9, 2, 1);$n = count($arr);$k = 3; minimizeWithKSwaps($arr, $n, $k); // This code is contributed by Sam007?>", "e": 7892, "s": 6641, "text": null }, { "code": "<script> // Javascript program to find lexicographically // minimum value after k swaps. // Modifies arr[0..n-1] to lexicographically // smallest with k swaps. function minimizeWithKSwaps(arr, n, k) { for (let i = 0; i < n - 1 && k > 0; ++i) { // Set the position where we want // to put the smallest integer let pos = i; for (let j = i+1; j < n ; ++j) { // If we exceed the Max swaps // then terminate the loop if (j - i > k) break; // Find the minimum value from // i + 1 to max k or n if (arr[j] < arr[pos]) pos = j; } // Swap the elements from Minimum position // we found till now to the i index let temp; for (let j = pos; j > i; --j) { temp = arr[j]; arr[j] = arr[j - 1]; arr[j - 1] = temp; } // Set the final value after // swapping pos-i elements k -= pos - i; } } let arr = [7, 6, 9, 2, 1]; let n = arr.length; let k = 3; // Function calling minimizeWithKSwaps(arr, n, k); // Print the final Array document.write(\"Output: \"); for (let i = 0; i < n; ++i) document.write(arr[i] + \" \"); // This code is contributed by divyesh072019.</script>", "e": 9423, "s": 7892, "text": null }, { "code": null, "e": 9441, "s": 9423, "text": "Output: 2 7 6 9 1" }, { "code": null, "e": 10000, "s": 9441, "text": "Time complexity: O(N2) Auxiliary space: O(1)Reference: http://stackoverflow.com/questions/25539423/finding-minimal-lexicographical-arrayThis article is contributed by Shubham Bansal. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. 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": 10013, "s": 10000, "text": "nitin mittal" }, { "code": null, "e": 10020, "s": 10013, "text": "Sam007" }, { "code": null, "e": 10034, "s": 10020, "text": "divyesh072019" }, { "code": null, "e": 10050, "s": 10034, "text": "amartyaghoshgfg" }, { "code": null, "e": 10067, "s": 10050, "text": "surinderdawra388" }, { "code": null, "e": 10090, "s": 10067, "text": "lexicographic-ordering" }, { "code": null, "e": 10097, "s": 10090, "text": "Arrays" }, { "code": null, "e": 10104, "s": 10097, "text": "Greedy" }, { "code": null, "e": 10111, "s": 10104, "text": "Arrays" }, { "code": null, "e": 10118, "s": 10111, "text": "Greedy" } ]
round() in C++
14 Nov, 2017 round is used to round off the given digit which can be in float or double. It returns the nearest integral value to provided parameter in round function, with halfway cases rounded away from zero. Instead of round(), std::round() can also be used .Header files used -> cmath, ctgmath Syntax : Parameters: x, value to be rounded double round (double x); float round (float x); long double round (long double x); double round (T x); // additional overloads for integral types Returns: The value of x rounded to the nearest integral (as a floating-point value). // C++ code to demonstrate the// use of round() function#include <cmath>#include <iostream>using namespace std; // Driver programint main(){ // initializing value double x = 12.5, y = 13.3, z = 14.8; // Displaying the nearest values // of x, y and z cout << "Nearest value of x :" << round(x) << "\n"; cout << "Nearest value of y :" << round(y) << "\n"; cout << "Nearest value of z :" << round(z) << "\n"; // For lround cout << "lround(-0.0) = " << lround(-0.0) << "\n"; cout << "lround(2.3) = " << lround(2.3) << "\n"; cout << "lround(2.5) = " << lround(2.5) << "\n"; cout << "lround(2.7) = " << lround(2.7) << "\n"; cout << "lround(-2.3) = " << lround(-2.3) << "\n"; cout << "lround(-2.5) = " << lround(-2.5) << "\n"; cout << "lround(-2.7) = " << lround(-2.7) << "\n"; // For llround cout << "llround(-0.01234) = " << llround(-0.01234) << "\n"; cout << "llround(2.3563) = " << llround(2.3563) << "\n"; cout << "llround(2.555) = " << llround(2.555) << "\n"; cout << "llround(2.7896) = " << llround(2.7896) << "\n"; cout << "llround(-2.323) = " << llround(-2.323) << "\n"; cout << "llround(-2.5258) = " << llround(-2.5258) << "\n"; cout << "llround(-2.71236) = " << llround(-2.71236) << "\n"; return 0;} Output: Nearest value of x :13 Nearest value of y :13 Nearest value of z :15 lround(-0.0) = 0 lround(2.3) = 2 lround(2.5) = 3 lround(2.7) = 3 lround(-2.3) = -2 lround(-2.5) = -3 lround(-2.7) = -3 llround(-0.01234) = 0 llround(2.3563) = 2 llround(2.555) = 3 llround(2.7896) = 3 llround(-2.323) = -2 llround(-2.5258) = -3 llround(-2.71236) = -3 Here, in the above program we have just calculated the nearest integral value of given float or double value.which has been calculated accurately. Possible Applications Handling the mismatch between fractions and decimal : One use of rounding numbers is shorten all the three’s to the right of the decimal point in converting 1/3 to decimal. Most of the time, we will use the rounded numbers 0.33 or 0.333 when we need to work with 1/3 in decimal. We usually work with just two or three digits to the right of the decimal point when there is no exact equivalent to the fraction in decimal.Changing multiplied result : There will be difference between multiplication of 25, 75 and 0.25, 0.75 we get 0.875 .We started with 2 digits to the right of the decimal point and ended up with 4. Many times we will just round up the result to 0.19 .// C+++ code for above explanation#include <cmath>#include <iostream>using namespace std; // Driver programint main(){ // Initializing values for int type long int a1 = 25, b1 = 30; // Initializing values for double type double a2 = .25, b2 = .30; long int ans_1 = (a1 * b1); double ans_2 = (a2 * b2); // Rounded result for both cout << "From first multiplication :" << round(ans_1) << "\n"; cout << "From second multiplication :" << round(ans_2) << "\n"; return 0;}Output: From first multiplication :750 From second multiplication :0 Fast calculation : Suppose in need of fast calculation we take approx value and then calculate nearest answer. For example, we get an answer 298.78 after any calculation and by rounding off we get an absolute answer of 300.Getting estimate : Sometimes you want to round integers instead of decimal numbers. Usually you are interested in rounding to the nearest multiple of 10, 100, 1, 000 or million. For example, in 2006 the census department determined that the population of New York City was 8, 214, 426. That number is hard to remember and if we say the population of New York City is 8 million it is a good estimate because it doesn’t make any real difference what the exact number is. Handling the mismatch between fractions and decimal : One use of rounding numbers is shorten all the three’s to the right of the decimal point in converting 1/3 to decimal. Most of the time, we will use the rounded numbers 0.33 or 0.333 when we need to work with 1/3 in decimal. We usually work with just two or three digits to the right of the decimal point when there is no exact equivalent to the fraction in decimal. Changing multiplied result : There will be difference between multiplication of 25, 75 and 0.25, 0.75 we get 0.875 .We started with 2 digits to the right of the decimal point and ended up with 4. Many times we will just round up the result to 0.19 .// C+++ code for above explanation#include <cmath>#include <iostream>using namespace std; // Driver programint main(){ // Initializing values for int type long int a1 = 25, b1 = 30; // Initializing values for double type double a2 = .25, b2 = .30; long int ans_1 = (a1 * b1); double ans_2 = (a2 * b2); // Rounded result for both cout << "From first multiplication :" << round(ans_1) << "\n"; cout << "From second multiplication :" << round(ans_2) << "\n"; return 0;}Output: From first multiplication :750 From second multiplication :0 // C+++ code for above explanation#include <cmath>#include <iostream>using namespace std; // Driver programint main(){ // Initializing values for int type long int a1 = 25, b1 = 30; // Initializing values for double type double a2 = .25, b2 = .30; long int ans_1 = (a1 * b1); double ans_2 = (a2 * b2); // Rounded result for both cout << "From first multiplication :" << round(ans_1) << "\n"; cout << "From second multiplication :" << round(ans_2) << "\n"; return 0;} Output: From first multiplication :750 From second multiplication :0 Fast calculation : Suppose in need of fast calculation we take approx value and then calculate nearest answer. For example, we get an answer 298.78 after any calculation and by rounding off we get an absolute answer of 300. Getting estimate : Sometimes you want to round integers instead of decimal numbers. Usually you are interested in rounding to the nearest multiple of 10, 100, 1, 000 or million. For example, in 2006 the census department determined that the population of New York City was 8, 214, 426. That number is hard to remember and if we say the population of New York City is 8 million it is a good estimate because it doesn’t make any real difference what the exact number is. Reference : www.mathworksheetcenter.com, www.cplusplus.com This article is contributed by Himanshu Ranjan. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. 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. CPP-Library STL C++ STL CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 53, "s": 25, "text": "\n14 Nov, 2017" }, { "code": null, "e": 338, "s": 53, "text": "round is used to round off the given digit which can be in float or double. It returns the nearest integral value to provided parameter in round function, with halfway cases rounded away from zero. Instead of round(), std::round() can also be used .Header files used -> cmath, ctgmath" }, { "code": null, "e": 347, "s": 338, "text": "Syntax :" }, { "code": null, "e": 627, "s": 347, "text": "Parameters: x, value to be rounded\ndouble round (double x);\nfloat round (float x);\nlong double round (long double x);\ndouble round (T x); \n// additional overloads for integral types\n\nReturns: The value of x rounded to the nearest \nintegral (as a floating-point value).\n" }, { "code": "// C++ code to demonstrate the// use of round() function#include <cmath>#include <iostream>using namespace std; // Driver programint main(){ // initializing value double x = 12.5, y = 13.3, z = 14.8; // Displaying the nearest values // of x, y and z cout << \"Nearest value of x :\" << round(x) << \"\\n\"; cout << \"Nearest value of y :\" << round(y) << \"\\n\"; cout << \"Nearest value of z :\" << round(z) << \"\\n\"; // For lround cout << \"lround(-0.0) = \" << lround(-0.0) << \"\\n\"; cout << \"lround(2.3) = \" << lround(2.3) << \"\\n\"; cout << \"lround(2.5) = \" << lround(2.5) << \"\\n\"; cout << \"lround(2.7) = \" << lround(2.7) << \"\\n\"; cout << \"lround(-2.3) = \" << lround(-2.3) << \"\\n\"; cout << \"lround(-2.5) = \" << lround(-2.5) << \"\\n\"; cout << \"lround(-2.7) = \" << lround(-2.7) << \"\\n\"; // For llround cout << \"llround(-0.01234) = \" << llround(-0.01234) << \"\\n\"; cout << \"llround(2.3563) = \" << llround(2.3563) << \"\\n\"; cout << \"llround(2.555) = \" << llround(2.555) << \"\\n\"; cout << \"llround(2.7896) = \" << llround(2.7896) << \"\\n\"; cout << \"llround(-2.323) = \" << llround(-2.323) << \"\\n\"; cout << \"llround(-2.5258) = \" << llround(-2.5258) << \"\\n\"; cout << \"llround(-2.71236) = \" << llround(-2.71236) << \"\\n\"; return 0;}", "e": 1912, "s": 627, "text": null }, { "code": null, "e": 1920, "s": 1912, "text": "Output:" }, { "code": null, "e": 2256, "s": 1920, "text": "Nearest value of x :13\nNearest value of y :13\nNearest value of z :15\nlround(-0.0) = 0\nlround(2.3) = 2\nlround(2.5) = 3\nlround(2.7) = 3\nlround(-2.3) = -2\nlround(-2.5) = -3\nlround(-2.7) = -3\nllround(-0.01234) = 0\nllround(2.3563) = 2\nllround(2.555) = 3\nllround(2.7896) = 3\nllround(-2.323) = -2\nllround(-2.5258) = -3\nllround(-2.71236) = -3\n" }, { "code": null, "e": 2403, "s": 2256, "text": "Here, in the above program we have just calculated the nearest integral value of given float or double value.which has been calculated accurately." }, { "code": null, "e": 2425, "s": 2403, "text": "Possible Applications" }, { "code": null, "e": 4363, "s": 2425, "text": "Handling the mismatch between fractions and decimal : One use of rounding numbers is shorten all the three’s to the right of the decimal point in converting 1/3 to decimal. Most of the time, we will use the rounded numbers 0.33 or 0.333 when we need to work with 1/3 in decimal. We usually work with just two or three digits to the right of the decimal point when there is no exact equivalent to the fraction in decimal.Changing multiplied result : There will be difference between multiplication of 25, 75 and 0.25, 0.75 we get 0.875 .We started with 2 digits to the right of the decimal point and ended up with 4. Many times we will just round up the result to 0.19 .// C+++ code for above explanation#include <cmath>#include <iostream>using namespace std; // Driver programint main(){ // Initializing values for int type long int a1 = 25, b1 = 30; // Initializing values for double type double a2 = .25, b2 = .30; long int ans_1 = (a1 * b1); double ans_2 = (a2 * b2); // Rounded result for both cout << \"From first multiplication :\" << round(ans_1) << \"\\n\"; cout << \"From second multiplication :\" << round(ans_2) << \"\\n\"; return 0;}Output: From first multiplication :750\n From second multiplication :0\nFast calculation : Suppose in need of fast calculation we take approx value and then calculate nearest answer. For example, we get an answer 298.78 after any calculation and by rounding off we get an absolute answer of 300.Getting estimate : Sometimes you want to round integers instead of decimal numbers. Usually you are interested in rounding to the nearest multiple of 10, 100, 1, 000 or million. For example, in 2006 the census department determined that the population of New York City was 8, 214, 426. That number is hard to remember and if we say the population of New York City is 8 million it is a good estimate because it doesn’t make any real difference what the exact number is." }, { "code": null, "e": 4784, "s": 4363, "text": "Handling the mismatch between fractions and decimal : One use of rounding numbers is shorten all the three’s to the right of the decimal point in converting 1/3 to decimal. Most of the time, we will use the rounded numbers 0.33 or 0.333 when we need to work with 1/3 in decimal. We usually work with just two or three digits to the right of the decimal point when there is no exact equivalent to the fraction in decimal." }, { "code": null, "e": 5611, "s": 4784, "text": "Changing multiplied result : There will be difference between multiplication of 25, 75 and 0.25, 0.75 we get 0.875 .We started with 2 digits to the right of the decimal point and ended up with 4. Many times we will just round up the result to 0.19 .// C+++ code for above explanation#include <cmath>#include <iostream>using namespace std; // Driver programint main(){ // Initializing values for int type long int a1 = 25, b1 = 30; // Initializing values for double type double a2 = .25, b2 = .30; long int ans_1 = (a1 * b1); double ans_2 = (a2 * b2); // Rounded result for both cout << \"From first multiplication :\" << round(ans_1) << \"\\n\"; cout << \"From second multiplication :\" << round(ans_2) << \"\\n\"; return 0;}Output: From first multiplication :750\n From second multiplication :0\n" }, { "code": "// C+++ code for above explanation#include <cmath>#include <iostream>using namespace std; // Driver programint main(){ // Initializing values for int type long int a1 = 25, b1 = 30; // Initializing values for double type double a2 = .25, b2 = .30; long int ans_1 = (a1 * b1); double ans_2 = (a2 * b2); // Rounded result for both cout << \"From first multiplication :\" << round(ans_1) << \"\\n\"; cout << \"From second multiplication :\" << round(ans_2) << \"\\n\"; return 0;}", "e": 6113, "s": 5611, "text": null }, { "code": null, "e": 6121, "s": 6113, "text": "Output:" }, { "code": null, "e": 6191, "s": 6121, "text": " From first multiplication :750\n From second multiplication :0\n" }, { "code": null, "e": 6415, "s": 6191, "text": "Fast calculation : Suppose in need of fast calculation we take approx value and then calculate nearest answer. For example, we get an answer 298.78 after any calculation and by rounding off we get an absolute answer of 300." }, { "code": null, "e": 6884, "s": 6415, "text": "Getting estimate : Sometimes you want to round integers instead of decimal numbers. Usually you are interested in rounding to the nearest multiple of 10, 100, 1, 000 or million. For example, in 2006 the census department determined that the population of New York City was 8, 214, 426. That number is hard to remember and if we say the population of New York City is 8 million it is a good estimate because it doesn’t make any real difference what the exact number is." }, { "code": null, "e": 6943, "s": 6884, "text": "Reference : www.mathworksheetcenter.com, www.cplusplus.com" }, { "code": null, "e": 7246, "s": 6943, "text": "This article is contributed by Himanshu Ranjan. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks." }, { "code": null, "e": 7371, "s": 7246, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 7383, "s": 7371, "text": "CPP-Library" }, { "code": null, "e": 7387, "s": 7383, "text": "STL" }, { "code": null, "e": 7391, "s": 7387, "text": "C++" }, { "code": null, "e": 7395, "s": 7391, "text": "STL" }, { "code": null, "e": 7399, "s": 7395, "text": "CPP" } ]
HTML | bgcolor attribute
10 Jan, 2022 The HTML bgcolor attribute is used to set the background color of an HTML element. Bgcolor is one of those attributes that has become deprecated with the implementation of Cascading Style Sheets (see CSS Backgrounds).Syntax: <"tag" bgcolor="Value"> Attribute Values: color_name: It sets the background color by using the color name. For example “red”. hex_number: It sets the background color by using the color hex code. For example “#0000ff”. rgb_number: It sets the background color by using the RGB code. For example: “RGB(0, 153, 0)” . Supported tags: body marquee table tBody td tFoot th tHead tr col colgroup Note: The bgcolor attribute is not supported by HTML5. Example: HTML <table> bgcolor attribute html <!DOCTYPE html><html> <head> <title> HTML table bgcolor Attribute </title></head> <body> <h1>GeeksforGeeks</h1> <h2>HTML table bgcolor Attribute</h2> <table border="1" bgcolor="green"> <caption> Author Details </caption> <tr> <th>NAME</th> <th>AGE</th> <th>BRANCH</th> </tr> <tr> <td>BITTU</td> <td>22</td> <td>CSE</td> </tr> <tr> <td>RAM</td> <td>21</td> <td>ECE</td> </tr> </table></body> </html> Output: Example:HTML body Bgcolor Attribute html <!DOCTYPE html><html> <head> <title> HTML body Bgcolor Attribute</title></head> <!-- body tag starts here --> <body text="green" bgcolor="orange"> <center> <h1>GeeksforGeeks</h1> <h2> HTML <body> bgcolor Attribute </h2> <p> It is a Computer Science portal For Geeks </p> </center></body><!-- body tag ends here --> </html> Output: Note: The bgcolor attribute is not supported in HTML5.Supported Browsers: The browsers supported by bgcolor attribute are listed below: Google Chrome Internet Explorer Firefox Apple Safari Opera ManasChhabra2 chhabradhanvi HTML-Attributes HTML Web Technologies HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n10 Jan, 2022" }, { "code": null, "e": 255, "s": 28, "text": "The HTML bgcolor attribute is used to set the background color of an HTML element. Bgcolor is one of those attributes that has become deprecated with the implementation of Cascading Style Sheets (see CSS Backgrounds).Syntax: " }, { "code": null, "e": 279, "s": 255, "text": "<\"tag\" bgcolor=\"Value\">" }, { "code": null, "e": 297, "s": 279, "text": "Attribute Values:" }, { "code": null, "e": 382, "s": 297, "text": "color_name: It sets the background color by using the color name. For example “red”." }, { "code": null, "e": 475, "s": 382, "text": "hex_number: It sets the background color by using the color hex code. For example “#0000ff”." }, { "code": null, "e": 571, "s": 475, "text": "rgb_number: It sets the background color by using the RGB code. For example: “RGB(0, 153, 0)” ." }, { "code": null, "e": 589, "s": 571, "text": "Supported tags: " }, { "code": null, "e": 594, "s": 589, "text": "body" }, { "code": null, "e": 602, "s": 594, "text": "marquee" }, { "code": null, "e": 608, "s": 602, "text": "table" }, { "code": null, "e": 614, "s": 608, "text": "tBody" }, { "code": null, "e": 617, "s": 614, "text": "td" }, { "code": null, "e": 623, "s": 617, "text": "tFoot" }, { "code": null, "e": 626, "s": 623, "text": "th" }, { "code": null, "e": 632, "s": 626, "text": "tHead" }, { "code": null, "e": 635, "s": 632, "text": "tr" }, { "code": null, "e": 639, "s": 635, "text": "col" }, { "code": null, "e": 648, "s": 639, "text": "colgroup" }, { "code": null, "e": 704, "s": 648, "text": "Note: The bgcolor attribute is not supported by HTML5. " }, { "code": null, "e": 746, "s": 704, "text": "Example: HTML <table> bgcolor attribute " }, { "code": null, "e": 751, "s": 746, "text": "html" }, { "code": "<!DOCTYPE html><html> <head> <title> HTML table bgcolor Attribute </title></head> <body> <h1>GeeksforGeeks</h1> <h2>HTML table bgcolor Attribute</h2> <table border=\"1\" bgcolor=\"green\"> <caption> Author Details </caption> <tr> <th>NAME</th> <th>AGE</th> <th>BRANCH</th> </tr> <tr> <td>BITTU</td> <td>22</td> <td>CSE</td> </tr> <tr> <td>RAM</td> <td>21</td> <td>ECE</td> </tr> </table></body> </html>", "e": 1343, "s": 751, "text": null }, { "code": null, "e": 1353, "s": 1343, "text": "Output: " }, { "code": null, "e": 1391, "s": 1353, "text": "Example:HTML body Bgcolor Attribute " }, { "code": null, "e": 1396, "s": 1391, "text": "html" }, { "code": "<!DOCTYPE html><html> <head> <title> HTML body Bgcolor Attribute</title></head> <!-- body tag starts here --> <body text=\"green\" bgcolor=\"orange\"> <center> <h1>GeeksforGeeks</h1> <h2> HTML <body> bgcolor Attribute </h2> <p> It is a Computer Science portal For Geeks </p> </center></body><!-- body tag ends here --> </html>", "e": 1786, "s": 1396, "text": null }, { "code": null, "e": 1796, "s": 1786, "text": "Output: " }, { "code": null, "e": 1934, "s": 1796, "text": "Note: The bgcolor attribute is not supported in HTML5.Supported Browsers: The browsers supported by bgcolor attribute are listed below: " }, { "code": null, "e": 1948, "s": 1934, "text": "Google Chrome" }, { "code": null, "e": 1966, "s": 1948, "text": "Internet Explorer" }, { "code": null, "e": 1974, "s": 1966, "text": "Firefox" }, { "code": null, "e": 1987, "s": 1974, "text": "Apple Safari" }, { "code": null, "e": 1993, "s": 1987, "text": "Opera" }, { "code": null, "e": 2009, "s": 1995, "text": "ManasChhabra2" }, { "code": null, "e": 2023, "s": 2009, "text": "chhabradhanvi" }, { "code": null, "e": 2039, "s": 2023, "text": "HTML-Attributes" }, { "code": null, "e": 2044, "s": 2039, "text": "HTML" }, { "code": null, "e": 2061, "s": 2044, "text": "Web Technologies" }, { "code": null, "e": 2066, "s": 2061, "text": "HTML" } ]
Send unlimited Whatsapp messages using JavaScript
03 Jul, 2022 When it comes to web development, JavaScript can do wonders! Let me show you one more wonder of JavaScript.Wouldn’t it be cool if we can send infinite WhatsApp messages at just one click? be the first one to wish birthday/anniversaries/special events to our loved ones? schedule any message for any contact/group on your WhatsApp? and so much more? Well yes, we can achieve all these things with the help of JavaScript. The most interesting part is that all you need is a phone with WhatsApp, a laptop/PC and a Web-Browser(Google Chrome, Edge, Mozilla etc.) with Javascript enabled in it (which is usually enabled by default). No need of installing anything else. Let’s get started.Open WhatsApp on the phone. Click on the 3 dots in the top right corner. Click on WhatsApp Web. Follow the instructions to open WhatsApp web on your computer. Assuming that by this time you have WhatsApp Web running on your computer, check if it looks like the image below:- Now let’s bring our attention to the computer. In the browser press Ctrl, Shift and I together to open a developer’s console. Find out the “Console” tab there and click on it. Now we are almost done. Double click the code below to edit it. Find and assign values to the following variables: name, message, and counter. The code works on the principle of simulating send via reproducing send actions, it cannot search for a contact if a conversation is not initiated, as of yet. Read the comments in the code and you will know what to do <script> function simulateMouseEvents(element, eventName){ var mouseEvent = document.createEvent('MouseEvents'); mouseEvent.initEvent(eventName, true, true); element.dispatchEvent(mouseEvent);} /*Schedule your message section starts herevar now = new Date(); // Replace Hours, Mins and secs with your // desired time in 24 hour time format e.g.// var rt = new Date(now.getFullYear(), now.getMonth(), // now.getDate(), Hours, Minutes, Sec, 0) - now; // to send message at 2.30PM var rt = new Date(now.getFullYear(), now.getMonth(), now.getDate(), 14, 30, 00, 0) - now; if (rt < 0) { rt += 86400000; } setTimeout(startTimer, rt);Schedule your message section ends here*/ // Replace My Contact Name with the name // of your WhatsApp contact or group e.g. title="Peter Parker"name = "My Contact Name" simulateMouseEvents(document.querySelector('[title="' + name + '"]'), 'mousedown'); function startTimer(){ setTimeout(myFunc, 3000);} startTimer(); var eventFire = (MyElement, ElementType) => { var MyEvent = document.createEvent("MouseEvents"); MyEvent.initMouseEvent (ElementType, true, true, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null); MyElement.dispatchEvent(MyEvent);}; function myFunc(){ messageBox = document.querySelectorAll("[contenteditable='true']")[1]; message = "My Message"; // Replace My Message with your message use to add spaces to your message counter = 5; // Replace 5 with the number of times you want to send your message for (i = 0; i < counter; i++) { event = document.createEvent("UIEvents"); messageBox.innerHTML = message.replace(/ /gm, ''); // test it event.initUIEvent("input", true, true, window, 1); messageBox.dispatchEvent(event); eventFire(document.querySelector('span[data-icon="send"]'), 'click'); }} </script> Now copy the modified code and paste it in the console windows that you opened before. You are good to go now! Hit Enter and voila! Your desired numbers of messages are sent, just with a single click. Extra Fun: To schedule your message, remove the comment from “Schedule your message section” in the code and set the time as per your wish!Note:- Make sure that the contact/group you are willing to send messages are visible in the browser without the need of scrolling down. WhatsApp may block your account for excessive use of such scripts. So use at your own risk! All the information provided on this site are for educational purposes only. The site and author of the article is no way responsible for any misuse of the information. Feel free to tweak the code as per your need and have fun! Happy Coding AbhimanyuZ hardikbharunt JavaScript TechTips Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n03 Jul, 2022" }, { "code": null, "e": 403, "s": 54, "text": "When it comes to web development, JavaScript can do wonders! Let me show you one more wonder of JavaScript.Wouldn’t it be cool if we can send infinite WhatsApp messages at just one click? be the first one to wish birthday/anniversaries/special events to our loved ones? schedule any message for any contact/group on your WhatsApp? and so much more?" }, { "code": null, "e": 718, "s": 403, "text": "Well yes, we can achieve all these things with the help of JavaScript. The most interesting part is that all you need is a phone with WhatsApp, a laptop/PC and a Web-Browser(Google Chrome, Edge, Mozilla etc.) with Javascript enabled in it (which is usually enabled by default). No need of installing anything else." }, { "code": null, "e": 764, "s": 718, "text": "Let’s get started.Open WhatsApp on the phone." }, { "code": null, "e": 809, "s": 764, "text": "Click on the 3 dots in the top right corner." }, { "code": null, "e": 832, "s": 809, "text": "Click on WhatsApp Web." }, { "code": null, "e": 895, "s": 832, "text": "Follow the instructions to open WhatsApp web on your computer." }, { "code": null, "e": 1011, "s": 895, "text": "Assuming that by this time you have WhatsApp Web running on your computer, check if it looks like the image below:-" }, { "code": null, "e": 1058, "s": 1011, "text": "Now let’s bring our attention to the computer." }, { "code": null, "e": 1137, "s": 1058, "text": "In the browser press Ctrl, Shift and I together to open a developer’s console." }, { "code": null, "e": 1187, "s": 1137, "text": "Find out the “Console” tab there and click on it." }, { "code": null, "e": 1211, "s": 1187, "text": "Now we are almost done." }, { "code": null, "e": 1251, "s": 1211, "text": "Double click the code below to edit it." }, { "code": null, "e": 1330, "s": 1251, "text": "Find and assign values to the following variables: name, message, and counter." }, { "code": null, "e": 1489, "s": 1330, "text": "The code works on the principle of simulating send via reproducing send actions, it cannot search for a contact if a conversation is not initiated, as of yet." }, { "code": null, "e": 1549, "s": 1489, "text": "Read the comments in the code and you will know what to do " }, { "code": "<script> function simulateMouseEvents(element, eventName){ var mouseEvent = document.createEvent('MouseEvents'); mouseEvent.initEvent(eventName, true, true); element.dispatchEvent(mouseEvent);} /*Schedule your message section starts herevar now = new Date(); // Replace Hours, Mins and secs with your // desired time in 24 hour time format e.g.// var rt = new Date(now.getFullYear(), now.getMonth(), // now.getDate(), Hours, Minutes, Sec, 0) - now; // to send message at 2.30PM var rt = new Date(now.getFullYear(), now.getMonth(), now.getDate(), 14, 30, 00, 0) - now; if (rt < 0) { rt += 86400000; } setTimeout(startTimer, rt);Schedule your message section ends here*/ // Replace My Contact Name with the name // of your WhatsApp contact or group e.g. title=\"Peter Parker\"name = \"My Contact Name\" simulateMouseEvents(document.querySelector('[title=\"' + name + '\"]'), 'mousedown'); function startTimer(){ setTimeout(myFunc, 3000);} startTimer(); var eventFire = (MyElement, ElementType) => { var MyEvent = document.createEvent(\"MouseEvents\"); MyEvent.initMouseEvent (ElementType, true, true, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null); MyElement.dispatchEvent(MyEvent);}; function myFunc(){ messageBox = document.querySelectorAll(\"[contenteditable='true']\")[1]; message = \"My Message\"; // Replace My Message with your message use to add spaces to your message counter = 5; // Replace 5 with the number of times you want to send your message for (i = 0; i < counter; i++) { event = document.createEvent(\"UIEvents\"); messageBox.innerHTML = message.replace(/ /gm, ''); // test it event.initUIEvent(\"input\", true, true, window, 1); messageBox.dispatchEvent(event); eventFire(document.querySelector('span[data-icon=\"send\"]'), 'click'); }} </script> ", "e": 3458, "s": 1549, "text": null }, { "code": null, "e": 3569, "s": 3458, "text": "Now copy the modified code and paste it in the console windows that you opened before. You are good to go now!" }, { "code": null, "e": 3659, "s": 3569, "text": "Hit Enter and voila! Your desired numbers of messages are sent, just with a single click." }, { "code": null, "e": 3934, "s": 3659, "text": "Extra Fun: To schedule your message, remove the comment from “Schedule your message section” in the code and set the time as per your wish!Note:- Make sure that the contact/group you are willing to send messages are visible in the browser without the need of scrolling down." }, { "code": null, "e": 4026, "s": 3934, "text": "WhatsApp may block your account for excessive use of such scripts. So use at your own risk!" }, { "code": null, "e": 4195, "s": 4026, "text": "All the information provided on this site are for educational purposes only. The site and author of the article is no way responsible for any misuse of the information." }, { "code": null, "e": 4268, "s": 4195, "text": "Feel free to tweak the code as per your need and have fun! Happy Coding " }, { "code": null, "e": 4279, "s": 4268, "text": "AbhimanyuZ" }, { "code": null, "e": 4293, "s": 4279, "text": "hardikbharunt" }, { "code": null, "e": 4304, "s": 4293, "text": "JavaScript" }, { "code": null, "e": 4313, "s": 4304, "text": "TechTips" }, { "code": null, "e": 4330, "s": 4313, "text": "Web Technologies" } ]
C++ Program to remove spaces from a string?
The program takes a string and removes the spaces in it. This is useful when we want to save the space of our The following sample shows how it is done with an explanation. Input: Hello World Output: HelloWorld To remove or delete spaces from the string or sentence, you have to ask the user to enter a string. Now start checking for spaces. If space will be found, then start placing the next character from the space to the back until the last character and continue to check for the next space to remove all the spaces present in the string #include <iostream> #include<string.h> using namespace std; int { char str[80]="Hello World"; int i=0, len, j; len = strlen(str); for( i = 0; i < len; i++) { if (str[i] == ' ') { for (j = i; j < len; j++) str[j] = str[j+1]; len--; } } cout << str; return 0; }
[ { "code": null, "e": 1235, "s": 1062, "text": "The program takes a string and removes the spaces in it. This is useful when we want to save the space of our The following sample shows how it is done with an explanation." }, { "code": null, "e": 1273, "s": 1235, "text": "Input: Hello World\nOutput: HelloWorld" }, { "code": null, "e": 1606, "s": 1273, "text": "To remove or delete spaces from the string or sentence, you have to ask the user to enter a string.\nNow start checking for spaces. If space will be found, then start placing the next character from the space to the back until the last character and continue to check for the next space to remove all the spaces present in the string" }, { "code": null, "e": 1933, "s": 1606, "text": "#include <iostream>\n#include<string.h>\nusing namespace std;\nint {\n char str[80]=\"Hello World\";\n int i=0, len, j;\n len = strlen(str);\n for( i = 0; i < len; i++) {\n if (str[i] == ' ') {\n for (j = i; j < len; j++)\n str[j] = str[j+1];\n len--;\n }\n }\n cout << str;\n return 0;\n}" } ]
SAP Hybris - Quick Guide
SAP Hybris is a family of product from a German company Hybris, which sells e-Commerce, Marketing, Sales, Service and Product Content Management Software. SAP Hybris provides solutions that helps any organization to cut cost, save time, reduce complexity and require lesser focus to achieve excellent customer experience. Hybris was introduced in 1997 in Zug, Switzerland and later this company was acquired by SAP S.E on 1 August 2013. SAP has integrated its own premise backend system – SAP CRM and SAP ERP with the Hybris solution, so any company that has SAP ERP or SAP CRM implemented can easily move to the SAP Hybris solution. The SAP Hybris Commerce Accelerator is an Omni channel e-commerce solution with storefront templates and tools to provide an amazing customer engagement experience. Hybris Product focuses on the following main areas − Commerce Marketing Revenue (Billing) Sales Service Hybris as a Service (YaaS) Let us now discuss each of these in detail. This is used to provide a meaningful and consistent experience to every channel. It includes products for B2C Commerce, B2B Commerce, Product Content and Catalog Management, Omni-Channel fulfillment, and Merchandising to understand what customer wants and to turn visitors into buyers. This is to understand the customer behavior in real-time and to provide them what they want and when they want. This solution provides a company with the capability to work in complex partner ecosystems, reselling products and sharing the revenue. It includes products for Subscription Order Management, Revenue in Cloud, Responsive Quality Control, Customer Financial Management, Consolidated Billing, Invoicing and many more. SAP Hybris cloud for Sales takes customer information from the backend system provides it to the front-end Sales team and enables them to understand target customers, and how to grab each opportunity of a new sale. This provides information to the sales executive out in the field and on the mobile device in the hands of the sales executive. It includes product for Retail Execution, Sales Performance Management and Sales Force Automation. SAP Hybris for Service allows a company to provide an exceptional service experience to its customer and hence delightful customer engagement experience. Using Hybris Service, organizations can give its customer the right service on the right channel. It includes product for Omni Channel Call Center, Proactive Field Service and Comprehensive Self Service. This is one of the most advanced micro services ecosystem, which allows a company to develop custom applications with the existing platform. YaaS allows companies to reassemble and adapt the existing services to build a custom experience without the need of developing them from scratch. The URL for Hybris solution and its key features is given below. www.hybris.com/en/ You can navigate to the Products section to see what all key products are being offered by SAP Hybris. You can also scroll down to different sub-categories under each category. Following are the Industries where SAP Hybris is implemented. It is implemented in Automotive, Banking and Finance, Consumer Products, Healthcare, Insurance and Manufacturing, Retail, Public Sector and many other industries. You can navigate to the “Customers” section to see the client list for SAP Hybris. Hybris is an ecommerce product platform that is used to address a family of products involving Customer Experience and Management. Hybris is not a single product like SAP ERP or SAP BW system, rather it is a group of products to provide end to end customer engagement experience. SAP Hybris is also different from SAP Hybris Cloud for Customer, which is a cloud based CRM application that has been recently renamed by SAP as SAP Hybris C4C solution. Hybris offers product for Commerce, Billing or Revenue, Sales, Service and Marketing and SAP Hybris Marketing is completely different from the Hybris Commerce. The SAP Hybris Product family contains the following distinct products named as − Hybris Commerce Hybris Revenue or Billing Hybris Cloud for Customer for Sales Hybris Cloud for Customer for Service Hybris Marketing The Hybris product family can be integrated with other backend solutions from SAP like SAP ERP and SAP CRM to achieve end-to-end customer engagement experience. Here, we have mentioned five products. However, in reality there are only four products as product for Sales and Product for Service are a part of SAP Hybris Cloud for Customer solution. The following image shows the SAP Hybris Product Family − With SAP Hybris Commerce Cloud, companies can meet those expectations and deliver great experiences that gain their loyalty. SAP Hybris Commerce Cloud can help companies to understand their customers at every point of the commerce experience, so they can drive relevant, meaningful interactions, from content creation to merchandising to fulfillment. Hybris products for E-Commerce includes B2B and B2C commerce applications like Product Content Management (PCM), Search and Merchandising and Order Management. Hybris commerce provides all the features that an organization can expect from an E-Commerce application. The Hybris product site covers the following capabilities of SAP Hybris Product for e-Commerce − www.hybris.com/en/products/commerce B2C Commerce B2B Commerce Product Content and Catalog Management Omni-Channel Fulfillment Creating Contextual Experiences This solution provides Revenue management, highly automated billing and invoicing solution. Using SAP Hybris Revenue Cloud, you can deliver Price and Quote, Order Management and Subscription Billing experiences directly from the cloud. It provides more flexibility to work in a complex partner ecosystem. Following is the product link from the Hybris site − www.hybris.com/en/products/billing. The following capabilities are covered in SAP Hybris Cloud for Revenue − Revenue in cloud Subscription Order Management Responsive Quality Control Agile Charging Invoicing Versatile Document Management Customer Financial Management Consolidated Billing This solution is used to fetch data from the on premise backend-system and provide it to the front-end sales team. The Sales team can access data on a mobile device and this provides information they need to know, who the target customers are, any issues in sales process and how to covert each opportunity to a sale. The following capabilities are covered in the SAP C4C Sales solution − Sales Force Automation Sales Performance Management Retail Execution www.hybris.com/en/products/sales This solution helps an organization to deliver an excellence customer service experience to its customers. Following capabilities are available in SAP C4C for Service solution − Comprehensive Self-Service Omni-Channel Call Center Proactive Field Service The link to the Hybris product site is as follows − www.hybris.com/en/products/service SAP Hybris Marketing solutions help the organization to understand its customer choices in real time and help them to maintain customer profiles from the data gathered from different sources. Old time CRM Marketing was not providing data in real time, however SAP Hybris Marketing is providing the most cutting edge solutions to marketers for providing personalized marketing experience as per their changing needs. The following capabilities are available in SAP C4C Marketing solution − Dynamic Customer Profiling Segmentation and Campaign Management Commerce Marketing Loyalty Management Marketing Resource Management Marketing Analysis Marketing Lead Management Customer Attribution Architecture and Technology The Hybris product site link is as follows − www.hybris.com/en/products/marketing SAP C4C (Cloud for Customer) is a SAP Cloud based CRM based management solution and is different from the traditional SAP CRM on premise setup. SAP C4C provides the best CRM based Sales, Service and Marketing practices including options to access its mobile devices. In April 2016, SAP renamed their Cloud for Customer solution as SAP Hybris Cloud for Customer. SAP Hybris is different from SAP Hybris Cloud for Customer in sense that it offers product for Commerce, Billing or Revenue, Sales, Service and Marketing and SAP Hybris Marketing is completely different from Hybris Commerce. The SAP Hybris Product family contains the following distinct products, which are − Hybris Commerce Hybris Revenue or Billing Hybris Cloud for Customer for Sales Hybris Cloud for Customer for Service Hybris Marketing In the above family of products under the Hybris umbrella, SAP Hybris Cloud for Customer for Sales and for Services are provided using SAP Cloud for Customer product. This provides close integration with traditional backend systems like SAP CRM and SAP ERP system. SAP Hybris portfolio also includes Commerce, Billing and Marketing part apart from cloud for Sales and Service. Note − You can integrate Cloud for Customer C4C solution to Hybris commerce platform, and both offers consistent end-to-end customer experience solution. SAP has maintained Hybris Commerce platform and Cloud for Customer as two different products, built separately to serve two different audiences. When an organization buys Hybris commerce, it does not provide the license for C4C solution or buying C4C does not provide the organization with the license of Hybris commerce. License has to be purchased separately for both products from the Hybris family. SAP C4C is based on the following individual products − SAP Cloud for Sales SAP Cloud for Marketing SAP Cloud for Social Engagement Following is the HTML user interface for SAP Cloud for Customer C4C product − It is also available in Microsoft Silverlight mode as shown in following screenshot. SAP Hybris provides product for e-Commerce, Marketing, Sales and Service, Revenue and cross-functional solutions and they are designed to help organizations to create valuable interactions with their customers and support for different industry types. Hybris includes product portfolio for the following capabilities − Products for Commerce Products for Marketing Products for Sales Products for Service Products for Billing Cross-Functional Solution The link of Hybris site to view the complete product portfolio under Hybris umbrella is − https://www.hybris.com/en/products/digital-portfolio The products for commerce available under SAP Hybris Commerce are explained in the screenshot below. SAP Hybris Commerce Cloud can help a company to understand their customers at every point of the commerce experience, so they can drive relevant, meaningful interactions, from content creation to merchandising to fulfillment. SAP Hybris Marketing is providing the most innovative solutions to marketers for providing personalized marketing experience as per their changing needs. The following product portfolio is available under SAP Hybris Products for Marketing. Hybris for Sales solution provides sales team to access data on mobile device and this provides information they need to know who the target customers are, any issues in sales process and how to covert each opportunity to a sale. This solution helps an organization to deliver an excellent customer service experience to its customers. Hybris Products for Service offers a consistent experience across all channels, access complete and contextual customer information, and gain real-time insight into call center performance and field service management. Following products are available under this portfolio − Using SAP Hybris Revenue Cloud, you can deliver Price and Quote, Order Management and Subscription Billing experiences directly from the cloud. Following products are available under this category − Apart from products mentioned, SAP also provides wide range of cross-functional solutions to manage customer interactions, wide range of tools to manage incentive plans and sales commission and to securely sign and manage documents online. SAP Hybris Commerce Accelerator provides organizations with ready-to-use Omni-channel commerce solutions with storefront templates and business tools that allows organization to create an exceptional customer experience. When a new project is started, it includes everything working ready for you to rebrand and customize as needed. SAP Hybris Accelerator is designed to provide the platform and architecture of SAP Hybris Commerce that helps in reducing cost of ownership and speeds up the implementation process. The SAP Hybris Commerce Accelerator is available for B2B, B2C, Financial services and other marketing types. Whereas, the sites are available with market specific capabilities and expected features for each market type. Following are the key advantages of using a SAP Hybris Accelerator concept − By using an Accelerator, companies get an integrated, truly Omni-channel solution from the starting day of project implementation. By using an Accelerator, companies get an integrated, truly Omni-channel solution from the starting day of project implementation. By using an Accelerator, you can have a solid infrastructure to scale out the business requirement. By using an Accelerator, you can have a solid infrastructure to scale out the business requirement. It reduces the implementation cost and time by providing platform for different device types. It reduces the implementation cost and time by providing platform for different device types. Ease to use tools for building and maintaining a feature-rich shopping experience. Ease to use tools for building and maintaining a feature-rich shopping experience. The following illustration shows the layered architecture of a SAP Hybris Commerce Accelerator. The top layer includes – HMC, Web Services and Cockpits, which define objects that end user uses to interact with applications. Various user actions can be performed like adding a product to the cart, edit quantity in shopping carts and manage user profiles. The top layer includes – HMC, Web Services and Cockpits, which define objects that end user uses to interact with applications. Various user actions can be performed like adding a product to the cart, edit quantity in shopping carts and manage user profiles. Hybris Service Layer Framework is responsible to implement Java Application Programmer’s Interface for objects in the Hybris Commerce Suite. Hybris Service Layer Framework is responsible to implement Java Application Programmer’s Interface for objects in the Hybris Commerce Suite. The Type layer defines business object models, which are generated based on types. The Type layer defines business object models, which are generated based on types. The Persistence Layer is responsible for abstraction from database, caching and clustering. The Persistence Layer is responsible for abstraction from database, caching and clustering. The Database layer is used to store the data contained in a Hybris Commerce suite. The Database layer is used to store the data contained in a Hybris Commerce suite. Other important components include − This is one of the key component in the top layer in Hybris. Products are maintained in the product cockpit if there is a requirement to update the description, then it can be done using the product cockpit without making a change to the code. It also has the CMS cockpit that allows marketing content to be updated without any dependence on the IT team. HMC or Backoffice provides a single user interface to manage any kind of data. It can be used to access stores, sites, products, users, companies, and catalogs. The following screenshots displays the Hybris B2C Accelerator that contains storefront templates and business tools based on best practices, which are designed to speed up the implementation and to reduce cost and implementation time. Product Content Management in SAP Hybris Cloud is used to incorporate product images in new marketing messages. These marketing messages can be created by using Messages and Email templates app or by using the Content Studio. A Digital Asset Management system is used to store images. It allows you to perform search capabilities. You can integrate Digital Asset Management (DAM) as the communication system with SAP Hybris Product Content Management. To integrate a PCM system with the Communication system app, you have to add a new Communication System. Go to the Open Communication System app and click on “New” to create a new communication system. In the new window, enter the following details and click on the Create button. System ID − HYBRIS_COMMERCE_PCM System ID − HYBRIS_COMMERCE_PCM System Name − HYBRIS_COMMERCE_PCM System Name − HYBRIS_COMMERCE_PCM In the next window, you have to the enter Host name – SAP Hybris Commerce server name. Next is to add inbound/outbound technical User for communication. You can select a user from the existing list or you can also create a new user by using the option – Maintain Communication User. You can also create new Communication Arrangements using the Communication Arrangement app and click on the ‘New’ option to create a new Communication arrangement. Follow the steps mentioned in the wizard, click on Next and you can click on Test Connection. The following information is required to add a new Communication Arrangement − Port − In the next dialog box, you need to pass the port number setup on the server for HTTPS (SSL). Port − In the next dialog box, you need to pass the port number setup on the server for HTTPS (SSL). Path − In the Path option, you have to enter the path to the V1 REST API of the Omni Commerce Channel (OCC). Path − In the Path option, you have to enter the path to the V1 REST API of the Omni Commerce Channel (OCC). Service URL − In this field, you have to mention the service URL. Service URL − In this field, you have to mention the service URL. Click on Save. You can click on Test Connection button to check the connection setup. One of the main features in Hybris is the flexibility to add new objects to the global Hybris Commerce Data model. Hybris data modeling helps an organization in maintaining their database and help to manage database connections and queries. Hybris Type system is used to design data modeling in Hybris. A Hybris type system has the following types supported for data modeling − Items.xml − This file is used for data modeling in a Hybris Commerce data model. Items.xml − This file is used for data modeling in a Hybris Commerce data model. Item types − This is used to create tables. Item types − This is used to create tables. Relation types − This is used to create relation between tables. Relation types − This is used to create relation between tables. Atomic types − Used to create various Atomic types. Atomic types − Used to create various Atomic types. Collection types − Used to create Collections. Collection types − Used to create Collections. Map Types − To define maps. Map Types − To define maps. Enum types − To define Enums. Enum types − To define Enums. Let us now discuss all of these in detail. These are defined as basic types in Hybris, which include Java number and string objects – java.lang.integer, java.lang.boolean or java.lang.string. <atomictypes> <atomictype class = "java.lang.Object" autocreate = "true" generate = "false" /> <atomictype class = "java.lang.Boolean" extends = "java.lang.Object" autocreate = "true" generate = "false" /> <atomictype class = "java.lang.Double" extends = "java.lang.Number" autocreate = "true" generate = "false" /> <atomictype class = "java.lang.String" extends = "java.lang.Object" autocreate = "true" generate = "false" /> </atomictypes> Item types are used to create new tables or to update existing tables. This is considered as a base for a Hybris type system. All new table structures are configured over this type using different attributes as shown below − <itemtype code = "Customer" extends = "User" jaloclass = "de.hybris/platform.jalo.user.Customer" autocreate = "true" generate = "true"> <attributes> <attribute autocreate = "true" qualifier = "customerID" type = "java.lang.String"> <modifiers read = "true" write = "true" search = "true" optional = "true"/> <persistence type = "property"/> </attribute> </attributes> </itemtype> This type is used to create a link between tables. For example – You can link a country and region. <relation code = "Country2RegionRelation" generate = "true" localized = "false" autocreate = "true"> <sourceElement type = "Country" qualifier = "country" cardinality = "one"> <modifiers read = "true" write = "true" search = "true" optional = "false" unique = "true"/> </sourceElement> <targetElement type = "Region" qualifier = "regions" cardinality = "many"> <modifiers read = "true" write = "true" search = "true" partof = "true"/> </targetElement> </relation> These are used to build enumeration in Java for preparing a particular set of values. For example – Months in a year. <enumtype code = "CreditCardType" autocreate = "true" generate = "true"> <value code = "amex"/> <value code = "visa"/> <value code = "master"/> <value code = "diners"/> </enumtype> These are used to build collection/group of element types – group of products, etc. <collectiontype code = "ProductCollection" elementtype = "Product" autocreate = "true" generate = "true"/> <collectiontype code = "LanguageList" elementtype = "Langauage" autocreate = "true" generate = "true"/> <collectiontype code = "LanguageSet" elementtype = "Langauage" autocreate = "true" generate = "true"/> Map types are used to store key values pairs in Hybris data modeling. Each key represents its own code. <maptype code = "localized:java.lang.String" argumenttype = "Language" returntype = "java.lang.String" autocreate = "true" generate = "false"/> Bundling module in SAP Hybris is used to address the needs of companies that sells service bundles and digital products. SAP Hybris provides a tool for configuring, to manage and sell bundled offerings. Bundling module provides various benefits in the e-commerce model. Some of these benefits are given below − Using bundling service, organizations can increase average order value and margin by bundling content and products. Using bundling service, organizations can increase average order value and margin by bundling content and products. Bundling module improves conversion rates with personalized and content-rich shopping experience to customers. Bundling module improves conversion rates with personalized and content-rich shopping experience to customers. It helps e-commerce organizations to cross-sell physical and digital goods on one commerce platform. It helps e-commerce organizations to cross-sell physical and digital goods on one commerce platform. Bundling helps an organization in managing and expanding product offerings by transforming complex products into simple, compelling selections for customers. Bundling helps an organization in managing and expanding product offerings by transforming complex products into simple, compelling selections for customers. Easy to use, flexible business tool to manage complex product offerings and bundling service. Easy to use, flexible business tool to manage complex product offerings and bundling service. Using SAP Hybris Bundling Module, organizations can easily set up a Product Cockpit by adding physical products like gaming bundles, media packages, etc., to specific bundle categories. Companies can also apply different pricing rules on bundle categories with setting up different merchandising. You can achieve the following key features using a SAP Hybris Bundling concept − Hybris Bundling module provides organization with bundle templates to guide selling of products using the product cockpit. Hybris Bundling module provides organization with bundle templates to guide selling of products using the product cockpit. Bundling provides optimized shopping carts for customers in an e-commerce model. Bundling provides optimized shopping carts for customers in an e-commerce model. Bundling service in Hybris helps in managing advanced bundle merchandising and personalization of merchandise behavior. Bundling service in Hybris helps in managing advanced bundle merchandising and personalization of merchandise behavior. Easy management of B2C and B2B channel using flexible Bundling service. Easy management of B2C and B2B channel using flexible Bundling service. Bundling service provides product merchandisers with ability to create bundles dynamically of physical and/or digital products based on predefined bundling templates and these can be available to customer suing easy to use Product cockpit. Bundling service provides product merchandisers with ability to create bundles dynamically of physical and/or digital products based on predefined bundling templates and these can be available to customer suing easy to use Product cockpit. In the next chapter, we will discuss regarding the workflow and business process engine of SAP Hybris. With the use of SAP Hybris Workflow, companies can define standardized processes, which run automatically, when required. The Workflow Module can be easily integrated with the Hybris platform. It ensures efficient management of standardized processes in the backend and hence efficient teamwork along with clear task assignment. Users can easily define standardized process and use of commented feature makes teamwork more efficient. Workflow allows user to trigger predefined workflows for complex processes or adhoc workflows for one single task. Following are the benefits that can be achieved using a Workflow − By using workflow integrated with other Hybris tools, you can handle processes more efficiently with a standardized method. By using workflow integrated with other Hybris tools, you can handle processes more efficiently with a standardized method. With the use of workflow, complex processes can be easily managed by defining tasks and corresponding actions. With the use of workflow, complex processes can be easily managed by defining tasks and corresponding actions. Workflow allows you to create templates as per the requirement. Workflow allows you to create templates as per the requirement. Comment functionality provides efficient teamwork. Comment functionality provides efficient teamwork. Workflow supports real time notifications to the user’s inbox. Workflow supports real time notifications to the user’s inbox. By using Hybris Workflow & Collaboration Module, it is easy for users to easily define workflows and view the workflow status. Workflow module can be easily implemented on the Hybris platform and you can integrate it with the Hybris product cockpit. Workflow module can be easily implemented on the Hybris platform and you can integrate it with the Hybris product cockpit. With the use of a Hybris Product Cockpit, users can easily access all workflow entries. With the use of a Hybris Product Cockpit, users can easily access all workflow entries. SAP Hybris provides predefined and adhoc workflows. SAP Hybris provides predefined and adhoc workflows. It is also possible to trigger the workflow using cron-jobs in the Hybris platform. It is also possible to trigger the workflow using cron-jobs in the Hybris platform. Hybris platform provides flexibility to create workflow templates. Hybris platform provides flexibility to create workflow templates. Users can design human and system based workflows Sequential, Parallel or Task-Dependent Workflow Execution. Users can design human and system based workflows Sequential, Parallel or Task-Dependent Workflow Execution. Workflow provides real-time notification via e-Mail to users. Workflow provides real-time notification via e-Mail to users. It is also possible to provide user access only relevant to-do’s in the workflow list. It is also possible to provide user access only relevant to-do’s in the workflow list. The following illustration shows commenting facility in Workflow on Hybris platform − To create a new workflow rule, we should follow the subsequent steps. Navigate to the Worklist and click on the ‘New’ button from the workflow rules worklist. You have to enter the general information − Mention the Description to identify the rule in the worklist. Mention the Description to identify the rule in the worklist. Next is to select the Business Object – such as opportunity or ticket, to which the rule is to be applied. Next is to select the Business Object – such as opportunity or ticket, to which the rule is to be applied. The next step is to select the Timing for applying the rule – you can select from the three following timing types to apply to your rule. On Create Only On Every Save Scheduled The next step is to select the Timing for applying the rule – you can select from the three following timing types to apply to your rule. On Create Only On Create Only On Every Save On Every Save Scheduled Scheduled When timing is left blank, the default On Every Save will be automatically applied. Using Catalog management, organizations can distribute product content in specific catalogs to target specific audience. Catalog defines a way to segment stored products for efficient and effective management and to target specific audiences. A Product Catalog is defined as part of content segment to provide the details of product categories and product information in the store. SAP Hybris Platform includes two types of catalogs: Product and Content. A content catalog refers to pages of website where the distribution of product is done. In simple terms, a catalog is defined as the container of products. Following are the key advantages that can be achieved using the Catalog and the Content Management feature of Hybris − With the use of Catalog management, companies can achieve improved marketing effectiveness by managing, structuring, and displaying product content. With the use of Catalog management, companies can achieve improved marketing effectiveness by managing, structuring, and displaying product content. With the use of catalog, an organization can import product content from different sources, organizing it hierarchically and assigning attributes. With the use of catalog, an organization can import product content from different sources, organizing it hierarchically and assigning attributes. With the use of Catalog management, companies can drive sales by distributing product content to specific audiences. With the use of Catalog management, companies can drive sales by distributing product content to specific audiences. In the following image, you can see Catalog management where products are divided into specific categories. With the use of the Catalog Module, companies can manage structuring of products and product information. On the right hand side, you can see the Product attributes that specify properties of products in the Product Catalog. All the products available in the commerce site has images and these are called media. To add any product to a commerce site, we have to create media with that image. Media can be created using different tools like HMC or via Impex. To create media in the Hybris system, you can login to the Hybris Management Console (HMC) Login to the Hybris Management Console – enter username and password. Navigate to the Multimedia tab on the right hand side → Create → Media. This will open a new window and you have to provide the following details − Unique Identifier − In this field, you have to enter the unique identifier for your media. Catalog Versions − In this field, you have to enter the catalog version, which means if you use this media for a product, enter the catalog version of the product as the media catalog version. Note that if you do not mention the catalog version of media same as the catalog version of product, media is not linked to the product. Media format − This is an identifier for a media dimension. You can see the existing standard formats in the drop down or you can also create your own format. If you upload an image of 40*40, but use the higher media format, it still accepts. The following media formats are available − To upload an image for media, navigate to the Upload button and provide the path of the product image file by clicking on the Choose File option. Click on the Upload button to load the image. Once the image is uploaded, few of the properties like URL, real file name, etc., would come automatically. To save new media, you can click on save item button at the top as shown in the following screenshot. Now, if you want to search for media that you have just created, you can use different filter options under Search. You can also select checkbox for Subtypes in the Search option. The following Search Criteria are shown in the following image − Identifier Mime Type Folder Catalog Version Once you click on the Search button, all items matching the search criteria are shown under the Results tab. All the information that you have entered for the media is shown along with the media image. SAP Hybris Web content management module is used for the management of content across multiple channels like Online, Mobile and other user interfaces. Companies require good presentation of their products across all channels by using an integrated content management solution provided by SAP Hybris WCMS (Web Content Management System). The following benefits can be achieved by using the SAP Hybris WCMS − Less integration cost by using single solution for Sales, PCM, etc. Less integration cost by using single solution for Sales, PCM, etc. Using WCMS, it supports easy creation of high quality product websites. Using WCMS, it supports easy creation of high quality product websites. Integrating and managing user generated content with ease. Integrating and managing user generated content with ease. Web Content Management System provides an easy to use and consistent management of desktop and mobile websites by providing entire content from a single multimedia source. Web Content Management System provides an easy to use and consistent management of desktop and mobile websites by providing entire content from a single multimedia source. Less time for implementation using WCMS as only the page is required to develop and maintain for all device types. Less time for implementation using WCMS as only the page is required to develop and maintain for all device types. With use of WCMS system, you can make the content available across all the channels. With use of WCMS system, you can make the content available across all the channels. Managing complex formats such as Images, Texts, HTML, Videos, etc. Managing complex formats such as Images, Texts, HTML, Videos, etc. Dynamic user restriction based on the user groups. Dynamic user restriction based on the user groups. WCMS provides ready to use components built on JQuery, Bootstrap and OWL. WCMS provides ready to use components built on JQuery, Bootstrap and OWL. WCMS provides an easy to use Web Content Management System Cockpit. By using this WCMS Cockpit, users can easily manage their website pages. It provides an Interactive Graphical User Interface based interface for data management for all the channels. You have to enter the URL and it is normally in the following format − http://servername:9001/cmscockpit/login.zul The WCMS Cockpit also provides support for workflow and synchronization tasks. The following screenshot shows the WCMS Cockpit − The WCMS Cockpit contains the following areas − Navigation Area Browser Area Cockpit Area Let us now discuss each of these in detail. On the left hand side, you have the navigation pane, where you can navigate to Shortcuts, Queries, Websites and the History tab. In the center, you have the Browser area, which is used to manage web content for all the channels. You can add Top Header, Bottom Header and Footer. On the right hand side, you have the Cockpit area. The following options are available under the Cockpit area in the Basic Category − Name Page title Page Template Catalog Version Label Homepage, etc Similarly, you have Context viability, Navigation, URL and Administrator tab in the cockpit area, which can be used to manage the web content. Using SAP Hybris, companies can provide an exceptional experience to customers when they buy from them. With SAP Hybris Commerce Cloud, organizations can meet the expectations and deliver great experiences that wins customer loyalty. SAP Hybris Commerce Management Module contains built-in-Omni-channel versatility and Hybris cloud platform engage that can transact with the customers any time using any device. SAP Hybris Commerce Cloud can help companies to understand its customer throughout the e-Commerce process and helps them to drive meaningful interactions with customers. SAP Hybris Commerce management approach cuts down on complexity and allowing companies to spend less time on managing systems and focus on responding to rapidly changing the market conditions. The following capabilities are provided as a part of SAP Hybris Commerce Management module. Let us discuss these capabilities in detail. Strengthen customer loyalty and increase sales with consistent, personal experiences for your customers. SAP Hybris Commerce Cloud for B2C gives your customers what they want, when they want it, every time they interact with your business – online or in the real world. With every interaction, you can gain further customer insights, so when they come back you are ready to deliver another great experience. Create an Omni-channel B2B experience to rival the best consumer sites. The flexibility and functionality of SAP Hybris Commerce Cloud for B2B can give your customers the freedom to save repeat purchases; buy in bulk, while providing self-service, and account management for buyers. Consolidate product content and control information about your products with a built-in, easy-to-use system that works across all channels. Wherever they are in their journey, give your customers rich, engaging content including video, images and editorial content that really show off your products – including those syndicated from multiple suppliers. One system takes care of your customers’ orders across all channels. They get a fast, secure experience that allows them to choose between collection and delivery, and benefit from fuss-free returns. You get to see all the order information in one place and have precise visibility of your stock. Get customers engaged with your products by creating a one-to-one experience that is relevant every time. With SAP Hybris Customer Experience, you can manage site layout and content across all channels and create highly personalized experiences for your customers. Use our modern merchandising tool as well as historical data and current behaviors to deliver the personal storefront that drives engagement and transactions. SAP Hybris Commerce Search is a powerful option in Hybris cloud to increase sales and profile for companies. If a company provides poorly organized search results, usability problems and results in loss of sales. Using Commerce search, companies can easily promote their products and product categories by driving from the Commerce Search Results. This in turn improves the customer’s shopping experience and hence improves the margin and sales for companies. SAP Hybris also provides keyword suggestion options to help users to easily search and spell their products. If a user wrongly spells a product, it also provides spell check to enter the right word in the search option. SAP Hybris Search capability provides a free-text search option to locate a specific product and showing relevant results. SAP Hybris Search capability provides a free-text search option to locate a specific product and showing relevant results. SAP Hybris also provides a feature in the Search Capability like – Synonyms and Stop Words to improve the search results. SAP Hybris also provides a feature in the Search Capability like – Synonyms and Stop Words to improve the search results. SAP Hybris Commerce feature provides a parametric search that displays the closest match, if there is no exact match found for customer inputs. SAP Hybris Commerce feature provides a parametric search that displays the closest match, if there is no exact match found for customer inputs. SAP Hybris supports advanced search features like Collapsing, Geospatial Search, etc. . SAP Hybris supports advanced search features like Collapsing, Geospatial Search, etc. . SAP Hybris also supports update of search results with automatic updates through real-time synchronization. SAP Hybris also supports update of search results with automatic updates through real-time synchronization. In the following screenshot, you can see how SAP Hybris helps the customer with amazing search capabilities and helps the customer to explore content of a website with fewer mouse clicks. With the use of advanced personalization module of SAP Hybris, companies can offer the right product to the right customers at the right time. This helps companies to raise their conversion rate. According to a survey, more than 50% of customers receive wrong products when they do shopping online. With the use of Hybris Advance Personalization module, companies can collect customer information from different sources and provide customers with an amazing customized/personalized shopping experience, which results in increased sales and profit. The SAP Hybris Advance Personalization is a part of the WCMS (Web Content Management System). Advanced Personalization is achieved using the BTG rules. Following are the four types of BTG rules − Order Rules Cart Rules Customer Rules Website Rules The following personalization experience can be considered using SAP Hybris Advance Personalization − Example 1 − Let us assume that a consumer browses a product on a multi-channel ecommerce website and adds products worth $2000 to the Cart. Now, consider a personalization scenario, where the customer gets a message, if the shopping cart value is greater than 1800$, then he can spend additional 300$ with no cost. This is one of the example of advance personalization in E-Commerce. Exampl 2 − Another Personalization scenario is, when a customer selected a product on an e-commerce website and a pop-up message appears showing product accessories that can be added to the shopping cart along with the selected product. Exampl 3 − Personalization example is where a customer logged into his account and a particular product line has been displayed to him on the arrival page. Exampl 4 − Another Personalization example is where a customer has browsed a site from his/her laptop and E-Commerce site identifies customer IP address and displays a particular site page to the customer. The following illustration shows a good example of SAP Hybris Personalization Module. It shows the buying history of the customer and the Top Recommendations with that particular product. The following image shows how Targeting rules are created and how information is captured from different sources. Targeting the rules in an Advance Personalization scenario can include the following rule types − You can use different types of rules as per the different scenarios based on the order details, card type and other personalized data, which is available for the customers. You can use different types of rules as per the different scenarios based on the order details, card type and other personalized data, which is available for the customers. Advanced Personalization provides flexible individual rules to meet different scenarios. Advanced Personalization provides flexible individual rules to meet different scenarios. Hybris Advance Personalization module provides an easy way to integrate custom rule types with Hybris e-Commerce platform. Hybris Advance Personalization module provides an easy way to integrate custom rule types with Hybris e-Commerce platform. In today’s market, it is required that companies provide the customers with an easy to pay options, when their order is ready. If the payment method is complex in nature, the customers will not come back and companies can lose their potential buyers. The SAP Hybris Payment Module provides an easy to use and integrated payment method of their choice to the customers. Following are the key features of the Hybris Payment Module − Remove payment complexity and allow the customers to connect to multiple PSP’s. Remove payment complexity and allow the customers to connect to multiple PSP’s. It provides the customers with multiple payment options and easy integration into the Hybris system. It provides the customers with multiple payment options and easy integration into the Hybris system. Provides a secure payment gateway between e-Commerce site, customer and payment processing channel. Provides a secure payment gateway between e-Commerce site, customer and payment processing channel. Centralized processing of all the payment channels. Centralized processing of all the payment channels. Using the SAP Hybris Payment Module, you can create PSP adapters to integrate external Payment systems into the Hybris E-Commerce platform. The Hybris Payment Module allows the customer to connect to any payment method and to use its features and capabilities. Using the Payment Module, customers can use any secure payment transfers to place orders on e-commerce websites like Credit Cards – Visa and Master cards and other card types as well. By using a Payment Service Provider that is an embedded feature provided by the Hybris System, users can make payment without redirecting to external payment gateways. Following are the key benefits that can be achieved by using the SAP Hybris Payment Module − Hybris PSP’s allows customers to make payments easily, hence making the payment process much simpler and reducing the cost by allowing connection to commonly used Payment Service Providers. Hybris PSP’s allows customers to make payments easily, hence making the payment process much simpler and reducing the cost by allowing connection to commonly used Payment Service Providers. By using flexible payment options, the payment process is simplified and the customer can select from the payment method that best suits their requirement. By using flexible payment options, the payment process is simplified and the customer can select from the payment method that best suits their requirement. Using the Hybris Payment Module, customers can immediately authenticate payments using the payment validation method on the website. Payments are more secure and it does not involve any redirection to external PSP’s. Using the Hybris Payment Module, customers can immediately authenticate payments using the payment validation method on the website. Payments are more secure and it does not involve any redirection to external PSP’s. Hybris Payment Module provides a centralized mechanism for the payment processing for multiple channels. Hybris Payment Module provides a centralized mechanism for the payment processing for multiple channels. By using the centralized single payment system, e-commerce websites can increase their sales and hence their net profit is higher. By using the centralized single payment system, e-commerce websites can increase their sales and hence their net profit is higher. In the following screenshot, you can see an example of an integrated Hybris Payment Module, where the payment is made using a Payment Service Provider (PSP). The SAP Hybris Promotion Module is used to increase sales and to integrate with online stores to win new customers. By using this module, business users can create new flexible, dynamic promotions without needing any expertise. This promotion module provides various predefined promotion templates and promotion rule builders to define a set of conditions. Following are the key components of the SAP Hybris Promotion Module − Promotion Templates Promotion Rule Builder Priority Order Promotion Contextual Messages Coupon codes generation and management Let us discuss each of these in detail. The Hybris Promotion Module provides inbuilt different promotion templates that can be used by an organization to boost their sale. Promotion modules comes with customizable sample promotions, which cover the most common promotion requirements that are suitable for B2C and B2B e-commerce businesses. Using the Promotion Rule Builder, business users can apply a different set of conditions and actions. This can be used to create different complex promotions as per different scenarios. In the above image, you can see a graphical user interface of the Promotion Rule Builder. In the central pane, business users can drag different conditions and define actions for each condition. On the right hand side, you can see the available conditions to be added to the Promotion rules. This option can be used to define order of execution for different promotion rules. When multiple promotions are applied on the same set of product, business users can use priority builder to define order in which promotions will be executed. The SAP Hybris Promotion Module provides contextual messages to customers that can be configured to display messages to the customer – like products qualified as per the promotion rules and corresponding actions for those promotions. With the use of SAP Hybris Promotion Module, business users can generate auto-generated or manual coupon. By using the Promotion Builder, these coupons can be distributed to customers for redemption in different promotions. SAP Hybris Subscription module is developed to integrate with subscription billing system and hence provides improved customer acquisition rate and less operational overhead. The SAP Hybris Subscription module was built to provide subscription based support for different pricing and product related promotions. By using the SAP Hybris Subscription module for e-commerce, business users can setup and manage subscription terms and conditions in the backend UI. While creating a subscription plan, users can opt from the following fields − Subscription Terms and Conditions Subscription Price Plans Included Entitlements The subscription terms and conditions allows the customers to select from different terms that are available for the customer. Customers can select subscription terms like – 12 months contract monthly billing, 24 months contract yearly billing, lifetime subscription plan, etc. Subscription Price plans provide customers with options to select from different plan types – Premium, Platinum, Gold, etc. Included Entitlement option is used to mention all the services that the customer will avail as a part of the selected price plan. It includes services like – Access to Print Edition, Weekly Blogs, Monthly Newsletters, etc. Business users can also check Subscription plan details by going to the Edit Subscription Price Plan option. It tells about the following features − Price Plan Status Basic Charges-Recurring/One time/Usage based Subscription Type, etc In the following illustration, you can see the above options that are available under the Edit Subscription Price Plan option. Following are the key advantages of the SAP Hybris Subscription plan − Customers are provided with personalized pricing based on their profile with e-commerce companies. Customers are provided with personalized pricing based on their profile with e-commerce companies. Customers can opt for a combination of different subscription plans – one time or recurring or usage based as per their requirement Customers can opt for a combination of different subscription plans – one time or recurring or usage based as per their requirement Different Price Plans are supported based on customer requirements – Premium, Platinum, Gold Package, etc. Different Price Plans are supported based on customer requirements – Premium, Platinum, Gold Package, etc. Using the Subscription Billing Gateway, complex bundle of subscription charges can be processed for enrolled customers easily, by the use of secure payment methods. Using the Subscription Billing Gateway, complex bundle of subscription charges can be processed for enrolled customers easily, by the use of secure payment methods. Support integration with third party billing systems using subscription based billing. Support integration with third party billing systems using subscription based billing. In the next chapter, we will discuss regarding the order management overview in SAP Hybris. When customers log into an e-commerce site, it is expected to provide quick delivery, easy returns and other flexible options, while placing an order. The SAP Hybris Order Management module provides an easy way to e-commerce companies that allow customers to build, view and return orders using a centralized system with complete flexibility. With SAP Hybris Order Management module, customers experience an exceptional ordering experience, flexible pickup and order fulfillment options for all the channels. https://www.hybris.com/en/products/commerce/order-management The SAP Hybris product site covers the following features under the Order Management Module − Customers can choose to collect their purchases in store or have them delivered, with the same flexibility for returns. Customers can choose to collect their purchases in store or have them delivered, with the same flexibility for returns. Shows stock availability across all channels in real time, so the customers will not be disappointed. Shows stock availability across all channels in real time, so the customers will not be disappointed. An intuitive user interface makes it easy for business users to manage the fulfillment process. An intuitive user interface makes it easy for business users to manage the fulfillment process. Gain a single view of inventory across your entire organization and optimize stock, sourcing and allocation rules. Gain a single view of inventory across your entire organization and optimize stock, sourcing and allocation rules. SAP Hybris Order Management module helps an organization to streamline your order processes across all the channels. E-commerce companies can fetch all the details related to demand, inventory and order supply using a single interface. Hybris Order Management cockpit is one of the key features under the Hybris Order Management module that helps organizations to manage stocks easily using one interface each of inventory and supply management. The following screenshot describes the Order Management cockpit that provides all the details related to Orders, Inventory, Supply and Imports. Different search options are available under each category, where users can search for all the orders – for Delivery, pickup or list of all orders available in the Order Management System. Business users can select any of the order in the search list and check further details in Order Management cockpit. SAP Hybris Commerce Order Management service solution allows a company to streamline their order process across all channels. We have already covered all the key points related to Hybris Order Management service in the previous chapter. Using Hybris Order Management Service solution, companies can view demand, inventory and supply globally using the Order Management cockpit. The SAP Hybris Customer Service module provides an easy way to resolve customer problems quickly and deliver highly personalized customer service with improved customer satisfaction and increased revenue. When a customer logs to an e-commerce website and gets a weak customer service, it can result customers moving to other websites without completing the order. To the retail customers, the company should provide an efficient service including call centers, chat, email and even web-enabled customer self-service. These customer service points should share correct information quickly and resolve customer queries on priority. SAP Hybris Customer Service module provides Customer Service Agents with an easier and quicker access to information that they can use to resolve customer queries. A CSA module can also be used by agents to place a new order, modify previously placed orders, placing partial orders, make payment, cancel payment, raise return requests and even to process order refunds for customers. The CSA (customer service associate) module also assists the customers by providing an option to the CSA to manage customer profiles and their personal information in their account for e-commerce shopping. The Customer Service module provides the following information to the customers − Personal Details Customer Orders Customer Addresses It is also possible to customize the Hybris Customer Service Module as per the business requirements and hence can change the Customer Service Experience to successful Sales platform, which results in increased revenue for the e-commerce companies. The following screenshot describes the cart management that a CSA can provide to the customers as a part of the Customer Service module. They can perform search as per the customer requirements, add products to the shopping cart and see all the promotions and the offers that a customer can see in their account. Following are the key features covered using SAP Hybris Customer Service Module (CSM) − Using SAP Hybris module, CSA’s can perform search for customers, can edit customer profiles and their personal information like DOB, Age, Current Address, etc. A CSA module provides simple UI based application to create payment for customer and manage other details related to the customer orders. The system identifies the customer’s phone number and directs the CSA to the Customer Detail page. By using the SAP Hybris Customer Service Module, it is also possible to integrate chat service with the e-commerce website for better customer management. Self-service has the following features − The SAP Hybris CSA module allows customers to check their order status. The SAP Hybris CSA module allows customers to check their order status. Customers can raise queries with CSA’s and manage their queries as well. Customers can raise queries with CSA’s and manage their queries as well. Better customer experience by providing features like payment refund, edit or cancel orders. Better customer experience by providing features like payment refund, edit or cancel orders. Let us understand the assisted services module of SAP Hybris in the next chapter. SAP Hybris Assisted Services Module (ASM) assists the customer during the buying process using the same storefront across the Omni-channel. The Hybris ASM module connects the customer with customer support and assists them in completing their order. The ASM acts as an interface between SAP Hybris Commerce, SAP CRM and SAP Hybris C4C Solution and hence allowing Customer Support Agents to pick customer’s online storefronts from CRM or C4C solution. Using the ASM module, tickets are synchronized between SAP Hybris Commerce and SAP Cloud for Customer solution. Hence, it provides an easy resolution of all the tickets. The SAP ASM also provides Customer Support Agents to take over the session from the customers to provide real time assistance and support. The following benefits can be achieved using the SAP Assisted Service module − The CSA agents can easily search for a customer’s account and session to support. The CSA agents can easily search for a customer’s account and session to support. The support agents can assign any cart to any of the customer. The support agents can assign any cart to any of the customer. Support agents can also create a new customer account for any customer on his/her request. Support agents can also create a new customer account for any customer on his/her request. Extended sale support for customers by providing assistance to add products to customer shopping carts, completing orders, etc. Extended sale support for customers by providing assistance to add products to customer shopping carts, completing orders, etc. In the next chapter, we will discuss the role of marketing in SAP Hybris. SAP Hybris Marketing is one of the key modules of Hybris product suite, which targets enrolling customers on e-commerce websites by creating dynamic profiles and by providing real time exceptional shopping experience. This results in an increase in the conversion rate and gains the customer’s loyalty. Hybris Marketing provides an individualized, contextual marketing experience to the customers. Contextual Marketing is a personalized marketing scenario, which involves the following three types of customer information − Past Interactions and Historical Transactions Predictive Analytics In-moment context The SAP Hybris Marketing Cloud brings together tools that allow you to understand and engage with your customers in real time and on all channels like never before. Hybris Marketing contains following nine products − Hybris Marketing Segmentation Hybris Marketing Data Management Hybris Marketing Recommendation Hybris Marketing Convert Hybris Marketing Acquisition Hybris Marketing Loyalty Hybris Marketing Planning Hybris Marketing Orchestration Hybris Marketing Insights As per a recent report by Gartner (www.gartner.com) – SAP Hybris has been positioned as a leader in the 2017 Gartner for Multichannel Campaign Management Magic Quadrant Report. SAP Hybris Marketing Cloud suite focuses on customer journey management and execution across marketing and advertising channels. Following is the product link on the Hybris site: https://www.hybris.com/en/products/marketing. This page also provides a 30-day free trial for SAP Hybris Marketing Cloud. To enroll for the trial version, click on the “Sign up now” option. Once you click on the Sign up now option, you will be landing onto the following page. It gives you a brief introduction about SAP Hybris Marketing Cloud. To get started with the FREE TRIAL, click on the yellow "GET IT" button and then sign up immediately. When you click on the GET IT button, it will open the following login page of SAP Cloud Appliance Library CAL. We can now further proceed by using the SAP Partner Id and password and it will open the SAP Hybris Marketing Cloud trial. If you want to learn more about SAP Hybris Cloud, you can navigate to the Trial Center option. Once you click on the Trial Center, the following page will open. To access the SAP Marketing Cloud open courses or to access Startup guides on Marketing, we need to navigate to the SAP Learning Corner. SAP Hybris Billing provides flexible different options to the customer for automating the invoice process. SAP Hybris Billing provides an automated way of managing billing and ordering processes from the cloud. Following are the key features covered under the SAP Hybris Billing/Revenue capability − Order and Contract Lifecycle Management Quote to cash capabilities Managing Revenue/Billing for subscription Easy integration of Revenue with Sales, service and Marketing solution Order Orchestration SAP Hybris Leading Edge public cloud platform Following is the link to the SAP Hybris Revenue product site − https://www.hybris.com/en/products/billing/revenue-cloud Following are the key features of SAP Hybris Billing module − SAP Hybris Billing provides a combination of multiple billing streams and allows to bill to a single invoice. SAP Hybris Billing provides a combination of multiple billing streams and allows to bill to a single invoice. SAP Hybris Billing allows revenue sharing agreements for different channels. SAP Hybris Billing allows revenue sharing agreements for different channels. SAP Hybris Billing provides subscription billing for different charge types like one time or recurring. SAP Hybris Billing provides subscription billing for different charge types like one time or recurring. SAP Hybris Billing includes support for complex discounting including invoice level discount and customer level discounts. SAP Hybris Billing includes support for complex discounting including invoice level discount and customer level discounts. Hybris Billing supports full revenue management practices. Hybris Billing supports full revenue management practices. In the following screenshot, you can see the subscription based billing for SAP Hybris Billing module and payment type is recurring. SAP Cloud for customer (C4C) is a cloud solution to manage Customer Sales, Customer Service and Marketing Activities efficiently and is one of the key SAP Solution to Manage Customer Relationship. SAP C4C is based on the following individual products − SAP Cloud for Sales SAP Cloud for Marketing SAP Cloud for Social Engagement SAP Cloud for Service Following are the key objectives of SAP Cloud for Customer − Relationships Collaboration Insight Business Processes Following are some interesting facts about SAP C4C − SAP Cloud for Customer solution is available from June 20, 2011. SAP Cloud for Customer solution is available from June 20, 2011. SAP C4C is available in 19 languages as on May 2015. SAP C4C is available in 19 languages as on May 2015. You can easily integrate C4C solution to SAP ECC, CRM and Outlook using SAP NW Process Integration or SAP HANA Cloud Integration HCI for standard scenarios. You can easily integrate C4C solution to SAP ECC, CRM and Outlook using SAP NW Process Integration or SAP HANA Cloud Integration HCI for standard scenarios. SAP C4C is a new product of SAP based on SaaS (software as a service), PaaS (Platform as a service) and IaaS (Infrastructure as a service). SAP C4C is a new product of SAP based on SaaS (software as a service), PaaS (Platform as a service) and IaaS (Infrastructure as a service). SAP C4C connecters are available for popular middleware like Dell Boomi for Cloud Integration, Informatica, MuleSoft for Application Integration, etc. SAP C4C connecters are available for popular middleware like Dell Boomi for Cloud Integration, Informatica, MuleSoft for Application Integration, etc. The following illustration describes the key differences between Cloud for Customer and on premise solution − In SAP Hybris C4C, a sales cycle consists of all key activities under the Sales process such as − Sales Order Sales Quotes Sales Lead Let us first understand how to create Sales Quotes. Sales quotes are used to offer products to the customers as per specific terms and fixed conditions. A sales quote bounds the seller to sell products for a specific period of time and price. Sales agents are responsible for the creation of a sales quote in a company. We should follow the steps given below to create a sales quote. Step 1 − Navigate to the Sales work center → Sales Quotes. Step 2 − Click New to enter account/customer data for creating sales quotes. Once you enter all the details, click on Save. Step 3 − In the next window, under the Products tab, click Add. You can add the product that you are selling to the customer in this tab. Step 4 − Go to the Involved Parties tab, you can add all the parties involved to execute the transactions such as – bill to party, ship to party, sold to party, etc. Step 5 − Go to the Sales Document. You can get the details of all the sales documents (sales quotes, sales order, etc.) that are related to this sales quote. If your sales quote is created with a reference to some other sales document, you can see the details in this tab. Step 6 − Go to the Attachment tab, you can attach any other external documents. Go to the Approval tab, you can see the approval processes like – approval required from senior to process this sales quote, etc. You can also see the status here, which can be – pending, approved, rejected, etc. Step 7 − Navigate to the Activities tab. Create activities related to the sales representative like create an appointment through phone calls, e-mails, etc. Step 8 − Under the Changes tab, click on Go. You can see all the changes made in this sales quote by all the users at different times on these sales quotes. You can get to know what all changes have been made to this sales quote. In SAP Hybris Cloud for Customer, service level defines the time when a ticket for a customer must be responded and completed. Service levels help the organizations define objectives for handling customer messages. Using these, you can measure the performance and the quality of your customer service. Service levels also help to define new rules as per the ticket category and description whenever a new customer message comes in the C4C system. Using service levels, a system can determine the service level based on those rules and then based on that service level, the initial response and completion due time points are calculated. To create a service level, let us follow the steps given below. Step 1 − To define Service Levels, go to Administrator → Service and Social. Step 2 − Click on Service Level in the next window that opens. Step 3 − Click New and select the Service Level. Step 4 − Click the General tab. Enter the Service level Name, Service Level ID and Description. To create a new service level, you must provide a Service Level Name, and a Service Level ID. You can also provide an optional service level Description. Step 5 − Navigate to the next tab Reaction Times. In this section, you define the time when the service agent responds to the ticket. This time depends on the SLAs (Service Level Agreement) signed with the customer and with the ticket priority and type of customer. Example − High priority ticket will have low response time or high-end customers have low response time. It means, the ticket related to these customers will respond faster when compared to other tickets. To create a milestone, click Add Row and choose the type of milestone. Select Alert When Overdue, if you want the system to send an automatic alert to the responsible person, when the target milestone-time point is exceeded. Click on Add Row. Select the milestone as per the business requirement and then click on Alert When Overdue. When you select this option, the system will send an alert to the service agent. Select the required milestones. To enter the reaction time for all the milestones, go to Details for milestone → Add Row. Repeat this process for all the above milestones. Select the milestones one by one and then enter the reaction time for these milestones. To assign a service to the selected milestone (in the Milestones table) click on Add Row. Choose the Type of Service, the Priority and enter the timer (Net Labor Time) duration. Add a row for all the available priorities for each type of service selected. Step 6 − Navigate to Operating Hours tab. Operating hour is the working hour of the service agent, i.e., from what time to what time an agent is available. Select the working day calendar. Enter the days of the week of working of a service agent. Click Add Row and then select the checkboxes for the required days of the week. Enter the time ranges. Click on Add Row and enter the start time and the end time of the working hours of the service agent. Step 7 − Navigate to the Changes tab. You can see all the changes that you made in the SLA over the time. Select different available criteria and click on the Go button. To display or refresh the change history, specify the required filter criteria and click on the ‘Go’ button. Many companies has an On-premise solution that contains master data, customer and product information as well as the pricing data. Details from the SAP ECC system is required when opportunities are won and a sales order is generated. Following are the key reasons why an integration is required with SAP ERP and CRM system − To provide an organization level solution for all sales, marketing and service activities including all subsidiaries, sales offices. To provide an organization level solution for all sales, marketing and service activities including all subsidiaries, sales offices. Many companies prefer a SAP Cloud solution for customer user experience that helps sales representatives to provide outstanding customer experience and SAP CRM as a backend system to support key activities. Many companies prefer a SAP Cloud solution for customer user experience that helps sales representatives to provide outstanding customer experience and SAP CRM as a backend system to support key activities. An organization wants to extend the existing CRM platform to new users. An organization wants to extend the existing CRM platform to new users. The SAP CRM system is up and running smoothly, but the company wants to switch over to cloud solution for managing new deployments and releases. The SAP CRM system is up and running smoothly, but the company wants to switch over to cloud solution for managing new deployments and releases. To replace the existing cloud SFA solutions with SAP Cloud for Customer. To replace the existing cloud SFA solutions with SAP Cloud for Customer. SAP provides standard integration scenarios for integration with SAP ERP and SAP CRM. Integration with ERP and CRM is very common. SAP provides standard integration scenarios for integration with SAP ERP and SAP CRM. Integration with ERP and CRM is very common. Two common integration scenarios that are prepacked with cloud solution are − SAP NetWeaver Process Integrator SAP HANA Cloud Integration HCI SAP HANA Cloud Integration is SAP’s Cloud middleware that can be used for Integration. It is a cloud option of the customers, who do not currently have an integration middleware. The integration middleware enables the customization of the integration as well as design of new integration scenarios. To create a communication system in SAP Hybris Cloud for customers, let us follow the steps given below − Step 1 − Navigate to Administration work center → Communication System → New. Step 2 − Enter ID, system access type and system Instance ID. Enter other fields as per the requirement. Select SAP Business Suit, if you are creating communication system for integrating SAP on the premise system (SAP ECC or SAP CRM) with SAP C4C. Enter Business System Id, IDOC logical Systems Id, SAP Client, Preferred application protocol. These are On-premise data. Therefore, we need to get this information from the On-premise system to enter here. Click on Save. Step 3 − The next step is to enter the details in the Communication Arrangements. Step 4 − Click on the ‘New’ button as shown in the following screenshot. Step 5 − A new window “New Communication Arrangement” will open. You need to select the communication scenario from the list as per the requirement. You have to select an account, as you want to replicate accounts from the On-premise system to SAP C4C system. Under the Select Scenarios tab, select the communications scenario for which you want to create a communication arrangement and then click on Next. Based on the communication scenario you selected, the system presets the fields in the next steps with default values. You can change the values, if necessary. Step 6 − Under Define Business Data tab, select System Instance ID. Click Value selection. If you have selected a B2B scenario, enter the ID of the business partner and select the associated Identification type. Select the communication system that we have created from the list and click on Next. Step 7 − In the Define Technical Data step, define the technical settings for inbound and outbound communication. Enter the application method and Authentication Method → click on Next. Step 8 − In the Review step, review the data you entered in the previous steps. To ensure that all data is correct, click Check Completeness. To create and activate your communication arrangement in the system, click on Finish. You can also save an inactive version of the communication arrangement by clicking Save as Draft. You can also create a new communication scenario by going to the Administrator work center → Communication Scenario. As a part of the SAP C4C, there are various activities, which you need to perform under project implementation. We will discuss some of the key activities here. The first step in implementation is preparing the system. This includes creating system administrator for implementation, scoping of C4C system, defining migration strategies for data from On-premise to Cloud System, etc. As per the scope of project, fine-tuning involves performing customization in SAP ECC On-premise system to perform configuration and setup your customizing as per the project scope. It includes creating users and business roles, defining organization structure and management rules, etc. Data Migration and Integration includes performing manual data migration by using the default templates based cloud system. In case of integration being in scope, then perform initial data load from On-premise source system to cloud system. In the Test phase, you perform Unit, Regression, Data test, etc. Go Live work center includes activities like user enablement. SAP C4C administrator is enabled who takes care of the day-to-day operation and supports activities before it goes live. Once this is done, you can set the system to Live. To implement a project in SAP C4C, follow the steps given below − Step 1 − Go to Business Configuration work center → Implementation Project. Step 2 − Click the New tab to start implementing a new project. As a project already exists, click Edit Project Scope to see the steps in implementation. The Cloud Application Studio is a cloud based Software Development Kit (SDK) that allows SAP customers to enhance the features of SAP Cloud Solutions – SAP Hybris Cloud for Customer and SAP Business by Design application. The SAP Cloud Application Studio is used to extend the underlying SAP Cloud solution to meet customer specific requirements, legal requirements or industry specific best practices. Following are the key features provided by the SAP Cloud Application Studio − Integrated Development Environment (IDE) UI Designer for new UI’s Web Services Extensibility Integrated Add on lifecycle SAP Store Publish option The Cloud Application Studio is based on a local integrated development environment (IDE), which provides access to all the tools that are required to create or extend the features of SAP Cloud based applications. Provides access to all the tools that you need to create and enhance the functionality of the SAP standard cloud solutions. Provides access to all the tools that you need to create and enhance the functionality of the SAP standard cloud solutions. Using IDE, developers can manage the entire lifecycle of the customer-specific solutions, including development, testing and assembly. Using IDE, developers can manage the entire lifecycle of the customer-specific solutions, including development, testing and assembly. Easy programming of custom applications. Easy programming of custom applications. In the next chapter, we will discuss regarding security and user management in SAP Hybris. In SAP Hybris C4C, user management deals with maintaining the employee records in a system and creation of users and business roles. As per the business roles, you can assign different access rights and data restrictions to the users. To create an employee in the Hybris C4C system, follow the steps given below. Step 1 − Open Silverlight UI, go to Administrator → click Employees. A new window opens. Step 2 − To create a new employee, click New → Employee. Step 3 − Enter all the fields in the New Employee page like Name, Gender, Preferred Language, Validity, Organizational Data, Address, etc. Step 4 − Click on the Save button as shown in the following screenshot. 25 Lectures 6 hours Sanjo Thomas 26 Lectures 2 hours Neha Gupta 30 Lectures 2.5 hours Sumit Agarwal 30 Lectures 4 hours Sumit Agarwal 14 Lectures 1.5 hours Neha Malik 13 Lectures 1.5 hours Neha Malik Print Add Notes Bookmark this page
[ { "code": null, "e": 2785, "s": 2463, "text": "SAP Hybris is a family of product from a German company Hybris, which sells e-Commerce, Marketing, Sales, Service and Product Content Management Software. SAP Hybris provides solutions that helps any organization to cut cost, save time, reduce complexity and require lesser focus to achieve excellent customer experience." }, { "code": null, "e": 3315, "s": 2785, "text": "Hybris was introduced in 1997 in Zug, Switzerland and later this company was acquired by SAP S.E on 1 August 2013. SAP has integrated its own premise backend system – SAP CRM and SAP ERP with the Hybris solution, so any company that has SAP ERP or SAP CRM implemented can easily move to the SAP Hybris solution. The SAP Hybris Commerce Accelerator is an Omni channel e-commerce solution with storefront templates and tools to provide an amazing customer engagement experience. Hybris Product focuses on the following main areas −" }, { "code": null, "e": 3324, "s": 3315, "text": "Commerce" }, { "code": null, "e": 3334, "s": 3324, "text": "Marketing" }, { "code": null, "e": 3352, "s": 3334, "text": "Revenue (Billing)" }, { "code": null, "e": 3358, "s": 3352, "text": "Sales" }, { "code": null, "e": 3366, "s": 3358, "text": "Service" }, { "code": null, "e": 3393, "s": 3366, "text": "Hybris as a Service (YaaS)" }, { "code": null, "e": 3437, "s": 3393, "text": "Let us now discuss each of these in detail." }, { "code": null, "e": 3723, "s": 3437, "text": "This is used to provide a meaningful and consistent experience to every channel. It includes products for B2C Commerce, B2B Commerce, Product Content and Catalog Management, Omni-Channel fulfillment, and Merchandising to understand what customer wants and to turn visitors into buyers." }, { "code": null, "e": 3835, "s": 3723, "text": "This is to understand the customer behavior in real-time and to provide them what they want and when they want." }, { "code": null, "e": 4151, "s": 3835, "text": "This solution provides a company with the capability to work in complex partner ecosystems, reselling products and sharing the revenue. It includes products for Subscription Order Management, Revenue in Cloud, Responsive Quality Control, Customer Financial Management, Consolidated Billing, Invoicing and many more." }, { "code": null, "e": 4593, "s": 4151, "text": "SAP Hybris cloud for Sales takes customer information from the backend system provides it to the front-end Sales team and enables them to understand target customers, and how to grab each opportunity of a new sale. This provides information to the sales executive out in the field and on the mobile device in the hands of the sales executive. It includes product for Retail Execution, Sales Performance Management and Sales Force Automation." }, { "code": null, "e": 4951, "s": 4593, "text": "SAP Hybris for Service allows a company to provide an exceptional service experience to its customer and hence delightful customer engagement experience. Using Hybris Service, organizations can give its customer the right service on the right channel. It includes product for Omni Channel Call Center, Proactive Field Service and Comprehensive Self Service." }, { "code": null, "e": 5239, "s": 4951, "text": "This is one of the most advanced micro services ecosystem, which allows a company to develop custom applications with the existing platform. YaaS allows companies to reassemble and adapt the existing services to build a custom experience without the need of developing them from scratch." }, { "code": null, "e": 5304, "s": 5239, "text": "The URL for Hybris solution and its key features is given below." }, { "code": null, "e": 5323, "s": 5304, "text": "www.hybris.com/en/" }, { "code": null, "e": 5500, "s": 5323, "text": "You can navigate to the Products section to see what all key products are being offered by SAP Hybris. You can also scroll down to different sub-categories under each category." }, { "code": null, "e": 5725, "s": 5500, "text": "Following are the Industries where SAP Hybris is implemented. It is implemented in Automotive, Banking and Finance, Consumer Products, Healthcare, Insurance and Manufacturing, Retail, Public Sector and many other industries." }, { "code": null, "e": 5808, "s": 5725, "text": "You can navigate to the “Customers” section to see the client list for SAP Hybris." }, { "code": null, "e": 6088, "s": 5808, "text": "Hybris is an ecommerce product platform that is used to address a family of products involving Customer Experience and Management. Hybris is not a single product like SAP ERP or SAP BW system, rather it is a group of products to provide end to end customer engagement experience." }, { "code": null, "e": 6418, "s": 6088, "text": "SAP Hybris is also different from SAP Hybris Cloud for Customer, which is a cloud based CRM application that has been recently renamed by SAP as SAP Hybris C4C solution. Hybris offers product for Commerce, Billing or Revenue, Sales, Service and Marketing and SAP Hybris Marketing is completely different from the Hybris Commerce." }, { "code": null, "e": 6500, "s": 6418, "text": "The SAP Hybris Product family contains the following distinct products named as −" }, { "code": null, "e": 6516, "s": 6500, "text": "Hybris Commerce" }, { "code": null, "e": 6542, "s": 6516, "text": "Hybris Revenue or Billing" }, { "code": null, "e": 6578, "s": 6542, "text": "Hybris Cloud for Customer for Sales" }, { "code": null, "e": 6616, "s": 6578, "text": "Hybris Cloud for Customer for Service" }, { "code": null, "e": 6633, "s": 6616, "text": "Hybris Marketing" }, { "code": null, "e": 6981, "s": 6633, "text": "The Hybris product family can be integrated with other backend solutions from SAP like SAP ERP and SAP CRM to achieve end-to-end customer engagement experience. Here, we have mentioned five products. However, in reality there are only four products as product for Sales and Product for Service are a part of SAP Hybris Cloud for Customer solution." }, { "code": null, "e": 7039, "s": 6981, "text": "The following image shows the SAP Hybris Product Family −" }, { "code": null, "e": 7390, "s": 7039, "text": "With SAP Hybris Commerce Cloud, companies can meet those expectations and deliver great experiences that gain their loyalty. SAP Hybris Commerce Cloud can help companies to understand their customers at every point of the commerce experience, so they can drive relevant, meaningful interactions, from content creation to merchandising to fulfillment." }, { "code": null, "e": 7656, "s": 7390, "text": "Hybris products for E-Commerce includes B2B and B2C commerce applications like Product Content Management (PCM), Search and Merchandising and Order Management. Hybris commerce provides all the features that an organization can expect from an E-Commerce application." }, { "code": null, "e": 7753, "s": 7656, "text": "The Hybris product site covers the following capabilities of SAP Hybris Product for e-Commerce −" }, { "code": null, "e": 7789, "s": 7753, "text": "www.hybris.com/en/products/commerce" }, { "code": null, "e": 7802, "s": 7789, "text": "B2C Commerce" }, { "code": null, "e": 7815, "s": 7802, "text": "B2B Commerce" }, { "code": null, "e": 7854, "s": 7815, "text": "Product Content and Catalog Management" }, { "code": null, "e": 7879, "s": 7854, "text": "Omni-Channel Fulfillment" }, { "code": null, "e": 7911, "s": 7879, "text": "Creating Contextual Experiences" }, { "code": null, "e": 8147, "s": 7911, "text": "This solution provides Revenue management, highly automated billing and invoicing solution. Using SAP Hybris Revenue Cloud, you can deliver Price and Quote, Order Management and Subscription Billing experiences directly from the cloud." }, { "code": null, "e": 8305, "s": 8147, "text": "It provides more flexibility to work in a complex partner ecosystem. Following is the product link from the Hybris site − www.hybris.com/en/products/billing." }, { "code": null, "e": 8378, "s": 8305, "text": "The following capabilities are covered in SAP Hybris Cloud for Revenue −" }, { "code": null, "e": 8395, "s": 8378, "text": "Revenue in cloud" }, { "code": null, "e": 8425, "s": 8395, "text": "Subscription Order Management" }, { "code": null, "e": 8452, "s": 8425, "text": "Responsive Quality Control" }, { "code": null, "e": 8467, "s": 8452, "text": "Agile Charging" }, { "code": null, "e": 8477, "s": 8467, "text": "Invoicing" }, { "code": null, "e": 8507, "s": 8477, "text": "Versatile Document Management" }, { "code": null, "e": 8537, "s": 8507, "text": "Customer Financial Management" }, { "code": null, "e": 8558, "s": 8537, "text": "Consolidated Billing" }, { "code": null, "e": 8876, "s": 8558, "text": "This solution is used to fetch data from the on premise backend-system and provide it to the front-end sales team. The Sales team can access data on a mobile device and this provides information they need to know, who the target customers are, any issues in sales process and how to covert each opportunity to a sale." }, { "code": null, "e": 8947, "s": 8876, "text": "The following capabilities are covered in the SAP C4C Sales solution −" }, { "code": null, "e": 8970, "s": 8947, "text": "Sales Force Automation" }, { "code": null, "e": 8999, "s": 8970, "text": "Sales Performance Management" }, { "code": null, "e": 9016, "s": 8999, "text": "Retail Execution" }, { "code": null, "e": 9049, "s": 9016, "text": "www.hybris.com/en/products/sales" }, { "code": null, "e": 9227, "s": 9049, "text": "This solution helps an organization to deliver an excellence customer service experience to its customers. Following capabilities are available in SAP C4C for Service solution −" }, { "code": null, "e": 9254, "s": 9227, "text": "Comprehensive Self-Service" }, { "code": null, "e": 9279, "s": 9254, "text": "Omni-Channel Call Center" }, { "code": null, "e": 9303, "s": 9279, "text": "Proactive Field Service" }, { "code": null, "e": 9355, "s": 9303, "text": "The link to the Hybris product site is as follows −" }, { "code": null, "e": 9390, "s": 9355, "text": "www.hybris.com/en/products/service" }, { "code": null, "e": 9806, "s": 9390, "text": "SAP Hybris Marketing solutions help the organization to understand its customer choices in real time and help them to maintain customer profiles from the data gathered from different sources. Old time CRM Marketing was not providing data in real time, however SAP Hybris Marketing is providing the most cutting edge solutions to marketers for providing personalized marketing experience as per their changing needs." }, { "code": null, "e": 9879, "s": 9806, "text": "The following capabilities are available in SAP C4C Marketing solution −" }, { "code": null, "e": 9906, "s": 9879, "text": "Dynamic Customer Profiling" }, { "code": null, "e": 9943, "s": 9906, "text": "Segmentation and Campaign Management" }, { "code": null, "e": 9962, "s": 9943, "text": "Commerce Marketing" }, { "code": null, "e": 9981, "s": 9962, "text": "Loyalty Management" }, { "code": null, "e": 10011, "s": 9981, "text": "Marketing Resource Management" }, { "code": null, "e": 10030, "s": 10011, "text": "Marketing Analysis" }, { "code": null, "e": 10056, "s": 10030, "text": "Marketing Lead Management" }, { "code": null, "e": 10077, "s": 10056, "text": "Customer Attribution" }, { "code": null, "e": 10105, "s": 10077, "text": "Architecture and Technology" }, { "code": null, "e": 10150, "s": 10105, "text": "The Hybris product site link is as follows −" }, { "code": null, "e": 10187, "s": 10150, "text": "www.hybris.com/en/products/marketing" }, { "code": null, "e": 10549, "s": 10187, "text": "SAP C4C (Cloud for Customer) is a SAP Cloud based CRM based management solution and is different from the traditional SAP CRM on premise setup. SAP C4C provides the best CRM based Sales, Service and Marketing practices including options to access its mobile devices. In April 2016, SAP renamed their Cloud for Customer solution as SAP Hybris Cloud for Customer." }, { "code": null, "e": 10774, "s": 10549, "text": "SAP Hybris is different from SAP Hybris Cloud for Customer in sense that it offers product for Commerce, Billing or Revenue, Sales, Service and Marketing and SAP Hybris Marketing is completely different from Hybris Commerce." }, { "code": null, "e": 10858, "s": 10774, "text": "The SAP Hybris Product family contains the following distinct products, which are −" }, { "code": null, "e": 10874, "s": 10858, "text": "Hybris Commerce" }, { "code": null, "e": 10900, "s": 10874, "text": "Hybris Revenue or Billing" }, { "code": null, "e": 10936, "s": 10900, "text": "Hybris Cloud for Customer for Sales" }, { "code": null, "e": 10974, "s": 10936, "text": "Hybris Cloud for Customer for Service" }, { "code": null, "e": 10991, "s": 10974, "text": "Hybris Marketing" }, { "code": null, "e": 11256, "s": 10991, "text": "In the above family of products under the Hybris umbrella, SAP Hybris Cloud for Customer for Sales and for Services are provided using SAP Cloud for Customer product. This provides close integration with traditional backend systems like SAP CRM and SAP ERP system." }, { "code": null, "e": 11368, "s": 11256, "text": "SAP Hybris portfolio also includes Commerce, Billing and Marketing part apart from cloud for Sales and Service." }, { "code": null, "e": 11667, "s": 11368, "text": "Note − You can integrate Cloud for Customer C4C solution to Hybris commerce platform, and both offers consistent end-to-end customer experience solution. SAP has maintained Hybris Commerce platform and Cloud for Customer as two different products, built separately to serve two different audiences." }, { "code": null, "e": 11925, "s": 11667, "text": "When an organization buys Hybris commerce, it does not provide the license for C4C solution or buying C4C does not provide the organization with the license of Hybris commerce. License has to be purchased separately for both products from the Hybris family." }, { "code": null, "e": 11982, "s": 11925, "text": "SAP C4C is based on the following individual products −" }, { "code": null, "e": 12002, "s": 11982, "text": "SAP Cloud for Sales" }, { "code": null, "e": 12026, "s": 12002, "text": "SAP Cloud for Marketing" }, { "code": null, "e": 12058, "s": 12026, "text": "SAP Cloud for Social Engagement" }, { "code": null, "e": 12136, "s": 12058, "text": "Following is the HTML user interface for SAP Cloud for Customer C4C product −" }, { "code": null, "e": 12221, "s": 12136, "text": "It is also available in Microsoft Silverlight mode as shown in following screenshot." }, { "code": null, "e": 12473, "s": 12221, "text": "SAP Hybris provides product for e-Commerce, Marketing, Sales and Service, Revenue and cross-functional solutions and they are designed to help organizations to create valuable interactions with their customers and support for different industry types." }, { "code": null, "e": 12540, "s": 12473, "text": "Hybris includes product portfolio for the following capabilities −" }, { "code": null, "e": 12562, "s": 12540, "text": "Products for Commerce" }, { "code": null, "e": 12585, "s": 12562, "text": "Products for Marketing" }, { "code": null, "e": 12604, "s": 12585, "text": "Products for Sales" }, { "code": null, "e": 12625, "s": 12604, "text": "Products for Service" }, { "code": null, "e": 12646, "s": 12625, "text": "Products for Billing" }, { "code": null, "e": 12672, "s": 12646, "text": "Cross-Functional Solution" }, { "code": null, "e": 12815, "s": 12672, "text": "The link of Hybris site to view the complete product portfolio under Hybris umbrella is − https://www.hybris.com/en/products/digital-portfolio" }, { "code": null, "e": 12916, "s": 12815, "text": "The products for commerce available under SAP Hybris Commerce are explained in the screenshot below." }, { "code": null, "e": 13142, "s": 12916, "text": "SAP Hybris Commerce Cloud can help a company to understand their customers at every point of the commerce experience, so they can drive relevant, meaningful interactions, from content creation to merchandising to fulfillment." }, { "code": null, "e": 13382, "s": 13142, "text": "SAP Hybris Marketing is providing the most innovative solutions to marketers for providing personalized marketing experience as per their changing needs. The following product portfolio is available under SAP Hybris Products for Marketing." }, { "code": null, "e": 13612, "s": 13382, "text": "Hybris for Sales solution provides sales team to access data on mobile device and this provides information they need to know who the target customers are, any issues in sales process and how to covert each opportunity to a sale." }, { "code": null, "e": 13993, "s": 13612, "text": "This solution helps an organization to deliver an excellent customer service experience to its customers. Hybris Products for Service offers a consistent experience across all channels, access complete and contextual customer information, and gain real-time insight into call center performance and field service management. Following products are available under this portfolio −" }, { "code": null, "e": 14192, "s": 13993, "text": "Using SAP Hybris Revenue Cloud, you can deliver Price and Quote, Order Management and Subscription Billing experiences directly from the cloud. Following products are available under this category −" }, { "code": null, "e": 14432, "s": 14192, "text": "Apart from products mentioned, SAP also provides wide range of cross-functional solutions to manage customer interactions, wide range of tools to manage incentive plans and sales commission and to securely sign and manage documents online." }, { "code": null, "e": 14653, "s": 14432, "text": "SAP Hybris Commerce Accelerator provides organizations with ready-to-use Omni-channel commerce solutions with storefront templates and business tools that allows organization to create an exceptional customer experience." }, { "code": null, "e": 14947, "s": 14653, "text": "When a new project is started, it includes everything working ready for you to rebrand and customize as needed. SAP Hybris Accelerator is designed to provide the platform and architecture of SAP Hybris Commerce that helps in reducing cost of ownership and speeds up the implementation process." }, { "code": null, "e": 15167, "s": 14947, "text": "The SAP Hybris Commerce Accelerator is available for B2B, B2C, Financial services and other marketing types. Whereas, the sites are available with market specific capabilities and expected features for each market type." }, { "code": null, "e": 15244, "s": 15167, "text": "Following are the key advantages of using a SAP Hybris Accelerator concept −" }, { "code": null, "e": 15375, "s": 15244, "text": "By using an Accelerator, companies get an integrated, truly Omni-channel solution from the starting day of project implementation." }, { "code": null, "e": 15506, "s": 15375, "text": "By using an Accelerator, companies get an integrated, truly Omni-channel solution from the starting day of project implementation." }, { "code": null, "e": 15606, "s": 15506, "text": "By using an Accelerator, you can have a solid infrastructure to scale out the business requirement." }, { "code": null, "e": 15706, "s": 15606, "text": "By using an Accelerator, you can have a solid infrastructure to scale out the business requirement." }, { "code": null, "e": 15800, "s": 15706, "text": "It reduces the implementation cost and time by providing platform for different device types." }, { "code": null, "e": 15894, "s": 15800, "text": "It reduces the implementation cost and time by providing platform for different device types." }, { "code": null, "e": 15977, "s": 15894, "text": "Ease to use tools for building and maintaining a feature-rich shopping experience." }, { "code": null, "e": 16060, "s": 15977, "text": "Ease to use tools for building and maintaining a feature-rich shopping experience." }, { "code": null, "e": 16156, "s": 16060, "text": "The following illustration shows the layered architecture of a SAP Hybris Commerce Accelerator." }, { "code": null, "e": 16415, "s": 16156, "text": "The top layer includes – HMC, Web Services and Cockpits, which define objects that end user uses to interact with applications. Various user actions can be performed like adding a product to the cart, edit quantity in shopping carts and manage user profiles." }, { "code": null, "e": 16674, "s": 16415, "text": "The top layer includes – HMC, Web Services and Cockpits, which define objects that end user uses to interact with applications. Various user actions can be performed like adding a product to the cart, edit quantity in shopping carts and manage user profiles." }, { "code": null, "e": 16815, "s": 16674, "text": "Hybris Service Layer Framework is responsible to implement Java Application Programmer’s Interface for objects in the Hybris Commerce Suite." }, { "code": null, "e": 16956, "s": 16815, "text": "Hybris Service Layer Framework is responsible to implement Java Application Programmer’s Interface for objects in the Hybris Commerce Suite." }, { "code": null, "e": 17039, "s": 16956, "text": "The Type layer defines business object models, which are generated based on types." }, { "code": null, "e": 17122, "s": 17039, "text": "The Type layer defines business object models, which are generated based on types." }, { "code": null, "e": 17214, "s": 17122, "text": "The Persistence Layer is responsible for abstraction from database, caching and clustering." }, { "code": null, "e": 17306, "s": 17214, "text": "The Persistence Layer is responsible for abstraction from database, caching and clustering." }, { "code": null, "e": 17389, "s": 17306, "text": "The Database layer is used to store the data contained in a Hybris Commerce suite." }, { "code": null, "e": 17472, "s": 17389, "text": "The Database layer is used to store the data contained in a Hybris Commerce suite." }, { "code": null, "e": 17509, "s": 17472, "text": "Other important components include −" }, { "code": null, "e": 17864, "s": 17509, "text": "This is one of the key component in the top layer in Hybris. Products are maintained in the product cockpit if there is a requirement to update the description, then it can be done using the product cockpit without making a change to the code. It also has the CMS cockpit that allows marketing content to be updated without any dependence on the IT team." }, { "code": null, "e": 18025, "s": 17864, "text": "HMC or Backoffice provides a single user interface to manage any kind of data. It can be used to access stores, sites, products, users, companies, and catalogs." }, { "code": null, "e": 18260, "s": 18025, "text": "The following screenshots displays the Hybris B2C Accelerator that contains storefront templates and business tools based on best practices, which are designed to speed up the implementation and to reduce cost and implementation time." }, { "code": null, "e": 18486, "s": 18260, "text": "Product Content Management in SAP Hybris Cloud is used to incorporate product images in new marketing messages. These marketing messages can be created by using Messages and Email templates app or by using the Content Studio." }, { "code": null, "e": 18712, "s": 18486, "text": "A Digital Asset Management system is used to store images. It allows you to perform search capabilities. You can integrate Digital Asset Management (DAM) as the communication system with SAP Hybris Product Content Management." }, { "code": null, "e": 18993, "s": 18712, "text": "To integrate a PCM system with the Communication system app, you have to add a new Communication System. Go to the Open Communication System app and click on “New” to create a new communication system. In the new window, enter the following details and click on the Create button." }, { "code": null, "e": 19025, "s": 18993, "text": "System ID − HYBRIS_COMMERCE_PCM" }, { "code": null, "e": 19057, "s": 19025, "text": "System ID − HYBRIS_COMMERCE_PCM" }, { "code": null, "e": 19091, "s": 19057, "text": "System Name − HYBRIS_COMMERCE_PCM" }, { "code": null, "e": 19125, "s": 19091, "text": "System Name − HYBRIS_COMMERCE_PCM" }, { "code": null, "e": 19408, "s": 19125, "text": "In the next window, you have to the enter Host name – SAP Hybris Commerce server name. Next is to add inbound/outbound technical User for communication. You can select a user from the existing list or you can also create a new user by using the option – Maintain Communication User." }, { "code": null, "e": 19572, "s": 19408, "text": "You can also create new Communication Arrangements using the Communication Arrangement app and click on the ‘New’ option to create a new Communication arrangement." }, { "code": null, "e": 19745, "s": 19572, "text": "Follow the steps mentioned in the wizard, click on Next and you can click on Test Connection. The following information is required to add a new Communication Arrangement −" }, { "code": null, "e": 19846, "s": 19745, "text": "Port − In the next dialog box, you need to pass the port number setup on the server for HTTPS (SSL)." }, { "code": null, "e": 19947, "s": 19846, "text": "Port − In the next dialog box, you need to pass the port number setup on the server for HTTPS (SSL)." }, { "code": null, "e": 20056, "s": 19947, "text": "Path − In the Path option, you have to enter the path to the V1 REST API of the Omni Commerce Channel (OCC)." }, { "code": null, "e": 20165, "s": 20056, "text": "Path − In the Path option, you have to enter the path to the V1 REST API of the Omni Commerce Channel (OCC)." }, { "code": null, "e": 20231, "s": 20165, "text": "Service URL − In this field, you have to mention the service URL." }, { "code": null, "e": 20297, "s": 20231, "text": "Service URL − In this field, you have to mention the service URL." }, { "code": null, "e": 20383, "s": 20297, "text": "Click on Save. You can click on Test Connection button to check the connection setup." }, { "code": null, "e": 20686, "s": 20383, "text": "One of the main features in Hybris is the flexibility to add new objects to the global Hybris Commerce Data model. Hybris data modeling helps an organization in maintaining their database and help to manage database connections and queries. Hybris Type system is used to design data modeling in Hybris." }, { "code": null, "e": 20761, "s": 20686, "text": "A Hybris type system has the following types supported for data modeling −" }, { "code": null, "e": 20842, "s": 20761, "text": "Items.xml − This file is used for data modeling in a Hybris Commerce data model." }, { "code": null, "e": 20923, "s": 20842, "text": "Items.xml − This file is used for data modeling in a Hybris Commerce data model." }, { "code": null, "e": 20967, "s": 20923, "text": "Item types − This is used to create tables." }, { "code": null, "e": 21011, "s": 20967, "text": "Item types − This is used to create tables." }, { "code": null, "e": 21076, "s": 21011, "text": "Relation types − This is used to create relation between tables." }, { "code": null, "e": 21141, "s": 21076, "text": "Relation types − This is used to create relation between tables." }, { "code": null, "e": 21193, "s": 21141, "text": "Atomic types − Used to create various Atomic types." }, { "code": null, "e": 21245, "s": 21193, "text": "Atomic types − Used to create various Atomic types." }, { "code": null, "e": 21292, "s": 21245, "text": "Collection types − Used to create Collections." }, { "code": null, "e": 21339, "s": 21292, "text": "Collection types − Used to create Collections." }, { "code": null, "e": 21367, "s": 21339, "text": "Map Types − To define maps." }, { "code": null, "e": 21395, "s": 21367, "text": "Map Types − To define maps." }, { "code": null, "e": 21425, "s": 21395, "text": "Enum types − To define Enums." }, { "code": null, "e": 21455, "s": 21425, "text": "Enum types − To define Enums." }, { "code": null, "e": 21498, "s": 21455, "text": "Let us now discuss all of these in detail." }, { "code": null, "e": 21647, "s": 21498, "text": "These are defined as basic types in Hybris, which include Java number and string objects – java.lang.integer, java.lang.boolean or java.lang.string." }, { "code": null, "e": 22100, "s": 21647, "text": "<atomictypes>\n <atomictype class = \"java.lang.Object\" autocreate = \"true\" generate = \"false\" />\n <atomictype class = \"java.lang.Boolean\" extends = \"java.lang.Object\" autocreate = \"true\" generate = \"false\" />\n <atomictype class = \"java.lang.Double\" extends = \"java.lang.Number\" autocreate = \"true\" generate = \"false\" />\n <atomictype class = \"java.lang.String\" extends = \"java.lang.Object\" autocreate = \"true\" generate = \"false\" />\n</atomictypes>" }, { "code": null, "e": 22325, "s": 22100, "text": "Item types are used to create new tables or to update existing tables. This is considered as a base for a Hybris type system. All new table structures are configured over this type using different attributes as shown below −" }, { "code": null, "e": 22748, "s": 22325, "text": "<itemtype code = \"Customer\" extends = \"User\" \n jaloclass = \"de.hybris/platform.jalo.user.Customer\" autocreate = \"true\" generate = \"true\">\n <attributes>\n <attribute autocreate = \"true\" qualifier = \"customerID\" type = \"java.lang.String\">\n <modifiers read = \"true\" write = \"true\" search = \"true\" optional = \"true\"/>\n <persistence type = \"property\"/>\n </attribute> \n </attributes>\n</itemtype>" }, { "code": null, "e": 22848, "s": 22748, "text": "This type is used to create a link between tables. For example – You can link a country and region." }, { "code": null, "e": 23348, "s": 22848, "text": "<relation code = \"Country2RegionRelation\" generate = \"true\" localized = \"false\" \n autocreate = \"true\">\n \n <sourceElement type = \"Country\" qualifier = \"country\" cardinality = \"one\">\n <modifiers read = \"true\" write = \"true\" search = \"true\" optional = \"false\" unique = \"true\"/>\n </sourceElement>\n \n <targetElement type = \"Region\" qualifier = \"regions\" cardinality = \"many\">\n <modifiers read = \"true\" write = \"true\" search = \"true\" partof = \"true\"/>\n </targetElement>\n</relation>" }, { "code": null, "e": 23466, "s": 23348, "text": "These are used to build enumeration in Java for preparing a particular set of values. For example – Months in a year." }, { "code": null, "e": 23659, "s": 23466, "text": "<enumtype code = \"CreditCardType\" autocreate = \"true\" generate = \"true\">\n <value code = \"amex\"/>\n <value code = \"visa\"/>\n <value code = \"master\"/>\n <value code = \"diners\"/>\n</enumtype>" }, { "code": null, "e": 23743, "s": 23659, "text": "These are used to build collection/group of element types – group of products, etc." }, { "code": null, "e": 24057, "s": 23743, "text": "<collectiontype code = \"ProductCollection\" elementtype = \"Product\" autocreate = \"true\" generate = \"true\"/>\n<collectiontype code = \"LanguageList\" elementtype = \"Langauage\" autocreate = \"true\" generate = \"true\"/>\n<collectiontype code = \"LanguageSet\" elementtype = \"Langauage\" autocreate = \"true\" generate = \"true\"/>" }, { "code": null, "e": 24161, "s": 24057, "text": "Map types are used to store key values pairs in Hybris data modeling. Each key represents its own code." }, { "code": null, "e": 24310, "s": 24161, "text": "<maptype code = \"localized:java.lang.String\" argumenttype = \"Language\" \n returntype = \"java.lang.String\" autocreate = \"true\" generate = \"false\"/>\n" }, { "code": null, "e": 24621, "s": 24310, "text": "Bundling module in SAP Hybris is used to address the needs of companies that sells service bundles and digital products. SAP Hybris provides a tool for configuring, to manage and sell bundled offerings. Bundling module provides various benefits in the e-commerce model. Some of these benefits are given below −" }, { "code": null, "e": 24737, "s": 24621, "text": "Using bundling service, organizations can increase average order value and margin by bundling content and products." }, { "code": null, "e": 24853, "s": 24737, "text": "Using bundling service, organizations can increase average order value and margin by bundling content and products." }, { "code": null, "e": 24964, "s": 24853, "text": "Bundling module improves conversion rates with personalized and content-rich shopping experience to customers." }, { "code": null, "e": 25075, "s": 24964, "text": "Bundling module improves conversion rates with personalized and content-rich shopping experience to customers." }, { "code": null, "e": 25176, "s": 25075, "text": "It helps e-commerce organizations to cross-sell physical and digital goods on one commerce platform." }, { "code": null, "e": 25277, "s": 25176, "text": "It helps e-commerce organizations to cross-sell physical and digital goods on one commerce platform." }, { "code": null, "e": 25435, "s": 25277, "text": "Bundling helps an organization in managing and expanding product offerings by transforming complex products into simple, compelling selections for customers." }, { "code": null, "e": 25593, "s": 25435, "text": "Bundling helps an organization in managing and expanding product offerings by transforming complex products into simple, compelling selections for customers." }, { "code": null, "e": 25687, "s": 25593, "text": "Easy to use, flexible business tool to manage complex product offerings and bundling service." }, { "code": null, "e": 25781, "s": 25687, "text": "Easy to use, flexible business tool to manage complex product offerings and bundling service." }, { "code": null, "e": 26078, "s": 25781, "text": "Using SAP Hybris Bundling Module, organizations can easily set up a Product Cockpit by adding physical products like gaming bundles, media packages, etc., to specific bundle categories. Companies can also apply different pricing rules on bundle categories with setting up different merchandising." }, { "code": null, "e": 26159, "s": 26078, "text": "You can achieve the following key features using a SAP Hybris Bundling concept −" }, { "code": null, "e": 26282, "s": 26159, "text": "Hybris Bundling module provides organization with bundle templates to guide selling of products using the product cockpit." }, { "code": null, "e": 26405, "s": 26282, "text": "Hybris Bundling module provides organization with bundle templates to guide selling of products using the product cockpit." }, { "code": null, "e": 26486, "s": 26405, "text": "Bundling provides optimized shopping carts for customers in an e-commerce model." }, { "code": null, "e": 26567, "s": 26486, "text": "Bundling provides optimized shopping carts for customers in an e-commerce model." }, { "code": null, "e": 26687, "s": 26567, "text": "Bundling service in Hybris helps in managing advanced bundle merchandising and personalization of merchandise behavior." }, { "code": null, "e": 26807, "s": 26687, "text": "Bundling service in Hybris helps in managing advanced bundle merchandising and personalization of merchandise behavior." }, { "code": null, "e": 26879, "s": 26807, "text": "Easy management of B2C and B2B channel using flexible Bundling service." }, { "code": null, "e": 26951, "s": 26879, "text": "Easy management of B2C and B2B channel using flexible Bundling service." }, { "code": null, "e": 27191, "s": 26951, "text": "Bundling service provides product merchandisers with ability to create bundles dynamically of physical and/or digital products based on predefined bundling templates and these can be available to customer suing easy to use Product cockpit." }, { "code": null, "e": 27431, "s": 27191, "text": "Bundling service provides product merchandisers with ability to create bundles dynamically of physical and/or digital products based on predefined bundling templates and these can be available to customer suing easy to use Product cockpit." }, { "code": null, "e": 27534, "s": 27431, "text": "In the next chapter, we will discuss regarding the workflow and business process engine of SAP Hybris." }, { "code": null, "e": 27863, "s": 27534, "text": "With the use of SAP Hybris Workflow, companies can define standardized processes, which run automatically, when required. The Workflow Module can be easily integrated with the Hybris platform. It ensures efficient management of standardized processes in the backend and hence efficient teamwork along with clear task assignment." }, { "code": null, "e": 28083, "s": 27863, "text": "Users can easily define standardized process and use of commented feature makes teamwork more efficient. Workflow allows user to trigger predefined workflows for complex processes or adhoc workflows for one single task." }, { "code": null, "e": 28150, "s": 28083, "text": "Following are the benefits that can be achieved using a Workflow −" }, { "code": null, "e": 28274, "s": 28150, "text": "By using workflow integrated with other Hybris tools, you can handle processes more efficiently with a standardized method." }, { "code": null, "e": 28398, "s": 28274, "text": "By using workflow integrated with other Hybris tools, you can handle processes more efficiently with a standardized method." }, { "code": null, "e": 28509, "s": 28398, "text": "With the use of workflow, complex processes can be easily managed by defining tasks and corresponding actions." }, { "code": null, "e": 28620, "s": 28509, "text": "With the use of workflow, complex processes can be easily managed by defining tasks and corresponding actions." }, { "code": null, "e": 28684, "s": 28620, "text": "Workflow allows you to create templates as per the requirement." }, { "code": null, "e": 28748, "s": 28684, "text": "Workflow allows you to create templates as per the requirement." }, { "code": null, "e": 28799, "s": 28748, "text": "Comment functionality provides efficient teamwork." }, { "code": null, "e": 28850, "s": 28799, "text": "Comment functionality provides efficient teamwork." }, { "code": null, "e": 28913, "s": 28850, "text": "Workflow supports real time notifications to the user’s inbox." }, { "code": null, "e": 28976, "s": 28913, "text": "Workflow supports real time notifications to the user’s inbox." }, { "code": null, "e": 29103, "s": 28976, "text": "By using Hybris Workflow & Collaboration Module, it is easy for users to easily define workflows and view the workflow status." }, { "code": null, "e": 29226, "s": 29103, "text": "Workflow module can be easily implemented on the Hybris platform and you can integrate it with the Hybris product cockpit." }, { "code": null, "e": 29349, "s": 29226, "text": "Workflow module can be easily implemented on the Hybris platform and you can integrate it with the Hybris product cockpit." }, { "code": null, "e": 29437, "s": 29349, "text": "With the use of a Hybris Product Cockpit, users can easily access all workflow entries." }, { "code": null, "e": 29525, "s": 29437, "text": "With the use of a Hybris Product Cockpit, users can easily access all workflow entries." }, { "code": null, "e": 29577, "s": 29525, "text": "SAP Hybris provides predefined and adhoc workflows." }, { "code": null, "e": 29629, "s": 29577, "text": "SAP Hybris provides predefined and adhoc workflows." }, { "code": null, "e": 29713, "s": 29629, "text": "It is also possible to trigger the workflow using cron-jobs in the Hybris platform." }, { "code": null, "e": 29797, "s": 29713, "text": "It is also possible to trigger the workflow using cron-jobs in the Hybris platform." }, { "code": null, "e": 29864, "s": 29797, "text": "Hybris platform provides flexibility to create workflow templates." }, { "code": null, "e": 29931, "s": 29864, "text": "Hybris platform provides flexibility to create workflow templates." }, { "code": null, "e": 30040, "s": 29931, "text": "Users can design human and system based workflows Sequential, Parallel or Task-Dependent Workflow Execution." }, { "code": null, "e": 30149, "s": 30040, "text": "Users can design human and system based workflows Sequential, Parallel or Task-Dependent Workflow Execution." }, { "code": null, "e": 30211, "s": 30149, "text": "Workflow provides real-time notification via e-Mail to users." }, { "code": null, "e": 30273, "s": 30211, "text": "Workflow provides real-time notification via e-Mail to users." }, { "code": null, "e": 30360, "s": 30273, "text": "It is also possible to provide user access only relevant to-do’s in the workflow list." }, { "code": null, "e": 30447, "s": 30360, "text": "It is also possible to provide user access only relevant to-do’s in the workflow list." }, { "code": null, "e": 30533, "s": 30447, "text": "The following illustration shows commenting facility in Workflow on Hybris platform −" }, { "code": null, "e": 30692, "s": 30533, "text": "To create a new workflow rule, we should follow the subsequent steps. Navigate to the Worklist and click on the ‘New’ button from the workflow rules worklist." }, { "code": null, "e": 30736, "s": 30692, "text": "You have to enter the general information −" }, { "code": null, "e": 30798, "s": 30736, "text": "Mention the Description to identify the rule in the worklist." }, { "code": null, "e": 30860, "s": 30798, "text": "Mention the Description to identify the rule in the worklist." }, { "code": null, "e": 30967, "s": 30860, "text": "Next is to select the Business Object – such as opportunity or ticket, to which the rule is to be applied." }, { "code": null, "e": 31074, "s": 30967, "text": "Next is to select the Business Object – such as opportunity or ticket, to which the rule is to be applied." }, { "code": null, "e": 31254, "s": 31074, "text": "The next step is to select the Timing for applying the rule – you can select from the three following timing types to apply to your rule.\n\nOn Create Only\nOn Every Save\nScheduled\n\n" }, { "code": null, "e": 31392, "s": 31254, "text": "The next step is to select the Timing for applying the rule – you can select from the three following timing types to apply to your rule." }, { "code": null, "e": 31407, "s": 31392, "text": "On Create Only" }, { "code": null, "e": 31422, "s": 31407, "text": "On Create Only" }, { "code": null, "e": 31436, "s": 31422, "text": "On Every Save" }, { "code": null, "e": 31450, "s": 31436, "text": "On Every Save" }, { "code": null, "e": 31460, "s": 31450, "text": "Scheduled" }, { "code": null, "e": 31470, "s": 31460, "text": "Scheduled" }, { "code": null, "e": 31554, "s": 31470, "text": "When timing is left blank, the default On Every Save will be automatically applied." }, { "code": null, "e": 31797, "s": 31554, "text": "Using Catalog management, organizations can distribute product content in specific catalogs to target specific audience. Catalog defines a way to segment stored products for efficient and effective management and to target specific audiences." }, { "code": null, "e": 32009, "s": 31797, "text": "A Product Catalog is defined as part of content segment to provide the details of product categories and product information in the store. SAP Hybris Platform includes two types of catalogs: Product and Content." }, { "code": null, "e": 32284, "s": 32009, "text": "A content catalog refers to pages of website where the distribution of product is done. In simple terms, a catalog is defined as the container of products. Following are the key advantages that can be achieved using the Catalog and the Content Management feature of Hybris −" }, { "code": null, "e": 32433, "s": 32284, "text": "With the use of Catalog management, companies can achieve improved marketing effectiveness by managing, structuring, and displaying product content." }, { "code": null, "e": 32582, "s": 32433, "text": "With the use of Catalog management, companies can achieve improved marketing effectiveness by managing, structuring, and displaying product content." }, { "code": null, "e": 32729, "s": 32582, "text": "With the use of catalog, an organization can import product content from different sources, organizing it hierarchically and assigning attributes." }, { "code": null, "e": 32876, "s": 32729, "text": "With the use of catalog, an organization can import product content from different sources, organizing it hierarchically and assigning attributes." }, { "code": null, "e": 32993, "s": 32876, "text": "With the use of Catalog management, companies can drive sales by distributing product content to specific audiences." }, { "code": null, "e": 33110, "s": 32993, "text": "With the use of Catalog management, companies can drive sales by distributing product content to specific audiences." }, { "code": null, "e": 33443, "s": 33110, "text": "In the following image, you can see Catalog management where products are divided into specific categories. With the use of the Catalog Module, companies can manage structuring of products and product information. On the right hand side, you can see the Product attributes that specify properties of products in the Product Catalog." }, { "code": null, "e": 33767, "s": 33443, "text": "All the products available in the commerce site has images and these are called media. To add any product to a commerce site, we have to create media with that image. Media can be created using different tools like HMC or via Impex. To create media in the Hybris system, you can login to the Hybris Management Console (HMC)" }, { "code": null, "e": 33837, "s": 33767, "text": "Login to the Hybris Management Console – enter username and password." }, { "code": null, "e": 33909, "s": 33837, "text": "Navigate to the Multimedia tab on the right hand side → Create → Media." }, { "code": null, "e": 33985, "s": 33909, "text": "This will open a new window and you have to provide the following details −" }, { "code": null, "e": 34076, "s": 33985, "text": "Unique Identifier − In this field, you have to enter the unique identifier for your media." }, { "code": null, "e": 34406, "s": 34076, "text": "Catalog Versions − In this field, you have to enter the catalog version, which means if you use this media for a product, enter the catalog version of the product as the media catalog version. Note that if you do not mention the catalog version of media same as the catalog version of product, media is not linked to the product." }, { "code": null, "e": 34649, "s": 34406, "text": "Media format − This is an identifier for a media dimension. You can see the existing standard formats in the drop down or you can also create your own format. If you upload an image of 40*40, but use the higher media format, it still accepts." }, { "code": null, "e": 34693, "s": 34649, "text": "The following media formats are available −" }, { "code": null, "e": 34885, "s": 34693, "text": "To upload an image for media, navigate to the Upload button and provide the path of the product image file by clicking on the Choose File option. Click on the Upload button to load the image." }, { "code": null, "e": 34993, "s": 34885, "text": "Once the image is uploaded, few of the properties like URL, real file name, etc., would come automatically." }, { "code": null, "e": 35095, "s": 34993, "text": "To save new media, you can click on save item button at the top as shown in the following screenshot." }, { "code": null, "e": 35275, "s": 35095, "text": "Now, if you want to search for media that you have just created, you can use different filter options under Search. You can also select checkbox for Subtypes in the Search option." }, { "code": null, "e": 35340, "s": 35275, "text": "The following Search Criteria are shown in the following image −" }, { "code": null, "e": 35351, "s": 35340, "text": "Identifier" }, { "code": null, "e": 35361, "s": 35351, "text": "Mime Type" }, { "code": null, "e": 35368, "s": 35361, "text": "Folder" }, { "code": null, "e": 35384, "s": 35368, "text": "Catalog Version" }, { "code": null, "e": 35586, "s": 35384, "text": "Once you click on the Search button, all items matching the search criteria are shown under the Results tab. All the information that you have entered for the media is shown along with the media image." }, { "code": null, "e": 35923, "s": 35586, "text": "SAP Hybris Web content management module is used for the management of content across multiple channels like Online, Mobile and other user interfaces. Companies require good presentation of their products across all channels by using an integrated content management solution provided by SAP Hybris WCMS (Web Content Management System)." }, { "code": null, "e": 35993, "s": 35923, "text": "The following benefits can be achieved by using the SAP Hybris WCMS −" }, { "code": null, "e": 36061, "s": 35993, "text": "Less integration cost by using single solution for Sales, PCM, etc." }, { "code": null, "e": 36129, "s": 36061, "text": "Less integration cost by using single solution for Sales, PCM, etc." }, { "code": null, "e": 36201, "s": 36129, "text": "Using WCMS, it supports easy creation of high quality product websites." }, { "code": null, "e": 36273, "s": 36201, "text": "Using WCMS, it supports easy creation of high quality product websites." }, { "code": null, "e": 36332, "s": 36273, "text": "Integrating and managing user generated content with ease." }, { "code": null, "e": 36391, "s": 36332, "text": "Integrating and managing user generated content with ease." }, { "code": null, "e": 36563, "s": 36391, "text": "Web Content Management System provides an easy to use and consistent management of desktop and mobile websites by providing entire content from a single multimedia source." }, { "code": null, "e": 36735, "s": 36563, "text": "Web Content Management System provides an easy to use and consistent management of desktop and mobile websites by providing entire content from a single multimedia source." }, { "code": null, "e": 36850, "s": 36735, "text": "Less time for implementation using WCMS as only the page is required to develop and maintain for all device types." }, { "code": null, "e": 36965, "s": 36850, "text": "Less time for implementation using WCMS as only the page is required to develop and maintain for all device types." }, { "code": null, "e": 37050, "s": 36965, "text": "With use of WCMS system, you can make the content available across all the channels." }, { "code": null, "e": 37135, "s": 37050, "text": "With use of WCMS system, you can make the content available across all the channels." }, { "code": null, "e": 37202, "s": 37135, "text": "Managing complex formats such as Images, Texts, HTML, Videos, etc." }, { "code": null, "e": 37269, "s": 37202, "text": "Managing complex formats such as Images, Texts, HTML, Videos, etc." }, { "code": null, "e": 37320, "s": 37269, "text": "Dynamic user restriction based on the user groups." }, { "code": null, "e": 37371, "s": 37320, "text": "Dynamic user restriction based on the user groups." }, { "code": null, "e": 37445, "s": 37371, "text": "WCMS provides ready to use components built on JQuery, Bootstrap and OWL." }, { "code": null, "e": 37519, "s": 37445, "text": "WCMS provides ready to use components built on JQuery, Bootstrap and OWL." }, { "code": null, "e": 37770, "s": 37519, "text": "WCMS provides an easy to use Web Content Management System Cockpit. By using this WCMS Cockpit, users can easily manage their website pages. It provides an Interactive Graphical User Interface based interface for data management for all the channels." }, { "code": null, "e": 37841, "s": 37770, "text": "You have to enter the URL and it is normally in the following format −" }, { "code": null, "e": 37885, "s": 37841, "text": "http://servername:9001/cmscockpit/login.zul" }, { "code": null, "e": 38014, "s": 37885, "text": "The WCMS Cockpit also provides support for workflow and synchronization tasks. The following screenshot shows the WCMS Cockpit −" }, { "code": null, "e": 38062, "s": 38014, "text": "The WCMS Cockpit contains the following areas −" }, { "code": null, "e": 38078, "s": 38062, "text": "Navigation Area" }, { "code": null, "e": 38091, "s": 38078, "text": "Browser Area" }, { "code": null, "e": 38104, "s": 38091, "text": "Cockpit Area" }, { "code": null, "e": 38148, "s": 38104, "text": "Let us now discuss each of these in detail." }, { "code": null, "e": 38277, "s": 38148, "text": "On the left hand side, you have the navigation pane, where you can navigate to Shortcuts, Queries, Websites and the History tab." }, { "code": null, "e": 38427, "s": 38277, "text": "In the center, you have the Browser area, which is used to manage web content for all the channels. You can add Top Header, Bottom Header and Footer." }, { "code": null, "e": 38561, "s": 38427, "text": "On the right hand side, you have the Cockpit area. The following options are available under the Cockpit area in the Basic Category −" }, { "code": null, "e": 38566, "s": 38561, "text": "Name" }, { "code": null, "e": 38577, "s": 38566, "text": "Page title" }, { "code": null, "e": 38591, "s": 38577, "text": "Page Template" }, { "code": null, "e": 38607, "s": 38591, "text": "Catalog Version" }, { "code": null, "e": 38613, "s": 38607, "text": "Label" }, { "code": null, "e": 38627, "s": 38613, "text": "Homepage, etc" }, { "code": null, "e": 38770, "s": 38627, "text": "Similarly, you have Context viability, Navigation, URL and Administrator tab in the cockpit area, which can be used to manage the web content." }, { "code": null, "e": 39004, "s": 38770, "text": "Using SAP Hybris, companies can provide an exceptional experience to customers when they buy from them. With SAP Hybris Commerce Cloud, organizations can meet the expectations and deliver great experiences that wins customer loyalty." }, { "code": null, "e": 39352, "s": 39004, "text": "SAP Hybris Commerce Management Module contains built-in-Omni-channel versatility and Hybris cloud platform engage that can transact with the customers any time using any device. SAP Hybris Commerce Cloud can help companies to understand its customer throughout the e-Commerce process and helps them to drive meaningful interactions with customers." }, { "code": null, "e": 39637, "s": 39352, "text": "SAP Hybris Commerce management approach cuts down on complexity and allowing companies to spend less time on managing systems and focus on responding to rapidly changing the market conditions. The following capabilities are provided as a part of SAP Hybris Commerce Management module." }, { "code": null, "e": 39682, "s": 39637, "text": "Let us discuss these capabilities in detail." }, { "code": null, "e": 40090, "s": 39682, "text": "Strengthen customer loyalty and increase sales with consistent, personal experiences for your customers. SAP Hybris Commerce Cloud for B2C gives your customers what they want, when they want it, every time they interact with your business – online or in the real world. With every interaction, you can gain further customer insights, so when they come back you are ready to deliver another great experience." }, { "code": null, "e": 40373, "s": 40090, "text": "Create an Omni-channel B2B experience to rival the best consumer sites. The flexibility and functionality of SAP Hybris Commerce Cloud for B2B can give your customers the freedom to save repeat purchases; buy in bulk, while providing self-service, and account management for buyers." }, { "code": null, "e": 40727, "s": 40373, "text": "Consolidate product content and control information about your products with a built-in, easy-to-use system that works across all channels. Wherever they are in their journey, give your customers rich, engaging content including video, images and editorial content that really show off your products – including those syndicated from multiple suppliers." }, { "code": null, "e": 41024, "s": 40727, "text": "One system takes care of your customers’ orders across all channels. They get a fast, secure experience that allows them to choose between collection and delivery, and benefit from fuss-free returns. You get to see all the order information in one place and have precise visibility of your stock." }, { "code": null, "e": 41448, "s": 41024, "text": "Get customers engaged with your products by creating a one-to-one experience that is relevant every time. With SAP Hybris Customer Experience, you can manage site layout and content across all channels and create highly personalized experiences for your customers. Use our modern merchandising tool as well as historical data and current behaviors to deliver the personal storefront that drives engagement and transactions." }, { "code": null, "e": 41908, "s": 41448, "text": "SAP Hybris Commerce Search is a powerful option in Hybris cloud to increase sales and profile for companies. If a company provides poorly organized search results, usability problems and results in loss of sales. Using Commerce search, companies can easily promote their products and product categories by driving from the Commerce Search Results. This in turn improves the customer’s shopping experience and hence improves the margin and sales for companies." }, { "code": null, "e": 42017, "s": 41908, "text": "SAP Hybris also provides keyword suggestion options to help users to easily search and spell their products." }, { "code": null, "e": 42128, "s": 42017, "text": "If a user wrongly spells a product, it also provides spell check to enter the right word in the search option." }, { "code": null, "e": 42251, "s": 42128, "text": "SAP Hybris Search capability provides a free-text search option to locate a specific product and showing relevant results." }, { "code": null, "e": 42374, "s": 42251, "text": "SAP Hybris Search capability provides a free-text search option to locate a specific product and showing relevant results." }, { "code": null, "e": 42496, "s": 42374, "text": "SAP Hybris also provides a feature in the Search Capability like – Synonyms and Stop Words to improve the search results." }, { "code": null, "e": 42618, "s": 42496, "text": "SAP Hybris also provides a feature in the Search Capability like – Synonyms and Stop Words to improve the search results." }, { "code": null, "e": 42762, "s": 42618, "text": "SAP Hybris Commerce feature provides a parametric search that displays the closest match, if there is no exact match found for customer inputs." }, { "code": null, "e": 42906, "s": 42762, "text": "SAP Hybris Commerce feature provides a parametric search that displays the closest match, if there is no exact match found for customer inputs." }, { "code": null, "e": 42994, "s": 42906, "text": "SAP Hybris supports advanced search features like Collapsing, Geospatial Search, etc. ." }, { "code": null, "e": 43082, "s": 42994, "text": "SAP Hybris supports advanced search features like Collapsing, Geospatial Search, etc. ." }, { "code": null, "e": 43190, "s": 43082, "text": "SAP Hybris also supports update of search results with automatic updates through real-time synchronization." }, { "code": null, "e": 43298, "s": 43190, "text": "SAP Hybris also supports update of search results with automatic updates through real-time synchronization." }, { "code": null, "e": 43486, "s": 43298, "text": "In the following screenshot, you can see how SAP Hybris helps the customer with amazing search capabilities and helps the customer to explore content of a website with fewer mouse clicks." }, { "code": null, "e": 43785, "s": 43486, "text": "With the use of advanced personalization module of SAP Hybris, companies can offer the right product to the right customers at the right time. This helps companies to raise their conversion rate. According to a survey, more than 50% of customers receive wrong products when they do shopping online." }, { "code": null, "e": 44034, "s": 43785, "text": "With the use of Hybris Advance Personalization module, companies can collect customer information from different sources and provide customers with an amazing customized/personalized shopping experience, which results in increased sales and profit." }, { "code": null, "e": 44230, "s": 44034, "text": "The SAP Hybris Advance Personalization is a part of the WCMS (Web Content Management System). Advanced Personalization is achieved using the BTG rules. Following are the four types of BTG rules −" }, { "code": null, "e": 44242, "s": 44230, "text": "Order Rules" }, { "code": null, "e": 44253, "s": 44242, "text": "Cart Rules" }, { "code": null, "e": 44268, "s": 44253, "text": "Customer Rules" }, { "code": null, "e": 44282, "s": 44268, "text": "Website Rules" }, { "code": null, "e": 44384, "s": 44282, "text": "The following personalization experience can be considered using SAP Hybris Advance Personalization −" }, { "code": null, "e": 44768, "s": 44384, "text": "Example 1 − Let us assume that a consumer browses a product on a multi-channel ecommerce website and adds products worth $2000 to the Cart. Now, consider a personalization scenario, where the customer gets a message, if the shopping cart value is greater than 1800$, then he can spend additional 300$ with no cost. This is one of the example of advance personalization in E-Commerce." }, { "code": null, "e": 45005, "s": 44768, "text": "Exampl 2 − Another Personalization scenario is, when a customer selected a product on an e-commerce website and a pop-up message appears showing product accessories that can be added to the shopping cart along with the selected product." }, { "code": null, "e": 45161, "s": 45005, "text": "Exampl 3 − Personalization example is where a customer logged into his account and a particular product line has been displayed to him on the arrival page." }, { "code": null, "e": 45367, "s": 45161, "text": "Exampl 4 − Another Personalization example is where a customer has browsed a site from his/her laptop and E-Commerce site identifies customer IP address and displays a particular site page to the customer." }, { "code": null, "e": 45555, "s": 45367, "text": "The following illustration shows a good example of SAP Hybris Personalization Module. It shows the buying history of the customer and the Top Recommendations with that particular product." }, { "code": null, "e": 45669, "s": 45555, "text": "The following image shows how Targeting rules are created and how information is captured from different sources." }, { "code": null, "e": 45767, "s": 45669, "text": "Targeting the rules in an Advance Personalization scenario can include the following rule types −" }, { "code": null, "e": 45940, "s": 45767, "text": "You can use different types of rules as per the different scenarios based on the order details, card type and other personalized data, which is available for the customers." }, { "code": null, "e": 46113, "s": 45940, "text": "You can use different types of rules as per the different scenarios based on the order details, card type and other personalized data, which is available for the customers." }, { "code": null, "e": 46202, "s": 46113, "text": "Advanced Personalization provides flexible individual rules to meet different scenarios." }, { "code": null, "e": 46291, "s": 46202, "text": "Advanced Personalization provides flexible individual rules to meet different scenarios." }, { "code": null, "e": 46414, "s": 46291, "text": "Hybris Advance Personalization module provides an easy way to integrate custom rule types with Hybris e-Commerce platform." }, { "code": null, "e": 46537, "s": 46414, "text": "Hybris Advance Personalization module provides an easy way to integrate custom rule types with Hybris e-Commerce platform." }, { "code": null, "e": 46788, "s": 46537, "text": "In today’s market, it is required that companies provide the customers with an easy to pay options, when their order is ready. If the payment method is complex in nature, the customers will not come back and companies can lose their potential buyers." }, { "code": null, "e": 46968, "s": 46788, "text": "The SAP Hybris Payment Module provides an easy to use and integrated payment method of their choice to the customers. Following are the key features of the Hybris Payment Module −" }, { "code": null, "e": 47048, "s": 46968, "text": "Remove payment complexity and allow the customers to connect to multiple PSP’s." }, { "code": null, "e": 47128, "s": 47048, "text": "Remove payment complexity and allow the customers to connect to multiple PSP’s." }, { "code": null, "e": 47229, "s": 47128, "text": "It provides the customers with multiple payment options and easy integration into the Hybris system." }, { "code": null, "e": 47330, "s": 47229, "text": "It provides the customers with multiple payment options and easy integration into the Hybris system." }, { "code": null, "e": 47430, "s": 47330, "text": "Provides a secure payment gateway between e-Commerce site, customer and payment processing channel." }, { "code": null, "e": 47530, "s": 47430, "text": "Provides a secure payment gateway between e-Commerce site, customer and payment processing channel." }, { "code": null, "e": 47582, "s": 47530, "text": "Centralized processing of all the payment channels." }, { "code": null, "e": 47634, "s": 47582, "text": "Centralized processing of all the payment channels." }, { "code": null, "e": 48079, "s": 47634, "text": "Using the SAP Hybris Payment Module, you can create PSP adapters to integrate external Payment systems into the Hybris E-Commerce platform. The Hybris Payment Module allows the customer to connect to any payment method and to use its features and capabilities. Using the Payment Module, customers can use any secure payment transfers to place orders on e-commerce websites like Credit Cards – Visa and Master cards and other card types as well." }, { "code": null, "e": 48247, "s": 48079, "text": "By using a Payment Service Provider that is an embedded feature provided by the Hybris System, users can make payment without redirecting to external payment gateways." }, { "code": null, "e": 48340, "s": 48247, "text": "Following are the key benefits that can be achieved by using the SAP Hybris Payment Module −" }, { "code": null, "e": 48530, "s": 48340, "text": "Hybris PSP’s allows customers to make payments easily, hence making the payment process much simpler and reducing the cost by allowing connection to commonly used Payment Service Providers." }, { "code": null, "e": 48720, "s": 48530, "text": "Hybris PSP’s allows customers to make payments easily, hence making the payment process much simpler and reducing the cost by allowing connection to commonly used Payment Service Providers." }, { "code": null, "e": 48876, "s": 48720, "text": "By using flexible payment options, the payment process is simplified and the customer can select from the payment method that best suits their requirement." }, { "code": null, "e": 49032, "s": 48876, "text": "By using flexible payment options, the payment process is simplified and the customer can select from the payment method that best suits their requirement." }, { "code": null, "e": 49249, "s": 49032, "text": "Using the Hybris Payment Module, customers can immediately authenticate payments using the payment validation method on the website. Payments are more secure and it does not involve any redirection to external PSP’s." }, { "code": null, "e": 49466, "s": 49249, "text": "Using the Hybris Payment Module, customers can immediately authenticate payments using the payment validation method on the website. Payments are more secure and it does not involve any redirection to external PSP’s." }, { "code": null, "e": 49571, "s": 49466, "text": "Hybris Payment Module provides a centralized mechanism for the payment processing for multiple channels." }, { "code": null, "e": 49676, "s": 49571, "text": "Hybris Payment Module provides a centralized mechanism for the payment processing for multiple channels." }, { "code": null, "e": 49807, "s": 49676, "text": "By using the centralized single payment system, e-commerce websites can increase their sales and hence their net profit is higher." }, { "code": null, "e": 49938, "s": 49807, "text": "By using the centralized single payment system, e-commerce websites can increase their sales and hence their net profit is higher." }, { "code": null, "e": 50096, "s": 49938, "text": "In the following screenshot, you can see an example of an integrated Hybris Payment Module, where the payment is made using a Payment Service Provider (PSP)." }, { "code": null, "e": 50453, "s": 50096, "text": "The SAP Hybris Promotion Module is used to increase sales and to integrate with online stores to win new customers. By using this module, business users can create new flexible, dynamic promotions without needing any expertise. This promotion module provides various predefined promotion templates and promotion rule builders to define a set of conditions." }, { "code": null, "e": 50523, "s": 50453, "text": "Following are the key components of the SAP Hybris Promotion Module −" }, { "code": null, "e": 50543, "s": 50523, "text": "Promotion Templates" }, { "code": null, "e": 50566, "s": 50543, "text": "Promotion Rule Builder" }, { "code": null, "e": 50581, "s": 50566, "text": "Priority Order" }, { "code": null, "e": 50611, "s": 50581, "text": "Promotion Contextual Messages" }, { "code": null, "e": 50650, "s": 50611, "text": "Coupon codes generation and management" }, { "code": null, "e": 50690, "s": 50650, "text": "Let us discuss each of these in detail." }, { "code": null, "e": 50991, "s": 50690, "text": "The Hybris Promotion Module provides inbuilt different promotion templates that can be used by an organization to boost their sale. Promotion modules comes with customizable sample promotions, which cover the most common promotion requirements that are suitable for B2C and B2B e-commerce businesses." }, { "code": null, "e": 51177, "s": 50991, "text": "Using the Promotion Rule Builder, business users can apply a different set of conditions and actions. This can be used to create different complex promotions as per different scenarios." }, { "code": null, "e": 51469, "s": 51177, "text": "In the above image, you can see a graphical user interface of the Promotion Rule Builder. In the central pane, business users can drag different conditions and define actions for each condition. On the right hand side, you can see the available conditions to be added to the Promotion rules." }, { "code": null, "e": 51712, "s": 51469, "text": "This option can be used to define order of execution for different promotion rules. When multiple promotions are applied on the same set of product, business users can use priority builder to define order in which promotions will be executed." }, { "code": null, "e": 51946, "s": 51712, "text": "The SAP Hybris Promotion Module provides contextual messages to customers that can be configured to display messages to the customer – like products qualified as per the promotion rules and corresponding actions for those promotions." }, { "code": null, "e": 52170, "s": 51946, "text": "With the use of SAP Hybris Promotion Module, business users can generate auto-generated or manual coupon. By using the Promotion Builder, these coupons can be distributed to customers for redemption in different promotions." }, { "code": null, "e": 52482, "s": 52170, "text": "SAP Hybris Subscription module is developed to integrate with subscription billing system and hence provides improved customer acquisition rate and less operational overhead. The SAP Hybris Subscription module was built to provide subscription based support for different pricing and product related promotions." }, { "code": null, "e": 52709, "s": 52482, "text": "By using the SAP Hybris Subscription module for e-commerce, business users can setup and manage subscription terms and conditions in the backend UI. While creating a subscription plan, users can opt from the following fields −" }, { "code": null, "e": 52743, "s": 52709, "text": "Subscription Terms and Conditions" }, { "code": null, "e": 52768, "s": 52743, "text": "Subscription Price Plans" }, { "code": null, "e": 52790, "s": 52768, "text": "Included Entitlements" }, { "code": null, "e": 53192, "s": 52790, "text": "The subscription terms and conditions allows the customers to select from different terms that are available for the customer. Customers can select subscription terms like – 12 months contract monthly billing, 24 months contract yearly billing, lifetime subscription plan, etc. Subscription Price plans provide customers with options to select from different plan types – Premium, Platinum, Gold, etc." }, { "code": null, "e": 53416, "s": 53192, "text": "Included Entitlement option is used to mention all the services that the customer will avail as a part of the selected price plan. It includes services like – Access to Print Edition, Weekly Blogs, Monthly Newsletters, etc." }, { "code": null, "e": 53565, "s": 53416, "text": "Business users can also check Subscription plan details by going to the Edit Subscription Price Plan option. It tells about the following features −" }, { "code": null, "e": 53583, "s": 53565, "text": "Price Plan Status" }, { "code": null, "e": 53589, "s": 53583, "text": "Basic" }, { "code": null, "e": 53628, "s": 53589, "text": "Charges-Recurring/One time/Usage based" }, { "code": null, "e": 53651, "s": 53628, "text": "Subscription Type, etc" }, { "code": null, "e": 53778, "s": 53651, "text": "In the following illustration, you can see the above options that are available under the Edit Subscription Price Plan option." }, { "code": null, "e": 53849, "s": 53778, "text": "Following are the key advantages of the SAP Hybris Subscription plan −" }, { "code": null, "e": 53948, "s": 53849, "text": "Customers are provided with personalized pricing based on their profile with e-commerce companies." }, { "code": null, "e": 54047, "s": 53948, "text": "Customers are provided with personalized pricing based on their profile with e-commerce companies." }, { "code": null, "e": 54179, "s": 54047, "text": "Customers can opt for a combination of different subscription plans – one time or recurring or usage based as per their requirement" }, { "code": null, "e": 54311, "s": 54179, "text": "Customers can opt for a combination of different subscription plans – one time or recurring or usage based as per their requirement" }, { "code": null, "e": 54418, "s": 54311, "text": "Different Price Plans are supported based on customer requirements – Premium, Platinum, Gold Package, etc." }, { "code": null, "e": 54525, "s": 54418, "text": "Different Price Plans are supported based on customer requirements – Premium, Platinum, Gold Package, etc." }, { "code": null, "e": 54690, "s": 54525, "text": "Using the Subscription Billing Gateway, complex bundle of subscription charges can be processed for enrolled customers easily, by the use of secure payment methods." }, { "code": null, "e": 54855, "s": 54690, "text": "Using the Subscription Billing Gateway, complex bundle of subscription charges can be processed for enrolled customers easily, by the use of secure payment methods." }, { "code": null, "e": 54942, "s": 54855, "text": "Support integration with third party billing systems using subscription based billing." }, { "code": null, "e": 55029, "s": 54942, "text": "Support integration with third party billing systems using subscription based billing." }, { "code": null, "e": 55121, "s": 55029, "text": "In the next chapter, we will discuss regarding the order management overview in SAP Hybris." }, { "code": null, "e": 55464, "s": 55121, "text": "When customers log into an e-commerce site, it is expected to provide quick delivery, easy returns and other flexible options, while placing an order. The SAP Hybris Order Management module provides an easy way to e-commerce companies that allow customers to build, view and return orders using a centralized system with complete flexibility." }, { "code": null, "e": 55630, "s": 55464, "text": "With SAP Hybris Order Management module, customers experience an exceptional ordering experience, flexible pickup and order fulfillment options for all the channels." }, { "code": null, "e": 55691, "s": 55630, "text": "https://www.hybris.com/en/products/commerce/order-management" }, { "code": null, "e": 55785, "s": 55691, "text": "The SAP Hybris product site covers the following features under the Order Management Module −" }, { "code": null, "e": 55905, "s": 55785, "text": "Customers can choose to collect their purchases in store or have them delivered, with the same flexibility for returns." }, { "code": null, "e": 56025, "s": 55905, "text": "Customers can choose to collect their purchases in store or have them delivered, with the same flexibility for returns." }, { "code": null, "e": 56127, "s": 56025, "text": "Shows stock availability across all channels in real time, so the customers will not be disappointed." }, { "code": null, "e": 56229, "s": 56127, "text": "Shows stock availability across all channels in real time, so the customers will not be disappointed." }, { "code": null, "e": 56325, "s": 56229, "text": "An intuitive user interface makes it easy for business users to manage the fulfillment process." }, { "code": null, "e": 56421, "s": 56325, "text": "An intuitive user interface makes it easy for business users to manage the fulfillment process." }, { "code": null, "e": 56536, "s": 56421, "text": "Gain a single view of inventory across your entire organization and optimize stock, sourcing and allocation rules." }, { "code": null, "e": 56651, "s": 56536, "text": "Gain a single view of inventory across your entire organization and optimize stock, sourcing and allocation rules." }, { "code": null, "e": 57097, "s": 56651, "text": "SAP Hybris Order Management module helps an organization to streamline your order processes across all the channels. E-commerce companies can fetch all the details related to demand, inventory and order supply using a single interface. Hybris Order Management cockpit is one of the key features under the Hybris Order Management module that helps organizations to manage stocks easily using one interface each of inventory and supply management." }, { "code": null, "e": 57241, "s": 57097, "text": "The following screenshot describes the Order Management cockpit that provides all the details related to Orders, Inventory, Supply and Imports." }, { "code": null, "e": 57430, "s": 57241, "text": "Different search options are available under each category, where users can search for all the orders – for Delivery, pickup or list of all orders available in the Order Management System." }, { "code": null, "e": 57547, "s": 57430, "text": "Business users can select any of the order in the search list and check further details in Order Management cockpit." }, { "code": null, "e": 57925, "s": 57547, "text": "SAP Hybris Commerce Order Management service solution allows a company to streamline their order process across all channels. We have already covered all the key points related to Hybris Order Management service in the previous chapter. Using Hybris Order Management Service solution, companies can view demand, inventory and supply globally using the Order Management cockpit." }, { "code": null, "e": 58289, "s": 57925, "text": "The SAP Hybris Customer Service module provides an easy way to resolve customer problems quickly and deliver highly personalized customer service with improved customer satisfaction and increased revenue. When a customer logs to an e-commerce website and gets a weak customer service, it can result customers moving to other websites without completing the order." }, { "code": null, "e": 58555, "s": 58289, "text": "To the retail customers, the company should provide an efficient service including call centers, chat, email and even web-enabled customer self-service. These customer service points should share correct information quickly and resolve customer queries on priority." }, { "code": null, "e": 59145, "s": 58555, "text": "SAP Hybris Customer Service module provides Customer Service Agents with an easier and quicker access to information that they can use to resolve customer queries. A CSA module can also be used by agents to place a new order, modify previously placed orders, placing partial orders, make payment, cancel payment, raise return requests and even to process order refunds for customers. The CSA (customer service associate) module also assists the customers by providing an option to the CSA to manage customer profiles and their personal information in their account for e-commerce shopping." }, { "code": null, "e": 59227, "s": 59145, "text": "The Customer Service module provides the following information to the customers −" }, { "code": null, "e": 59244, "s": 59227, "text": "Personal Details" }, { "code": null, "e": 59260, "s": 59244, "text": "Customer Orders" }, { "code": null, "e": 59279, "s": 59260, "text": "Customer Addresses" }, { "code": null, "e": 59528, "s": 59279, "text": "It is also possible to customize the Hybris Customer Service Module as per the business requirements and hence can change the Customer Service Experience to successful Sales platform, which results in increased revenue for the e-commerce companies." }, { "code": null, "e": 59841, "s": 59528, "text": "The following screenshot describes the cart management that a CSA can provide to the customers as a part of the Customer Service module. They can perform search as per the customer requirements, add products to the shopping cart and see all the promotions and the offers that a customer can see in their account." }, { "code": null, "e": 59929, "s": 59841, "text": "Following are the key features covered using SAP Hybris Customer Service Module (CSM) −" }, { "code": null, "e": 60089, "s": 59929, "text": "Using SAP Hybris module, CSA’s can perform search for customers, can edit customer profiles and their personal information like DOB, Age, Current Address, etc." }, { "code": null, "e": 60227, "s": 60089, "text": "A CSA module provides simple UI based application to create payment for customer and manage other details related to the customer orders." }, { "code": null, "e": 60326, "s": 60227, "text": "The system identifies the customer’s phone number and directs the CSA to the Customer Detail page." }, { "code": null, "e": 60481, "s": 60326, "text": "By using the SAP Hybris Customer Service Module, it is also possible to integrate chat service with the e-commerce website for better customer management." }, { "code": null, "e": 60523, "s": 60481, "text": "Self-service has the following features −" }, { "code": null, "e": 60595, "s": 60523, "text": "The SAP Hybris CSA module allows customers to check their order status." }, { "code": null, "e": 60667, "s": 60595, "text": "The SAP Hybris CSA module allows customers to check their order status." }, { "code": null, "e": 60740, "s": 60667, "text": "Customers can raise queries with CSA’s and manage their queries as well." }, { "code": null, "e": 60813, "s": 60740, "text": "Customers can raise queries with CSA’s and manage their queries as well." }, { "code": null, "e": 60906, "s": 60813, "text": "Better customer experience by providing features like payment refund, edit or cancel orders." }, { "code": null, "e": 60999, "s": 60906, "text": "Better customer experience by providing features like payment refund, edit or cancel orders." }, { "code": null, "e": 61081, "s": 60999, "text": "Let us understand the assisted services module of SAP Hybris in the next chapter." }, { "code": null, "e": 61331, "s": 61081, "text": "SAP Hybris Assisted Services Module (ASM) assists the customer during the buying process using the same storefront across the Omni-channel. The Hybris ASM module connects the customer with customer support and assists them in completing their order." }, { "code": null, "e": 61532, "s": 61331, "text": "The ASM acts as an interface between SAP Hybris Commerce, SAP CRM and SAP Hybris C4C Solution and hence allowing Customer Support Agents to pick customer’s online storefronts from CRM or C4C solution." }, { "code": null, "e": 61841, "s": 61532, "text": "Using the ASM module, tickets are synchronized between SAP Hybris Commerce and SAP Cloud for Customer solution. Hence, it provides an easy resolution of all the tickets. The SAP ASM also provides Customer Support Agents to take over the session from the customers to provide real time assistance and support." }, { "code": null, "e": 61920, "s": 61841, "text": "The following benefits can be achieved using the SAP Assisted Service module −" }, { "code": null, "e": 62002, "s": 61920, "text": "The CSA agents can easily search for a customer’s account and session to support." }, { "code": null, "e": 62084, "s": 62002, "text": "The CSA agents can easily search for a customer’s account and session to support." }, { "code": null, "e": 62147, "s": 62084, "text": "The support agents can assign any cart to any of the customer." }, { "code": null, "e": 62210, "s": 62147, "text": "The support agents can assign any cart to any of the customer." }, { "code": null, "e": 62301, "s": 62210, "text": "Support agents can also create a new customer account for any customer on his/her request." }, { "code": null, "e": 62392, "s": 62301, "text": "Support agents can also create a new customer account for any customer on his/her request." }, { "code": null, "e": 62520, "s": 62392, "text": "Extended sale support for customers by providing assistance to add products to customer shopping carts, completing orders, etc." }, { "code": null, "e": 62648, "s": 62520, "text": "Extended sale support for customers by providing assistance to add products to customer shopping carts, completing orders, etc." }, { "code": null, "e": 62722, "s": 62648, "text": "In the next chapter, we will discuss the role of marketing in SAP Hybris." }, { "code": null, "e": 63025, "s": 62722, "text": "SAP Hybris Marketing is one of the key modules of Hybris product suite, which targets enrolling customers on e-commerce websites by creating dynamic profiles and by providing real time exceptional shopping experience. This results in an increase in the conversion rate and gains the customer’s loyalty." }, { "code": null, "e": 63246, "s": 63025, "text": "Hybris Marketing provides an individualized, contextual marketing experience to the customers. Contextual Marketing is a personalized marketing scenario, which involves the following three types of customer information −" }, { "code": null, "e": 63292, "s": 63246, "text": "Past Interactions and Historical Transactions" }, { "code": null, "e": 63313, "s": 63292, "text": "Predictive Analytics" }, { "code": null, "e": 63331, "s": 63313, "text": "In-moment context" }, { "code": null, "e": 63548, "s": 63331, "text": "The SAP Hybris Marketing Cloud brings together tools that allow you to understand and engage with your customers in real time and on all channels like never before. Hybris Marketing contains following nine products −" }, { "code": null, "e": 63578, "s": 63548, "text": "Hybris Marketing Segmentation" }, { "code": null, "e": 63611, "s": 63578, "text": "Hybris Marketing Data Management" }, { "code": null, "e": 63643, "s": 63611, "text": "Hybris Marketing Recommendation" }, { "code": null, "e": 63668, "s": 63643, "text": "Hybris Marketing Convert" }, { "code": null, "e": 63697, "s": 63668, "text": "Hybris Marketing Acquisition" }, { "code": null, "e": 63722, "s": 63697, "text": "Hybris Marketing Loyalty" }, { "code": null, "e": 63748, "s": 63722, "text": "Hybris Marketing Planning" }, { "code": null, "e": 63779, "s": 63748, "text": "Hybris Marketing Orchestration" }, { "code": null, "e": 63805, "s": 63779, "text": "Hybris Marketing Insights" }, { "code": null, "e": 64111, "s": 63805, "text": "As per a recent report by Gartner (www.gartner.com) – SAP Hybris has been positioned as a leader in the 2017 Gartner for Multichannel Campaign Management Magic Quadrant Report. SAP Hybris Marketing Cloud suite focuses on customer journey management and execution across marketing and advertising channels." }, { "code": null, "e": 64207, "s": 64111, "text": "Following is the product link on the Hybris site: https://www.hybris.com/en/products/marketing." }, { "code": null, "e": 64351, "s": 64207, "text": "This page also provides a 30-day free trial for SAP Hybris Marketing Cloud. To enroll for the trial version, click on the “Sign up now” option." }, { "code": null, "e": 64608, "s": 64351, "text": "Once you click on the Sign up now option, you will be landing onto the following page. It gives you a brief introduction about SAP Hybris Marketing Cloud. To get started with the FREE TRIAL, click on the yellow \"GET IT\" button and then sign up immediately." }, { "code": null, "e": 64719, "s": 64608, "text": "When you click on the GET IT button, it will open the following login page of SAP Cloud Appliance Library CAL." }, { "code": null, "e": 64842, "s": 64719, "text": "We can now further proceed by using the SAP Partner Id and password and it will open the SAP Hybris Marketing Cloud trial." }, { "code": null, "e": 65140, "s": 64842, "text": "If you want to learn more about SAP Hybris Cloud, you can navigate to the Trial Center option. Once you click on the Trial Center, the following page will open. To access the SAP Marketing Cloud open courses or to access Startup guides on Marketing, we need to navigate to the SAP Learning Corner." }, { "code": null, "e": 65351, "s": 65140, "text": "SAP Hybris Billing provides flexible different options to the customer for automating the invoice process. SAP Hybris Billing provides an automated way of managing billing and ordering processes from the cloud." }, { "code": null, "e": 65440, "s": 65351, "text": "Following are the key features covered under the SAP Hybris Billing/Revenue capability −" }, { "code": null, "e": 65480, "s": 65440, "text": "Order and Contract Lifecycle Management" }, { "code": null, "e": 65507, "s": 65480, "text": "Quote to cash capabilities" }, { "code": null, "e": 65549, "s": 65507, "text": "Managing Revenue/Billing for subscription" }, { "code": null, "e": 65620, "s": 65549, "text": "Easy integration of Revenue with Sales, service and Marketing solution" }, { "code": null, "e": 65640, "s": 65620, "text": "Order Orchestration" }, { "code": null, "e": 65686, "s": 65640, "text": "SAP Hybris Leading Edge public cloud platform" }, { "code": null, "e": 65806, "s": 65686, "text": "Following is the link to the SAP Hybris Revenue product site −\nhttps://www.hybris.com/en/products/billing/revenue-cloud" }, { "code": null, "e": 65868, "s": 65806, "text": "Following are the key features of SAP Hybris Billing module −" }, { "code": null, "e": 65978, "s": 65868, "text": "SAP Hybris Billing provides a combination of multiple billing streams and allows to bill to a single invoice." }, { "code": null, "e": 66088, "s": 65978, "text": "SAP Hybris Billing provides a combination of multiple billing streams and allows to bill to a single invoice." }, { "code": null, "e": 66165, "s": 66088, "text": "SAP Hybris Billing allows revenue sharing agreements for different channels." }, { "code": null, "e": 66242, "s": 66165, "text": "SAP Hybris Billing allows revenue sharing agreements for different channels." }, { "code": null, "e": 66346, "s": 66242, "text": "SAP Hybris Billing provides subscription billing for different charge types like one time or recurring." }, { "code": null, "e": 66450, "s": 66346, "text": "SAP Hybris Billing provides subscription billing for different charge types like one time or recurring." }, { "code": null, "e": 66573, "s": 66450, "text": "SAP Hybris Billing includes support for complex discounting including invoice level discount and customer level discounts." }, { "code": null, "e": 66696, "s": 66573, "text": "SAP Hybris Billing includes support for complex discounting including invoice level discount and customer level discounts." }, { "code": null, "e": 66755, "s": 66696, "text": "Hybris Billing supports full revenue management practices." }, { "code": null, "e": 66814, "s": 66755, "text": "Hybris Billing supports full revenue management practices." }, { "code": null, "e": 66947, "s": 66814, "text": "In the following screenshot, you can see the subscription based billing for SAP Hybris Billing module and payment type is recurring." }, { "code": null, "e": 67144, "s": 66947, "text": "SAP Cloud for customer (C4C) is a cloud solution to manage Customer Sales, Customer Service and Marketing Activities efficiently and is one of the key SAP Solution to Manage Customer Relationship." }, { "code": null, "e": 67200, "s": 67144, "text": "SAP C4C is based on the following individual products −" }, { "code": null, "e": 67220, "s": 67200, "text": "SAP Cloud for Sales" }, { "code": null, "e": 67244, "s": 67220, "text": "SAP Cloud for Marketing" }, { "code": null, "e": 67276, "s": 67244, "text": "SAP Cloud for Social Engagement" }, { "code": null, "e": 67298, "s": 67276, "text": "SAP Cloud for Service" }, { "code": null, "e": 67359, "s": 67298, "text": "Following are the key objectives of SAP Cloud for Customer −" }, { "code": null, "e": 67373, "s": 67359, "text": "Relationships" }, { "code": null, "e": 67387, "s": 67373, "text": "Collaboration" }, { "code": null, "e": 67395, "s": 67387, "text": "Insight" }, { "code": null, "e": 67414, "s": 67395, "text": "Business Processes" }, { "code": null, "e": 67467, "s": 67414, "text": "Following are some interesting facts about SAP C4C −" }, { "code": null, "e": 67532, "s": 67467, "text": "SAP Cloud for Customer solution is available from June 20, 2011." }, { "code": null, "e": 67597, "s": 67532, "text": "SAP Cloud for Customer solution is available from June 20, 2011." }, { "code": null, "e": 67650, "s": 67597, "text": "SAP C4C is available in 19 languages as on May 2015." }, { "code": null, "e": 67703, "s": 67650, "text": "SAP C4C is available in 19 languages as on May 2015." }, { "code": null, "e": 67860, "s": 67703, "text": "You can easily integrate C4C solution to SAP ECC, CRM and Outlook using SAP NW Process Integration or SAP HANA Cloud Integration HCI for standard scenarios." }, { "code": null, "e": 68017, "s": 67860, "text": "You can easily integrate C4C solution to SAP ECC, CRM and Outlook using SAP NW Process Integration or SAP HANA Cloud Integration HCI for standard scenarios." }, { "code": null, "e": 68157, "s": 68017, "text": "SAP C4C is a new product of SAP based on SaaS (software as a service), PaaS (Platform as a service) and IaaS (Infrastructure as a service)." }, { "code": null, "e": 68297, "s": 68157, "text": "SAP C4C is a new product of SAP based on SaaS (software as a service), PaaS (Platform as a service) and IaaS (Infrastructure as a service)." }, { "code": null, "e": 68448, "s": 68297, "text": "SAP C4C connecters are available for popular middleware like Dell Boomi for Cloud Integration, Informatica, MuleSoft for Application Integration, etc." }, { "code": null, "e": 68599, "s": 68448, "text": "SAP C4C connecters are available for popular middleware like Dell Boomi for Cloud Integration, Informatica, MuleSoft for Application Integration, etc." }, { "code": null, "e": 68709, "s": 68599, "text": "The following illustration describes the key differences between Cloud for Customer and on premise solution −" }, { "code": null, "e": 68807, "s": 68709, "text": "In SAP Hybris C4C, a sales cycle consists of all key activities under the Sales process such as −" }, { "code": null, "e": 68819, "s": 68807, "text": "Sales Order" }, { "code": null, "e": 68832, "s": 68819, "text": "Sales Quotes" }, { "code": null, "e": 68843, "s": 68832, "text": "Sales Lead" }, { "code": null, "e": 68895, "s": 68843, "text": "Let us first understand how to create Sales Quotes." }, { "code": null, "e": 69163, "s": 68895, "text": "Sales quotes are used to offer products to the customers as per specific terms and fixed conditions. A sales quote bounds the seller to sell products for a specific period of time and price. Sales agents are responsible for the creation of a sales quote in a company." }, { "code": null, "e": 69227, "s": 69163, "text": "We should follow the steps given below to create a sales quote." }, { "code": null, "e": 69286, "s": 69227, "text": "Step 1 − Navigate to the Sales work center → Sales Quotes." }, { "code": null, "e": 69410, "s": 69286, "text": "Step 2 − Click New to enter account/customer data for creating sales quotes. Once you enter all the details, click on Save." }, { "code": null, "e": 69548, "s": 69410, "text": "Step 3 − In the next window, under the Products tab, click Add. You can add the product that you are selling to the customer in this tab." }, { "code": null, "e": 69714, "s": 69548, "text": "Step 4 − Go to the Involved Parties tab, you can add all the parties involved to execute the transactions such as – bill to party, ship to party, sold to party, etc." }, { "code": null, "e": 69987, "s": 69714, "text": "Step 5 − Go to the Sales Document. You can get the details of all the sales documents (sales quotes, sales order, etc.) that are related to this sales quote. If your sales quote is created with a reference to some other sales document, you can see the details in this tab." }, { "code": null, "e": 70197, "s": 69987, "text": "Step 6 − Go to the Attachment tab, you can attach any other external documents. Go to the Approval tab, you can see the approval processes like – approval required from senior to process this sales quote, etc." }, { "code": null, "e": 70280, "s": 70197, "text": "You can also see the status here, which can be – pending, approved, rejected, etc." }, { "code": null, "e": 70437, "s": 70280, "text": "Step 7 − Navigate to the Activities tab. Create activities related to the sales representative like create an appointment through phone calls, e-mails, etc." }, { "code": null, "e": 70667, "s": 70437, "text": "Step 8 − Under the Changes tab, click on Go. You can see all the changes made in this sales quote by all the users at different times on these sales quotes. You can get to know what all changes have been made to this sales quote." }, { "code": null, "e": 70969, "s": 70667, "text": "In SAP Hybris Cloud for Customer, service level defines the time when a ticket for a customer must be responded and completed. Service levels help the organizations define objectives for handling customer messages. Using these, you can measure the performance and the quality of your customer service." }, { "code": null, "e": 71304, "s": 70969, "text": "Service levels also help to define new rules as per the ticket category and description whenever a new customer message comes in the C4C system. Using service levels, a system can determine the service level based on those rules and then based on that service level, the initial response and completion due time points are calculated." }, { "code": null, "e": 71368, "s": 71304, "text": "To create a service level, let us follow the steps given below." }, { "code": null, "e": 71445, "s": 71368, "text": "Step 1 − To define Service Levels, go to Administrator → Service and Social." }, { "code": null, "e": 71508, "s": 71445, "text": "Step 2 − Click on Service Level in the next window that opens." }, { "code": null, "e": 71557, "s": 71508, "text": "Step 3 − Click New and select the Service Level." }, { "code": null, "e": 71653, "s": 71557, "text": "Step 4 − Click the General tab. Enter the Service level Name, Service Level ID and Description." }, { "code": null, "e": 71807, "s": 71653, "text": "To create a new service level, you must provide a Service Level Name, and a Service Level ID. You can also provide an optional service level Description." }, { "code": null, "e": 72073, "s": 71807, "text": "Step 5 − Navigate to the next tab Reaction Times. In this section, you define the time when the service agent responds to the ticket. This time depends on the SLAs (Service Level Agreement) signed with the customer and with the ticket priority and type of customer." }, { "code": null, "e": 72278, "s": 72073, "text": "Example − High priority ticket will have low response time or high-end customers have low response time. It means, the ticket related to these customers will respond faster when compared to other tickets." }, { "code": null, "e": 72503, "s": 72278, "text": "To create a milestone, click Add Row and choose the type of milestone. Select Alert When Overdue, if you want the system to send an automatic alert to the responsible person, when the target milestone-time point is exceeded." }, { "code": null, "e": 72725, "s": 72503, "text": "Click on Add Row. Select the milestone as per the business requirement and then click on Alert When Overdue. When you select this option, the system will send an alert to the service agent. Select the required milestones." }, { "code": null, "e": 72953, "s": 72725, "text": "To enter the reaction time for all the milestones, go to Details for milestone → Add Row. Repeat this process for all the above milestones. Select the milestones one by one and then enter the reaction time for these milestones." }, { "code": null, "e": 73209, "s": 72953, "text": "To assign a service to the selected milestone (in the Milestones table) click on Add Row. Choose the Type of Service, the Priority and enter the timer (Net Labor Time) duration. Add a row for all the available priorities for each type of service selected." }, { "code": null, "e": 73365, "s": 73209, "text": "Step 6 − Navigate to Operating Hours tab. Operating hour is the working hour of the service agent, i.e., from what time to what time an agent is available." }, { "code": null, "e": 73661, "s": 73365, "text": "Select the working day calendar. Enter the days of the week of working of a service agent. Click Add Row and then select the checkboxes for the required days of the week. Enter the time ranges. Click on Add Row and enter the start time and the end time of the working hours of the service agent." }, { "code": null, "e": 73940, "s": 73661, "text": "Step 7 − Navigate to the Changes tab. You can see all the changes that you made in the SLA over the time. Select different available criteria and click on the Go button. To display or refresh the change history, specify the required filter criteria and click on the ‘Go’ button." }, { "code": null, "e": 74174, "s": 73940, "text": "Many companies has an On-premise solution that contains master data, customer and product information as well as the pricing data. Details from the SAP ECC system is required when opportunities are won and a sales order is generated." }, { "code": null, "e": 74265, "s": 74174, "text": "Following are the key reasons why an integration is required with SAP ERP and CRM system −" }, { "code": null, "e": 74398, "s": 74265, "text": "To provide an organization level solution for all sales, marketing and service activities including all subsidiaries, sales offices." }, { "code": null, "e": 74531, "s": 74398, "text": "To provide an organization level solution for all sales, marketing and service activities including all subsidiaries, sales offices." }, { "code": null, "e": 74738, "s": 74531, "text": "Many companies prefer a SAP Cloud solution for customer user experience that helps sales representatives to provide outstanding customer experience and SAP CRM as a backend system to support key activities." }, { "code": null, "e": 74945, "s": 74738, "text": "Many companies prefer a SAP Cloud solution for customer user experience that helps sales representatives to provide outstanding customer experience and SAP CRM as a backend system to support key activities." }, { "code": null, "e": 75017, "s": 74945, "text": "An organization wants to extend the existing CRM platform to new users." }, { "code": null, "e": 75089, "s": 75017, "text": "An organization wants to extend the existing CRM platform to new users." }, { "code": null, "e": 75234, "s": 75089, "text": "The SAP CRM system is up and running smoothly, but the company wants to switch over to cloud solution for managing new deployments and releases." }, { "code": null, "e": 75379, "s": 75234, "text": "The SAP CRM system is up and running smoothly, but the company wants to switch over to cloud solution for managing new deployments and releases." }, { "code": null, "e": 75452, "s": 75379, "text": "To replace the existing cloud SFA solutions with SAP Cloud for Customer." }, { "code": null, "e": 75525, "s": 75452, "text": "To replace the existing cloud SFA solutions with SAP Cloud for Customer." }, { "code": null, "e": 75656, "s": 75525, "text": "SAP provides standard integration scenarios for integration with SAP ERP and SAP CRM. Integration with ERP and CRM is very common." }, { "code": null, "e": 75787, "s": 75656, "text": "SAP provides standard integration scenarios for integration with SAP ERP and SAP CRM. Integration with ERP and CRM is very common." }, { "code": null, "e": 75865, "s": 75787, "text": "Two common integration scenarios that are prepacked with cloud solution are −" }, { "code": null, "e": 75898, "s": 75865, "text": "SAP NetWeaver Process Integrator" }, { "code": null, "e": 75929, "s": 75898, "text": "SAP HANA Cloud Integration HCI" }, { "code": null, "e": 76228, "s": 75929, "text": "SAP HANA Cloud Integration is SAP’s Cloud middleware that can be used for Integration. It is a cloud option of the customers, who do not currently have an integration middleware. The integration middleware enables the customization of the integration as well as design of new integration scenarios." }, { "code": null, "e": 76334, "s": 76228, "text": "To create a communication system in SAP Hybris Cloud for customers, let us follow the steps given below −" }, { "code": null, "e": 76412, "s": 76334, "text": "Step 1 − Navigate to Administration work center → Communication System → New." }, { "code": null, "e": 76661, "s": 76412, "text": "Step 2 − Enter ID, system access type and system Instance ID. Enter other fields as per the requirement. Select SAP Business Suit, if you are creating communication system for integrating SAP on the premise system (SAP ECC or SAP CRM) with SAP C4C." }, { "code": null, "e": 76883, "s": 76661, "text": "Enter Business System Id, IDOC logical Systems Id, SAP Client, Preferred application protocol. These are On-premise data. Therefore, we need to get this information from the On-premise system to enter here. Click on Save." }, { "code": null, "e": 76965, "s": 76883, "text": "Step 3 − The next step is to enter the details in the Communication Arrangements." }, { "code": null, "e": 77038, "s": 76965, "text": "Step 4 − Click on the ‘New’ button as shown in the following screenshot." }, { "code": null, "e": 77298, "s": 77038, "text": "Step 5 − A new window “New Communication Arrangement” will open. You need to select the communication scenario from the list as per the requirement. You have to select an account, as you want to replicate accounts from the On-premise system to SAP C4C system." }, { "code": null, "e": 77606, "s": 77298, "text": "Under the Select Scenarios tab, select the communications scenario for which you want to create a communication arrangement and then click on Next. Based on the communication scenario you selected, the system presets the fields in the next steps with default values. You can change the values, if necessary." }, { "code": null, "e": 77904, "s": 77606, "text": "Step 6 − Under Define Business Data tab, select System Instance ID. Click Value selection. If you have selected a B2B scenario, enter the ID of the business partner and select the associated Identification type. Select the communication system that we have created from the list and click on Next." }, { "code": null, "e": 78090, "s": 77904, "text": "Step 7 − In the Define Technical Data step, define the technical settings for inbound and outbound communication. Enter the application method and Authentication Method → click on Next." }, { "code": null, "e": 78232, "s": 78090, "text": "Step 8 − In the Review step, review the data you entered in the previous steps. To ensure that all data is correct, click Check Completeness." }, { "code": null, "e": 78416, "s": 78232, "text": "To create and activate your communication arrangement in the system, click on Finish. You can also save an inactive version of the communication arrangement by clicking Save as Draft." }, { "code": null, "e": 78533, "s": 78416, "text": "You can also create a new communication scenario by going to the Administrator work center → Communication Scenario." }, { "code": null, "e": 78694, "s": 78533, "text": "As a part of the SAP C4C, there are various activities, which you need to perform under project implementation. We will discuss some of the key activities here." }, { "code": null, "e": 78916, "s": 78694, "text": "The first step in implementation is preparing the system. This includes creating system administrator for implementation, scoping of C4C system, defining migration strategies for data from On-premise to Cloud System, etc." }, { "code": null, "e": 79204, "s": 78916, "text": "As per the scope of project, fine-tuning involves performing customization in SAP ECC On-premise system to perform configuration and setup your customizing as per the project scope. It includes creating users and business roles, defining organization structure and management rules, etc." }, { "code": null, "e": 79445, "s": 79204, "text": "Data Migration and Integration includes performing manual data migration by using the default templates based cloud system. In case of integration being in scope, then perform initial data load from On-premise source system to cloud system." }, { "code": null, "e": 79510, "s": 79445, "text": "In the Test phase, you perform Unit, Regression, Data test, etc." }, { "code": null, "e": 79744, "s": 79510, "text": "Go Live work center includes activities like user enablement. SAP C4C administrator is enabled who takes care of the day-to-day operation and supports activities before it goes live. Once this is done, you can set the system to Live." }, { "code": null, "e": 79810, "s": 79744, "text": "To implement a project in SAP C4C, follow the steps given below −" }, { "code": null, "e": 79886, "s": 79810, "text": "Step 1 − Go to Business Configuration work center → Implementation Project." }, { "code": null, "e": 80040, "s": 79886, "text": "Step 2 − Click the New tab to start implementing a new project. As a project already exists, click Edit Project Scope to see the steps in implementation." }, { "code": null, "e": 80262, "s": 80040, "text": "The Cloud Application Studio is a cloud based Software Development Kit (SDK) that allows SAP customers to enhance the features of SAP Cloud Solutions – SAP Hybris Cloud for Customer and SAP Business by Design application." }, { "code": null, "e": 80443, "s": 80262, "text": "The SAP Cloud Application Studio is used to extend the underlying SAP Cloud solution to meet customer specific requirements, legal requirements or industry specific best practices." }, { "code": null, "e": 80521, "s": 80443, "text": "Following are the key features provided by the SAP Cloud Application Studio −" }, { "code": null, "e": 80562, "s": 80521, "text": "Integrated Development Environment (IDE)" }, { "code": null, "e": 80587, "s": 80562, "text": "UI Designer for new UI’s" }, { "code": null, "e": 80600, "s": 80587, "text": "Web Services" }, { "code": null, "e": 80614, "s": 80600, "text": "Extensibility" }, { "code": null, "e": 80642, "s": 80614, "text": "Integrated Add on lifecycle" }, { "code": null, "e": 80667, "s": 80642, "text": "SAP Store Publish option" }, { "code": null, "e": 80881, "s": 80667, "text": "The Cloud Application Studio is based on a local integrated development environment (IDE), which provides access to all the tools that are required to create or extend the features of SAP Cloud based applications." }, { "code": null, "e": 81005, "s": 80881, "text": "Provides access to all the tools that you need to create and enhance the functionality of the SAP standard cloud solutions." }, { "code": null, "e": 81129, "s": 81005, "text": "Provides access to all the tools that you need to create and enhance the functionality of the SAP standard cloud solutions." }, { "code": null, "e": 81264, "s": 81129, "text": "Using IDE, developers can manage the entire lifecycle of the customer-specific solutions, including development, testing and assembly." }, { "code": null, "e": 81399, "s": 81264, "text": "Using IDE, developers can manage the entire lifecycle of the customer-specific solutions, including development, testing and assembly." }, { "code": null, "e": 81440, "s": 81399, "text": "Easy programming of custom applications." }, { "code": null, "e": 81481, "s": 81440, "text": "Easy programming of custom applications." }, { "code": null, "e": 81572, "s": 81481, "text": "In the next chapter, we will discuss regarding security and user management in SAP Hybris." }, { "code": null, "e": 81807, "s": 81572, "text": "In SAP Hybris C4C, user management deals with maintaining the employee records in a system and creation of users and business roles. As per the business roles, you can assign different access rights and data restrictions to the users." }, { "code": null, "e": 81885, "s": 81807, "text": "To create an employee in the Hybris C4C system, follow the steps given below." }, { "code": null, "e": 81954, "s": 81885, "text": "Step 1 − Open Silverlight UI, go to Administrator → click Employees." }, { "code": null, "e": 81974, "s": 81954, "text": "A new window opens." }, { "code": null, "e": 82031, "s": 81974, "text": "Step 2 − To create a new employee, click New → Employee." }, { "code": null, "e": 82170, "s": 82031, "text": "Step 3 − Enter all the fields in the New Employee page like Name, Gender, Preferred Language, Validity, Organizational Data, Address, etc." }, { "code": null, "e": 82242, "s": 82170, "text": "Step 4 − Click on the Save button as shown in the following screenshot." }, { "code": null, "e": 82275, "s": 82242, "text": "\n 25 Lectures \n 6 hours \n" }, { "code": null, "e": 82289, "s": 82275, "text": " Sanjo Thomas" }, { "code": null, "e": 82322, "s": 82289, "text": "\n 26 Lectures \n 2 hours \n" }, { "code": null, "e": 82334, "s": 82322, "text": " Neha Gupta" }, { "code": null, "e": 82369, "s": 82334, "text": "\n 30 Lectures \n 2.5 hours \n" }, { "code": null, "e": 82384, "s": 82369, "text": " Sumit Agarwal" }, { "code": null, "e": 82417, "s": 82384, "text": "\n 30 Lectures \n 4 hours \n" }, { "code": null, "e": 82432, "s": 82417, "text": " Sumit Agarwal" }, { "code": null, "e": 82467, "s": 82432, "text": "\n 14 Lectures \n 1.5 hours \n" }, { "code": null, "e": 82479, "s": 82467, "text": " Neha Malik" }, { "code": null, "e": 82514, "s": 82479, "text": "\n 13 Lectures \n 1.5 hours \n" }, { "code": null, "e": 82526, "s": 82514, "text": " Neha Malik" }, { "code": null, "e": 82533, "s": 82526, "text": " Print" }, { "code": null, "e": 82544, "s": 82533, "text": " Add Notes" } ]
Find other two sides and angles of a right angle triangle - GeeksforGeeks
03 May, 2021 Given one side of right angle triangle, check if there exists a right angle triangle possible with any other two sides of the triangle. If possible print length of the other two sides and all the angles of the triangle. Examples: Input : a = 12 Output : Sides are a = 12, b = 35, c = 37 Angles are A = 18.9246, B = 71.0754, C = 90 Explanation: a = 12, b = 35 and c = 37 form right angle triangle because 12*12 + 35*35 = 37*37Input : a = 6 Output : Sides are a = 6, b = 8, c = 10 Angles are A = 36.8699, B = 53.1301, C = 90 Approach to check if triangle exists and finding Sides: To solve this problem we first observe the Pythagoras equation. If a and b are the lengths of the legs of a right triangle and c is the length of the hypotenuse, then the sum of the squares of the lengths of the legs is equal to the square of the length of the hypotenuse. This relationship is represented by the formula: a*a + b*b = c*c Case 1: a is an odd number: Given a, find b and c c2 - b2 = a2 OR c = (a2 + 1)/2; b = (a2 - 1)/2; Above solution works only for case when a is odd, because a2 + 1 is divisible by 2 only for odd a.Case 2 : a is an even number: When c-b is 2 & c+b is (a2)/2 c-b = 2 & c+b = (a2)/2 Hence, c = (a2)/4 + 1; b = (a2)/4 - 1; This works when a is even.Approach to find Angles: First find all sides of triangle. Then Applied “SSS” rule that’s means law of cosine: Below is the implementation of the above approach: C++ Java Python 3 C# PHP Javascript // C++ program to print all sides and angles of right// angle triangle given one side#include <bits/stdc++.h>#include <cmath>using namespace std; #define PI 3.1415926535 // Function to find angle A// Angle in front of side adouble findAnglesA(double a, double b, double c){ // applied cosine rule double A = acos((b * b + c * c - a * a) / (2 * b * c)); // convert into degrees return A * 180 / PI;} // Function to find angle B// Angle in front of side bdouble findAnglesB(double a, double b, double c){ // applied cosine rule double B = acos((a * a + c * c - b * b) / (2 * a * c)); // convert into degrees and return return B * 180 / PI;} // Function to print all angles// of the right angled trianglevoid printAngles(int a, int b, int c){ double x = (double)a; double y = (double)b; double z = (double)c; // for calculate angle A double A = findAnglesA(x, y, z); // for calculate angle B double B = findAnglesB(x, y, z); cout << "Angles are A = " << A << ", B = " << B << ", C = " << 90 << endl;} // Function to find other two sides of the// right angled trianglevoid printOtherSides(int n){ int b,c; // if n is odd if (n & 1) { // case of n = 1 handled separately if (n == 1) cout << -1 << endl; else { b = (n*n-1)/2; c = (n*n+1)/2; cout << "Side b = " << b << ", Side c = " << c << endl; } } else { // case of n = 2 handled separately if (n == 2) cout << -1 << endl; else { b = n*n/4-1; c = n*n/4+1; cout << "Side b = " << b << ", Side c = " << c << endl; } } // Print angles of the triangle printAngles(n,b,c);} // Driver Programint main(){ int a = 12; printOtherSides(a); return 0;} // Java program to print all sides and angles of right// angle triangle given one side import java.io.*; class GFG { static double PI = 3.1415926535; // Function to find angle A// Angle in front of side astatic double findAnglesA(double a, double b, double c){ // applied cosine rule double A = Math.acos((b * b + c * c - a * a) / (2 * b * c)); // convert into degrees return A * 180 / PI;} // Function to find angle B// Angle in front of side bstatic double findAnglesB(double a, double b, double c){ // applied cosine rule double B = Math.acos((a * a + c * c - b * b) / (2 * a * c)); // convert into degrees and return return B * 180 / PI;} // Function to print all angles// of the right angled trianglestatic void printAngles(int a, int b, int c){ double x = (double)a; double y = (double)b; double z = (double)c; // for calculate angle A double A = findAnglesA(x, y, z); // for calculate angle B double B = findAnglesB(x, y, z); System.out.println( "Angles are A = " + A + ", B = " + B + ", C = " + 90);} // Function to find other two sides of the// right angled trianglestatic void printOtherSides(int n){ int b=0,c=0; // if n is odd if ((n & 1)>0) { // case of n = 1 handled separately if (n == 1) System.out.println( -1); else { b = (n*n-1)/2; c = (n*n+1)/2; System.out.println( "Side b = " + b + ", Side c = " + c ); } } else { // case of n = 2 handled separately if (n == 2) System.out.println( -1); else { b = n*n/4-1; c = n*n/4+1; System.out.println( "Side b = " + b + ", Side c = " + c); } } // Print angles of the triangle printAngles(n,b,c);} // Driver Program public static void main (String[] args) { int a = 12; printOtherSides(a); }} // This code is contributed// by inder_verma.. # Python 3 program to print all# sides and angles of right# angle triangle given one sideimport math PI = 3.1415926535 # Function to find angle A# Angle in front of side adef findAnglesA( a, b, c): # applied cosine rule A = math.acos((b * b + c * c - a * a) / (2 * b * c)) # convert into degrees return A * 180 / PI # Function to find angle B# Angle in front of side bdef findAnglesB(a, b, c): # applied cosine rule B = math.acos((a * a + c * c - b * b) / (2 * a * c)) # convert into degrees # and return return B * 180 / PI # Function to print all angles# of the right angled triangledef printAngles(a, b, c): x = a y = b z = c # for calculate angle A A = findAnglesA(x, y, z) # for calculate angle B B = findAnglesB(x, y, z) print("Angles are A = ", A, ", B = ", B , ", C = ", "90 ") # Function to find other two sides# of the right angled triangledef printOtherSides(n): # if n is odd if (n & 1) : # case of n = 1 handled # separately if (n == 1): print("-1") else: b = (n * n - 1) // 2 c = (n * n + 1) // 2 print("Side b = ", b, " Side c = ", c) else: # case of n = 2 handled # separately if (n == 2) : print("-1") else: b = n * n // 4 - 1; c = n * n // 4 + 1; print("Side b = " , b, ", Side c = " , c) # Print angles of the triangle printAngles(n, b, c) # Driver Codeif __name__ == "__main__": a = 12 printOtherSides(a) # This code is contributed# by ChitraNayal // C# program to print all sides// and angles of right angle// triangle given one sideusing System; class GFG{static double PI = 3.1415926535; // Function to find angle A// Angle in front of side astatic double findAnglesA(double a, double b, double c){ // applied cosine rule double A = Math.Acos((b * b + c * c - a * a) / (2 * b * c)); // convert into degrees return A * 180 / PI;} // Function to find angle B// Angle in front of side bstatic double findAnglesB(double a, double b, double c){ // applied cosine rule double B = Math.Acos((a * a + c * c - b * b) / (2 * a * c)); // convert into degrees and return return B * 180 / PI;} // Function to print all angles// of the right angled trianglestatic void printAngles(int a, int b, int c){ double x = (double)a; double y = (double)b; double z = (double)c; // for calculate angle A double A = findAnglesA(x, y, z); // for calculate angle B double B = findAnglesB(x, y, z); Console.WriteLine( "Angles are A = " + A + ", B = " + B + ", C = " + 90);} // Function to find other two sides// of the right angled trianglestatic void printOtherSides(int n){ int b = 0, c = 0; // if n is odd if ((n & 1) > 0) { // case of n = 1 handled separately if (n == 1) Console.WriteLine( -1); else { b = (n * n - 1) / 2; c = (n * n + 1) / 2; Console.WriteLine( "Side b = " + b + ", Side c = " + c); } } else { // case of n = 2 handled separately if (n == 2) Console.WriteLine( -1); else { b = n * n / 4 - 1; c = n * n / 4 + 1; Console.WriteLine( "Side b = " + b + ", Side c = " + c); } } // Print angles of the triangle printAngles(n, b, c);} // Driver Codepublic static void Main (){ int a = 12; printOtherSides(a);}} // This code is contributed// by inder_verma <?php// PHP program to print all sides// and angles of right angle triangle// given one side$PI = 3.1415926535; // Function to find angle A// Angle in front of side afunction findAnglesA($a, $b, $c){ global $PI; // applied cosine rule $A = acos(($b * $b + $c * $c - $a * $a) / (2 * $b * $c)); // convert into degrees return $A * 180 / $PI;} // Function to find angle B// Angle in front of side bfunction findAnglesB($a, $b, $c){ global $PI; // applied cosine rule $B = acos(($a * $a + $c * $c - $b * $b) / (2 * $a * $c)); // convert into degrees and return return $B * 180 / $PI;} // Function to print all angles// of the right angled trianglefunction printAngles($a, $b, $c){ $x = (double)$a; $y = (double)$b; $z = (double)$c; // for calculate angle A $A = findAnglesA($x, $y, $z); // for calculate angle B $B = findAnglesB($x, $y, $z); echo "Angles are A = " . $A . ", B = " . $B . ", C = 90\n";} // Function to find other two sides// of the right angled trianglefunction printOtherSides($n){ // if n is odd if ($n & 1) { // case of n = 1 handled separately if ($n == 1) echo "-1\n"; else { $b = ($n * $n - 1) / 2; $c = ($n * $n + 1) / 2; echo "Side b = " . $b . ", Side c = " . $c . "\n"; } } else { // case of n = 2 handled separately if ($n == 2) echo "-1\n"; else { $b = $n * $n / 4 - 1; $c = $n * $n / 4 + 1; echo "Side b = " . $b . ", Side c = " . $c . "\n"; } } // Print angles of the triangle printAngles($n, $b, $c);} // Driver Code$a = 12; printOtherSides($a); // This code is contributed by mits?> <script> // Javascript program to print all sides and angles of right// angle triangle given one side let PI = 3.1415926535; // Function to find angle A// Angle in front of side afunction findAnglesA(a, b, c){ // applied cosine rule let A = Math.acos((b * b + c * c - a * a) / (2 * b * c)); // convert into degrees return A * 180 / PI;} // Function to find angle B// Angle in front of side bfunction findAnglesB(a, b, c){ // applied cosine rule let B = Math.acos((a * a + c * c - b * b) / (2 * a * c)); // convert into degrees and return return B * 180 / PI;} // Function to print all angles// of the right angled trianglefunction printAngles(a, b, c){ let x = a; let y = b; let z = c; // for calculate angle A let A = findAnglesA(x, y, z); // for calculate angle B let B = findAnglesB(x, y, z); document.write( "Angles are A = " + A + ", B = " + B + ", C = " + 90);} // Function to find other two sides of the// right angled trianglefunction printOtherSides(n){ let b=0,c=0; // if n is odd if ((n & 1)>0) { // case of n = 1 handled separately if (n == 1) document.write( -1); else { b = (n*n-1)/2; c = (n*n+1)/2; document.write( "Side b = " + b + ", Side c = " + c ); } } else { // case of n = 2 handled separately if (n == 2) document.write( -1); else { b = n*n/4-1; c = n*n/4+1; document.write( "Side b = " + b + ", Side c = " + c + "<br/>"); } } // Print angles of the triangle printAngles(n,b,c);} // Driver Code let a = 12; printOtherSides(a); </script> Side b = 35, Side c = 37 Angles are A = 18.9246, B = 71.0754, C = 90 inderDuMCA ukasp Mithun Kumar sanjoy_62 math Technical Scripter 2018 triangle Mathematical Technical Scripter Mathematical Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Modulo Operator (%) in C/C++ with Examples Program to find GCD or HCF of two numbers Merge two sorted arrays Prime Numbers Program to find sum of elements in a given array Program for factorial of a number Program for Decimal to Binary Conversion Sieve of Eratosthenes Operators in C / C++ The Knight's tour problem | Backtracking-1
[ { "code": null, "e": 24960, "s": 24932, "text": "\n03 May, 2021" }, { "code": null, "e": 25182, "s": 24960, "text": "Given one side of right angle triangle, check if there exists a right angle triangle possible with any other two sides of the triangle. If possible print length of the other two sides and all the angles of the triangle. " }, { "code": null, "e": 25194, "s": 25182, "text": "Examples: " }, { "code": null, "e": 25489, "s": 25194, "text": "Input : a = 12 Output : Sides are a = 12, b = 35, c = 37 Angles are A = 18.9246, B = 71.0754, C = 90 Explanation: a = 12, b = 35 and c = 37 form right angle triangle because 12*12 + 35*35 = 37*37Input : a = 6 Output : Sides are a = 6, b = 8, c = 10 Angles are A = 36.8699, B = 53.1301, C = 90 " }, { "code": null, "e": 25870, "s": 25491, "text": "Approach to check if triangle exists and finding Sides: To solve this problem we first observe the Pythagoras equation. If a and b are the lengths of the legs of a right triangle and c is the length of the hypotenuse, then the sum of the squares of the lengths of the legs is equal to the square of the length of the hypotenuse. This relationship is represented by the formula: " }, { "code": null, "e": 25886, "s": 25870, "text": "a*a + b*b = c*c" }, { "code": null, "e": 25937, "s": 25886, "text": "Case 1: a is an odd number: Given a, find b and c " }, { "code": null, "e": 25985, "s": 25937, "text": "c2 - b2 = a2\nOR\nc = (a2 + 1)/2;\nb = (a2 - 1)/2;" }, { "code": null, "e": 26144, "s": 25985, "text": "Above solution works only for case when a is odd, because a2 + 1 is divisible by 2 only for odd a.Case 2 : a is an even number: When c-b is 2 & c+b is (a2)/2 " }, { "code": null, "e": 26206, "s": 26144, "text": "c-b = 2 & c+b = (a2)/2\nHence,\nc = (a2)/4 + 1;\nb = (a2)/4 - 1;" }, { "code": null, "e": 26343, "s": 26206, "text": "This works when a is even.Approach to find Angles: First find all sides of triangle. Then Applied “SSS” rule that’s means law of cosine:" }, { "code": null, "e": 26401, "s": 26348, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 26405, "s": 26401, "text": "C++" }, { "code": null, "e": 26410, "s": 26405, "text": "Java" }, { "code": null, "e": 26419, "s": 26410, "text": "Python 3" }, { "code": null, "e": 26422, "s": 26419, "text": "C#" }, { "code": null, "e": 26426, "s": 26422, "text": "PHP" }, { "code": null, "e": 26437, "s": 26426, "text": "Javascript" }, { "code": "// C++ program to print all sides and angles of right// angle triangle given one side#include <bits/stdc++.h>#include <cmath>using namespace std; #define PI 3.1415926535 // Function to find angle A// Angle in front of side adouble findAnglesA(double a, double b, double c){ // applied cosine rule double A = acos((b * b + c * c - a * a) / (2 * b * c)); // convert into degrees return A * 180 / PI;} // Function to find angle B// Angle in front of side bdouble findAnglesB(double a, double b, double c){ // applied cosine rule double B = acos((a * a + c * c - b * b) / (2 * a * c)); // convert into degrees and return return B * 180 / PI;} // Function to print all angles// of the right angled trianglevoid printAngles(int a, int b, int c){ double x = (double)a; double y = (double)b; double z = (double)c; // for calculate angle A double A = findAnglesA(x, y, z); // for calculate angle B double B = findAnglesB(x, y, z); cout << \"Angles are A = \" << A << \", B = \" << B << \", C = \" << 90 << endl;} // Function to find other two sides of the// right angled trianglevoid printOtherSides(int n){ int b,c; // if n is odd if (n & 1) { // case of n = 1 handled separately if (n == 1) cout << -1 << endl; else { b = (n*n-1)/2; c = (n*n+1)/2; cout << \"Side b = \" << b << \", Side c = \" << c << endl; } } else { // case of n = 2 handled separately if (n == 2) cout << -1 << endl; else { b = n*n/4-1; c = n*n/4+1; cout << \"Side b = \" << b << \", Side c = \" << c << endl; } } // Print angles of the triangle printAngles(n,b,c);} // Driver Programint main(){ int a = 12; printOtherSides(a); return 0;}", "e": 28358, "s": 26437, "text": null }, { "code": "// Java program to print all sides and angles of right// angle triangle given one side import java.io.*; class GFG { static double PI = 3.1415926535; // Function to find angle A// Angle in front of side astatic double findAnglesA(double a, double b, double c){ // applied cosine rule double A = Math.acos((b * b + c * c - a * a) / (2 * b * c)); // convert into degrees return A * 180 / PI;} // Function to find angle B// Angle in front of side bstatic double findAnglesB(double a, double b, double c){ // applied cosine rule double B = Math.acos((a * a + c * c - b * b) / (2 * a * c)); // convert into degrees and return return B * 180 / PI;} // Function to print all angles// of the right angled trianglestatic void printAngles(int a, int b, int c){ double x = (double)a; double y = (double)b; double z = (double)c; // for calculate angle A double A = findAnglesA(x, y, z); // for calculate angle B double B = findAnglesB(x, y, z); System.out.println( \"Angles are A = \" + A + \", B = \" + B + \", C = \" + 90);} // Function to find other two sides of the// right angled trianglestatic void printOtherSides(int n){ int b=0,c=0; // if n is odd if ((n & 1)>0) { // case of n = 1 handled separately if (n == 1) System.out.println( -1); else { b = (n*n-1)/2; c = (n*n+1)/2; System.out.println( \"Side b = \" + b + \", Side c = \" + c ); } } else { // case of n = 2 handled separately if (n == 2) System.out.println( -1); else { b = n*n/4-1; c = n*n/4+1; System.out.println( \"Side b = \" + b + \", Side c = \" + c); } } // Print angles of the triangle printAngles(n,b,c);} // Driver Program public static void main (String[] args) { int a = 12; printOtherSides(a); }} // This code is contributed// by inder_verma..", "e": 30392, "s": 28358, "text": null }, { "code": "# Python 3 program to print all# sides and angles of right# angle triangle given one sideimport math PI = 3.1415926535 # Function to find angle A# Angle in front of side adef findAnglesA( a, b, c): # applied cosine rule A = math.acos((b * b + c * c - a * a) / (2 * b * c)) # convert into degrees return A * 180 / PI # Function to find angle B# Angle in front of side bdef findAnglesB(a, b, c): # applied cosine rule B = math.acos((a * a + c * c - b * b) / (2 * a * c)) # convert into degrees # and return return B * 180 / PI # Function to print all angles# of the right angled triangledef printAngles(a, b, c): x = a y = b z = c # for calculate angle A A = findAnglesA(x, y, z) # for calculate angle B B = findAnglesB(x, y, z) print(\"Angles are A = \", A, \", B = \", B , \", C = \", \"90 \") # Function to find other two sides# of the right angled triangledef printOtherSides(n): # if n is odd if (n & 1) : # case of n = 1 handled # separately if (n == 1): print(\"-1\") else: b = (n * n - 1) // 2 c = (n * n + 1) // 2 print(\"Side b = \", b, \" Side c = \", c) else: # case of n = 2 handled # separately if (n == 2) : print(\"-1\") else: b = n * n // 4 - 1; c = n * n // 4 + 1; print(\"Side b = \" , b, \", Side c = \" , c) # Print angles of the triangle printAngles(n, b, c) # Driver Codeif __name__ == \"__main__\": a = 12 printOtherSides(a) # This code is contributed# by ChitraNayal", "e": 32148, "s": 30392, "text": null }, { "code": "// C# program to print all sides// and angles of right angle// triangle given one sideusing System; class GFG{static double PI = 3.1415926535; // Function to find angle A// Angle in front of side astatic double findAnglesA(double a, double b, double c){ // applied cosine rule double A = Math.Acos((b * b + c * c - a * a) / (2 * b * c)); // convert into degrees return A * 180 / PI;} // Function to find angle B// Angle in front of side bstatic double findAnglesB(double a, double b, double c){ // applied cosine rule double B = Math.Acos((a * a + c * c - b * b) / (2 * a * c)); // convert into degrees and return return B * 180 / PI;} // Function to print all angles// of the right angled trianglestatic void printAngles(int a, int b, int c){ double x = (double)a; double y = (double)b; double z = (double)c; // for calculate angle A double A = findAnglesA(x, y, z); // for calculate angle B double B = findAnglesB(x, y, z); Console.WriteLine( \"Angles are A = \" + A + \", B = \" + B + \", C = \" + 90);} // Function to find other two sides// of the right angled trianglestatic void printOtherSides(int n){ int b = 0, c = 0; // if n is odd if ((n & 1) > 0) { // case of n = 1 handled separately if (n == 1) Console.WriteLine( -1); else { b = (n * n - 1) / 2; c = (n * n + 1) / 2; Console.WriteLine( \"Side b = \" + b + \", Side c = \" + c); } } else { // case of n = 2 handled separately if (n == 2) Console.WriteLine( -1); else { b = n * n / 4 - 1; c = n * n / 4 + 1; Console.WriteLine( \"Side b = \" + b + \", Side c = \" + c); } } // Print angles of the triangle printAngles(n, b, c);} // Driver Codepublic static void Main (){ int a = 12; printOtherSides(a);}} // This code is contributed// by inder_verma", "e": 34372, "s": 32148, "text": null }, { "code": "<?php// PHP program to print all sides// and angles of right angle triangle// given one side$PI = 3.1415926535; // Function to find angle A// Angle in front of side afunction findAnglesA($a, $b, $c){ global $PI; // applied cosine rule $A = acos(($b * $b + $c * $c - $a * $a) / (2 * $b * $c)); // convert into degrees return $A * 180 / $PI;} // Function to find angle B// Angle in front of side bfunction findAnglesB($a, $b, $c){ global $PI; // applied cosine rule $B = acos(($a * $a + $c * $c - $b * $b) / (2 * $a * $c)); // convert into degrees and return return $B * 180 / $PI;} // Function to print all angles// of the right angled trianglefunction printAngles($a, $b, $c){ $x = (double)$a; $y = (double)$b; $z = (double)$c; // for calculate angle A $A = findAnglesA($x, $y, $z); // for calculate angle B $B = findAnglesB($x, $y, $z); echo \"Angles are A = \" . $A . \", B = \" . $B . \", C = 90\\n\";} // Function to find other two sides// of the right angled trianglefunction printOtherSides($n){ // if n is odd if ($n & 1) { // case of n = 1 handled separately if ($n == 1) echo \"-1\\n\"; else { $b = ($n * $n - 1) / 2; $c = ($n * $n + 1) / 2; echo \"Side b = \" . $b . \", Side c = \" . $c . \"\\n\"; } } else { // case of n = 2 handled separately if ($n == 2) echo \"-1\\n\"; else { $b = $n * $n / 4 - 1; $c = $n * $n / 4 + 1; echo \"Side b = \" . $b . \", Side c = \" . $c . \"\\n\"; } } // Print angles of the triangle printAngles($n, $b, $c);} // Driver Code$a = 12; printOtherSides($a); // This code is contributed by mits?>", "e": 36222, "s": 34372, "text": null }, { "code": "<script> // Javascript program to print all sides and angles of right// angle triangle given one side let PI = 3.1415926535; // Function to find angle A// Angle in front of side afunction findAnglesA(a, b, c){ // applied cosine rule let A = Math.acos((b * b + c * c - a * a) / (2 * b * c)); // convert into degrees return A * 180 / PI;} // Function to find angle B// Angle in front of side bfunction findAnglesB(a, b, c){ // applied cosine rule let B = Math.acos((a * a + c * c - b * b) / (2 * a * c)); // convert into degrees and return return B * 180 / PI;} // Function to print all angles// of the right angled trianglefunction printAngles(a, b, c){ let x = a; let y = b; let z = c; // for calculate angle A let A = findAnglesA(x, y, z); // for calculate angle B let B = findAnglesB(x, y, z); document.write( \"Angles are A = \" + A + \", B = \" + B + \", C = \" + 90);} // Function to find other two sides of the// right angled trianglefunction printOtherSides(n){ let b=0,c=0; // if n is odd if ((n & 1)>0) { // case of n = 1 handled separately if (n == 1) document.write( -1); else { b = (n*n-1)/2; c = (n*n+1)/2; document.write( \"Side b = \" + b + \", Side c = \" + c ); } } else { // case of n = 2 handled separately if (n == 2) document.write( -1); else { b = n*n/4-1; c = n*n/4+1; document.write( \"Side b = \" + b + \", Side c = \" + c + \"<br/>\"); } } // Print angles of the triangle printAngles(n,b,c);} // Driver Code let a = 12; printOtherSides(a); </script>", "e": 38019, "s": 36222, "text": null }, { "code": null, "e": 38088, "s": 38019, "text": "Side b = 35, Side c = 37\nAngles are A = 18.9246, B = 71.0754, C = 90" }, { "code": null, "e": 38101, "s": 38090, "text": "inderDuMCA" }, { "code": null, "e": 38107, "s": 38101, "text": "ukasp" }, { "code": null, "e": 38120, "s": 38107, "text": "Mithun Kumar" }, { "code": null, "e": 38130, "s": 38120, "text": "sanjoy_62" }, { "code": null, "e": 38135, "s": 38130, "text": "math" }, { "code": null, "e": 38159, "s": 38135, "text": "Technical Scripter 2018" }, { "code": null, "e": 38168, "s": 38159, "text": "triangle" }, { "code": null, "e": 38181, "s": 38168, "text": "Mathematical" }, { "code": null, "e": 38200, "s": 38181, "text": "Technical Scripter" }, { "code": null, "e": 38213, "s": 38200, "text": "Mathematical" }, { "code": null, "e": 38311, "s": 38213, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 38354, "s": 38311, "text": "Modulo Operator (%) in C/C++ with Examples" }, { "code": null, "e": 38396, "s": 38354, "text": "Program to find GCD or HCF of two numbers" }, { "code": null, "e": 38420, "s": 38396, "text": "Merge two sorted arrays" }, { "code": null, "e": 38434, "s": 38420, "text": "Prime Numbers" }, { "code": null, "e": 38483, "s": 38434, "text": "Program to find sum of elements in a given array" }, { "code": null, "e": 38517, "s": 38483, "text": "Program for factorial of a number" }, { "code": null, "e": 38558, "s": 38517, "text": "Program for Decimal to Binary Conversion" }, { "code": null, "e": 38580, "s": 38558, "text": "Sieve of Eratosthenes" }, { "code": null, "e": 38601, "s": 38580, "text": "Operators in C / C++" } ]
Use of Callbacks in Layered Architecture - GeeksforGeeks
05 Feb, 2019 From OSI model of network to Operating System, any daily life project is based on layered architecture. Ever thought how the abstraction between upper layers and lower layers are created? It is all about callbacks. So, in general upper layers are created to make things simpler and easier to use (like SDKs) and lower layers are the actual layers which interact with network (for a networking based project) or system level calls (for OS based projects). So, we can directly call a function, defined (and declared also) in lower layer, from a upper layer source file and pass the data through function arguments. But, we can not just call a function of upper layer from lower layers, as that will create a circular dependency. So, here Callbacks come into picture. Callback is the way of passing a function through it’s reference as argument of another function and calling it later by the reference. Let’s say upperlayer.c and lowerlayer.c are a sourcefiles of upper layer and lower layer respectively. lowerlayer.h is the header file of lowerlayer.c. In the upperlayer.c, first the function reference of notify_observer() is passed to the lowerlayer.c as an argument of register_callback(). This is called registering callback in the lower layer. Now, the lower layer knows about the function reference of notify_observer(). The register_callback() function just stores the function reference into a global function pointer g_notify_ob, so that any function from the file can call notify_observer(). Now, whenever the lower layer needs to pass data to upper layer (or needs to send a notification), it just calls notify_observer() by the calling g_notify_ob(). Below is upperlayer.c #include <stdio.h>#include "lowerlayer.h" void notify_observer(){ printf("Function called by callback\n");} int main(){ // Calling register_callback function and // passing address of notify_observer as argument register_callback(notify_observer); lowerlevelfunction();} This is lowerlayer.h. The highlighted line is just to denote the prototype of the callback function that will be actually passed as reference. The basic template of the prototype is like, typedef <Function return type> (*<Name of the function pointer type>) (<Type of Function arguments separated by comma>) // Below is the prototype of the function // that will be actually passed by reference typedef void (*notify_ob)(void); void register_callback(notify_ob); void lowerlevelfunction(); Now this is lowerlayer.c #include "lowerlayer.h"#define NULL 0 notify_ob g_notify_ob; // Callback functionvoid lowerlevelfunction(){ // Calling back to notify_observer g_notify_ob(); } // Callback registrationvoid register_callback(notify_ob fun){ g_notify_ob = fun;} If we compile and run these files like these, the output will be like this. $gcc -c upperlayer.c $gcc -c lowerlayer.c $gcc -o exe upperlayer.o lowerlayer.o $./exe Output: Function called by callback C-Functions Technical Scripter 2018 Computer Networks Computer Networks Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Advanced Encryption Standard (AES) Block Cipher modes of Operation Intrusion Detection System (IDS) Cryptography and its Types Transport Layer responsibilities GSM in Wireless Communication Multiple Access Protocols in Computer Network Stop and Wait ARQ Active and Passive attacks in Information Security Difference between Distance vector routing and Link State routing
[ { "code": null, "e": 24119, "s": 24091, "text": "\n05 Feb, 2019" }, { "code": null, "e": 24307, "s": 24119, "text": "From OSI model of network to Operating System, any daily life project is based on layered architecture. Ever thought how the abstraction between upper layers and lower layers are created?" }, { "code": null, "e": 24884, "s": 24307, "text": "It is all about callbacks. So, in general upper layers are created to make things simpler and easier to use (like SDKs) and lower layers are the actual layers which interact with network (for a networking based project) or system level calls (for OS based projects). So, we can directly call a function, defined (and declared also) in lower layer, from a upper layer source file and pass the data through function arguments. But, we can not just call a function of upper layer from lower layers, as that will create a circular dependency. So, here Callbacks come into picture." }, { "code": null, "e": 25020, "s": 24884, "text": "Callback is the way of passing a function through it’s reference as argument of another function and calling it later by the reference." }, { "code": null, "e": 25782, "s": 25020, "text": "Let’s say upperlayer.c and lowerlayer.c are a sourcefiles of upper layer and lower layer respectively. lowerlayer.h is the header file of lowerlayer.c. In the upperlayer.c, first the function reference of notify_observer() is passed to the lowerlayer.c as an argument of register_callback(). This is called registering callback in the lower layer. Now, the lower layer knows about the function reference of notify_observer(). The register_callback() function just stores the function reference into a global function pointer g_notify_ob, so that any function from the file can call notify_observer(). Now, whenever the lower layer needs to pass data to upper layer (or needs to send a notification), it just calls notify_observer() by the calling g_notify_ob()." }, { "code": null, "e": 25804, "s": 25782, "text": "Below is upperlayer.c" }, { "code": "#include <stdio.h>#include \"lowerlayer.h\" void notify_observer(){ printf(\"Function called by callback\\n\");} int main(){ // Calling register_callback function and // passing address of notify_observer as argument register_callback(notify_observer); lowerlevelfunction();}", "e": 26095, "s": 25804, "text": null }, { "code": null, "e": 26283, "s": 26095, "text": "This is lowerlayer.h. The highlighted line is just to denote the prototype of the callback function that will be actually passed as reference. The basic template of the prototype is like," }, { "code": null, "e": 26425, "s": 26283, "text": "typedef <Function return type> (*<Name of the function pointer type>)\n (<Type of Function arguments separated by comma>)" }, { "code": "// Below is the prototype of the function // that will be actually passed by reference typedef void (*notify_ob)(void); void register_callback(notify_ob); void lowerlevelfunction();", "e": 26609, "s": 26425, "text": null }, { "code": null, "e": 26634, "s": 26609, "text": "Now this is lowerlayer.c" }, { "code": "#include \"lowerlayer.h\"#define NULL 0 notify_ob g_notify_ob; // Callback functionvoid lowerlevelfunction(){ // Calling back to notify_observer g_notify_ob(); } // Callback registrationvoid register_callback(notify_ob fun){ g_notify_ob = fun;}", "e": 26890, "s": 26634, "text": null }, { "code": null, "e": 26966, "s": 26890, "text": "If we compile and run these files like these, the output will be like this." }, { "code": null, "e": 27091, "s": 26966, "text": "$gcc -c upperlayer.c\n$gcc -c lowerlayer.c\n$gcc -o exe upperlayer.o lowerlayer.o\n$./exe\n\nOutput: Function called by callback " }, { "code": null, "e": 27103, "s": 27091, "text": "C-Functions" }, { "code": null, "e": 27127, "s": 27103, "text": "Technical Scripter 2018" }, { "code": null, "e": 27145, "s": 27127, "text": "Computer Networks" }, { "code": null, "e": 27163, "s": 27145, "text": "Computer Networks" }, { "code": null, "e": 27261, "s": 27163, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27270, "s": 27261, "text": "Comments" }, { "code": null, "e": 27283, "s": 27270, "text": "Old Comments" }, { "code": null, "e": 27318, "s": 27283, "text": "Advanced Encryption Standard (AES)" }, { "code": null, "e": 27350, "s": 27318, "text": "Block Cipher modes of Operation" }, { "code": null, "e": 27383, "s": 27350, "text": "Intrusion Detection System (IDS)" }, { "code": null, "e": 27410, "s": 27383, "text": "Cryptography and its Types" }, { "code": null, "e": 27443, "s": 27410, "text": "Transport Layer responsibilities" }, { "code": null, "e": 27473, "s": 27443, "text": "GSM in Wireless Communication" }, { "code": null, "e": 27519, "s": 27473, "text": "Multiple Access Protocols in Computer Network" }, { "code": null, "e": 27537, "s": 27519, "text": "Stop and Wait ARQ" }, { "code": null, "e": 27588, "s": 27537, "text": "Active and Passive attacks in Information Security" } ]
Concatenate string with numbers in MySQL?
To concatenate string with numbers, use the CONCAT() method. Let us first create a table − mysql> create table DemoTable682( Name varchar(100), Age int ); Query OK, 0 rows affected (0.49 sec) Insert some records in the table using insert command − mysql> insert into DemoTable682 values('John',23); Query OK, 1 row affected (0.12 sec) mysql> insert into DemoTable682 values('Chris',21); Query OK, 1 row affected (0.17 sec) mysql> insert into DemoTable682 values('David',25); Query OK, 1 row affected (0.17 sec) Display all records from the table using select statement: Display all records from the table using select statement - mysql> select *from DemoTable682; This will produce the following output − +-------+------+ | Name | Age | +-------+------+ | John | 23 | | Chris | 21 | | David | 25 | +-------+------+ 3 rows in set (0.00 sec) Following is the query to implement concat() method to concatenate records − mysql> select concat(Name,Age) from DemoTable682; This will produce the following output − +------------------+ | concat(Name,Age) | +------------------+ | John23 | | Chris21 | | David25 | +------------------+ 3 rows in set (0.00 sec)
[ { "code": null, "e": 1153, "s": 1062, "text": "To concatenate string with numbers, use the CONCAT() method. Let us first create a table −" }, { "code": null, "e": 1260, "s": 1153, "text": "mysql> create table DemoTable682(\n Name varchar(100),\n Age int\n);\nQuery OK, 0 rows affected (0.49 sec)" }, { "code": null, "e": 1316, "s": 1260, "text": "Insert some records in the table using insert command −" }, { "code": null, "e": 1638, "s": 1316, "text": "mysql> insert into DemoTable682 values('John',23);\nQuery OK, 1 row affected (0.12 sec)\nmysql> insert into DemoTable682 values('Chris',21);\nQuery OK, 1 row affected (0.17 sec)\nmysql> insert into DemoTable682 values('David',25);\nQuery OK, 1 row affected (0.17 sec)\nDisplay all records from the table using select statement:" }, { "code": null, "e": 1698, "s": 1638, "text": "Display all records from the table using select statement -" }, { "code": null, "e": 1732, "s": 1698, "text": "mysql> select *from DemoTable682;" }, { "code": null, "e": 1773, "s": 1732, "text": "This will produce the following output −" }, { "code": null, "e": 1917, "s": 1773, "text": "+-------+------+\n| Name | Age |\n+-------+------+\n| John | 23 |\n| Chris | 21 |\n| David | 25 |\n+-------+------+\n3 rows in set (0.00 sec)" }, { "code": null, "e": 1994, "s": 1917, "text": "Following is the query to implement concat() method to concatenate records −" }, { "code": null, "e": 2044, "s": 1994, "text": "mysql> select concat(Name,Age) from DemoTable682;" }, { "code": null, "e": 2085, "s": 2044, "text": "This will produce the following output −" }, { "code": null, "e": 2257, "s": 2085, "text": "+------------------+\n| concat(Name,Age) |\n+------------------+\n| John23 |\n| Chris21 |\n| David25 |\n+------------------+\n3 rows in set (0.00 sec)" } ]
Mining and Classifying Medical Documents | by Georgi Tancev | Towards Data Science
In the medical world, a lot of (digital) text documents from several specialities are generated, be it patient health records, letters, or documentation of clinical studies. In fact, text data, which is usually unstructured, contributes to the huge increase of data volume globally — social media alone. Hence, retrieving information from texts becomes a more and more important task. The aim of this post is two-fold: demonstrating methods for text mining and document classification used in natural languague processing (NLP)presenting the development and deployment of an application for automatized text classifier generation in Python using Scikit-Learn and Streamlit. demonstrating methods for text mining and document classification used in natural languague processing (NLP) presenting the development and deployment of an application for automatized text classifier generation in Python using Scikit-Learn and Streamlit. The final product will look like this application with the name Medical Language Model Learner (MLML). (Raw data is available on kaggle.) Natural language processing (NLP) is a subfield of linguistics, computer science, information engineering, and artificial intelligence concerned with the interactions between computers and human (natural) languages, in particular how to program computers to process and analyze large amounts of natural language data. An important consideration is that text consists of strings, but mathematical models rely on numbers, and there are different ways to convert words to numeric vectors. Addtionally, there are different possibilities to model a language — depending on the problem definition. A common task is mapping sequences (e.g. text/speech in some language) from some domain to sequences in another domain (e.g. text/speech in another languague), known as sequence-to-sequence models. For instance, in order to generate speech from text (text-to-speech), recurrent neural networks together with pretrained word embeddings (for example Global Vectors for Word Representation, GloVe) are used. In that case, a word becomes a vector in a n-dimensional space, similar to data points in a space with n principal components. The different dimensions (also known as latent variables) can be thought as properties/attributes that describe the words, e.g. the property “edible” for words like bread, fruit, and apple; words like chair, car, and animal would be found on the opposite direction. Hence, “apple” and “chair” would be farther apart in this dimension, but “apple” and “fruit” much closer. As for the word “animal”, this would be somewhere in the middle, because some animals are eaten. Note that it is generally not possible to extract the meaning of the different latent variables. Due to these embeddings, the dimensionality is reduced compared to a 1-out-of-K encoded approach. For instance, a dictionary with K words has K dimensions in a 1-out-of-K space (every word is a vector orthogonal to all other words), but an embedding can reduce the dimension down to 100, and hence decrease computational complexity. (If K=10.000 and n=100, the compression factor is 100.) Pretrained embeddings can be downloaded and do not have to be constructed first. However, every possible word has to be available in the embedding already — or the embedding has to be trained first. The embeddings are context-free, i.e. the word “bank” is treated similar in expressions like “bank account” or “he sat on a bank”. Alternatively, there is the possibility to ignore the sequential aspect of a language and model a text as a collection of words (bag-of-words approach). This is the most frequent representation in text mining, which is the process of deriving high-quality information from text. To describe a text in this manner, a dictionary is constructed by using the most frequent words or n-grams (raw count or normalized by the total amount of words in a text), but such a dictionary might not very discriminative as every text contains expressions like “a”, “the”, “is”, and so on. To account for this issue, a solution called term frequency-inverse document frequency (tf-idf or TFIDF) was developed; tf-idf is a numerical statistic that is intended to reflect how important a word is to a document in a collection of documents. The tf-idf value increases proportionally to the number of times a word appears in the document and is modified by the number of documents in the corpus that contain the word, which helps to adjust for the fact that some words appear more frequently in general. tf-idf is one of the most popular term-weighting schemes today; 83% of text-based recommender systems in digital libraries use tf–idf. The term frequency (calculated for each document) is usually just the count of a specific word i (e.g. “cervix”) divided by the total amount of words in a text L, hence adjusting for document length. Inverse document frequency is obtained by calculating the inverse fraction of documents (N/ni) which contain the word i and applying a log transformation. Words that occur in almost every document will have a value close to one before the logarithmic transformation, and hence close to zero after logarithmic transformation. The tf-idf is defined for each word i in each document k in a collection of N documents. It is calculated by multiplying tf and idf. This way, a word i that occurs in almost every document k lowers the tf-idf value. For text mining, it does not make sense to keep words in the dictionary with low tf-idf values since they are not discriminative for a specific document class. Imagine a data scientist who wants to build a model that distinguishes between biological and legal documents; what words should (s)he focus on? Ubiquitous words like “is” or “a” do not help at all, but terms like “protein” or “contract” do — these are the interesting ones. If the model should distinguish even further between subclasses of biological documents (higher resolution), it needs to refine the dictionary. For instance, words like “DNA”, “enzyme”, or “pathway” are used more frequently in microbiology than in ecology, whereas the opposite is true for words like “biodiversity”, “habitat”, or “population”. If said higher resolution is desired, bigger dictionaries might be needed. Or, one has to be more selective in which maximum and minimum tf-idf values one wants to include in the dictionary of size D. The result of the tf-idf computation is a matrix with dimensions NxD, i.e. number of documents times dictionary size, filled with tf-idf values that serve as features. Note that this is likely a sparse matrix. Additionally, there are tunable parameters in the matrix construction process, and it is evident that the tf-idf transformation has some influence with respect to the model performance. Scikit-Learn as a built-in transformer for text documents. import pandas as pdfrom sklearn.feature_extraction.text import TfidfVectorizerfrom sklearn.preprocessing import LabelEncoderenc = LabelEncoder()# Load data.data = pd.read_csv("mtsamples.csv", index_col=0, usecols=[0,1,2,4])data = data.dropna()samples = data.transcriptiontext_labels = [label_name.lower() for label_name in data.medical_specialty]labels = enc.fit_transform(np.array(text_labels))# Transform data.max_df = 0.2min_df = 0.001max_features = 1000ngram_range = (1,1)tfidf_vectorizer = TfidfVectorizer(max_df=max_df, min_df=min_df, max_features=max_features, stop_words='english', ngram_range=ngram_range)tfidf = tfidf_vectorizer.fit_transform(samples)feature_names = tfidf_vectorizer.get_feature_names() Since there are several free parameters, Streamlit can be used to build sliders to change the values and try out different combinations manually; this way, many different options can be evaluated quickly. import streamlit as stfrom streamlit.logger import get_logger# Title.st.sidebar.header("Constructing dictonary of words.")# Upper bound for tf-idf value.max_df = st.sidebar.slider("Maximum tf-idf value for a word to be considered.", min_value=0.05, max_value=0.4, value=0.3, step=0.01)# Lower bound for tf-idf value.min_df = st.sidebar.slider("Minimum tf-idf value for a word to be considered.", min_value=0.00, max_value=0.05, value=0.01, step=0.01)# Size of dictionary.max_features = st.sidebar.slider("Size of dictionary.", min_value=100, max_value=1000, value=500, step=100) The final product looks should look like this. One possible application is the classification of medical documents according to their medical speciality. Once the document-word matrix is constructed and the texts are transformed into mathematical representations, they can be visualized using dimensionality reduction methods, e.g. truncated singular value decomposition, and a charting library, e.g. Altair. from sklearn.decomposition import TruncatedSVDimport altair as alt# Dimensionality reduction.dim_red = TruncatedSVD(n_components=2)data_red = dim_red.fit_transform(tfidf)# Plot.scatter = alt.Chart(data_red,title="dimensionality reduction",height=400).mark_circle().encode(x='principal component 1', y='principal component 2', color=alt.Color('class', scale=alt.Scale(scheme='blues')),tooltip=["class"]).interactive()st.altair_chart(scatter) The figure shows the different documents in the space of the two principal components explaining the highest variance in the original tf-idf space. It can already be seen that there is a lot of overlap between the classes — at least with the constructed dictionary — and a low classifier performance is to be expected. The data set contains 40 classes. However, it is not (yet) known how frequent a particular class is in the data set. For example, one can expect classes of low abundance to be misclassified more frequently in a skewed data set, so it might be reasonable to discard or merge rare classes. To build the text model, any algorithm for classification can be used, e.g. a random forest; compared to logistic regression, a random forest has the advantage that it can construct decision boundaries of any shape without basis expansion. To find the best random forest hyperparameters, a grid search can be performed. from sklearn.ensemble import RandomForestClassifier# Number of trees.n_estimators = 1000# Define classifier.forest_clf = RandomForestClassifier(n_estimators=n_estimators, max_depth=None, max_leaf_nodes=None, class_weight='balanced', oob_score=True, n_jobs=-1, random_state=0)# Define grid.parameters = {'max_leaf_nodes':np.linspace(20,35,14,dtype='int')}# Balanced accuracy as performance measure.clf = RandomizedSearchCV(forest_clf, parameters, n_iter=10, cv=3,iid=False, scoring='accuracy',n_jobs=-1)# Train/optimize classifier.classifier = clf.fit(tfidf, labels)# Retrieve optimum.forest = classifier.best_estimator_feature_importances = forest.feature_importances_indices = np.argsort(feature_importances)[::-1] It could be again interesting to tune these hyperparameters manually. (In the current version, there is only a text input container, so one has to convert the strings to integers.) st.sidebar.header("Customizing the model.")n_estimators = st.sidebar.text_input('Number of trees in random forest.', '1000')max_leaf_nodes = st.sidebar.text_input('Maximum number of leaf nodes in a tree.', '25')max_depth = st.sidebar.text_input('Maximum depth of a tree.', '5')class_weight = st.sidebar.selectbox("Class weights for the model.",('balanced','balanced_subsample')) To interpret the model, feature importances obtained from the random forest should be evaluated after training with a bar chart. # Retrieve values.feature_importance = classifier.feature_importances_# Plot.bars = alt.Chart(feature_importance, height=400, title="discriminative power of features").mark_bar(color='steelblue', opacity=0.7).encode(y='features:N', x='feature importance:Q', tooltip="feature importance")st.altair_chart(bars) It can be seen that most importances are of similar magnitude. The overall performance as determined by the out-of-bag score is low (0.41). It is likely that there is too much overlap between the classes, which is supported by the dimensionality reduction. To evaluate the model with respect to precision and recall, F1 score and confusion matrix are computed. from sklearn.metrics import f1_score, confusion_matrix# Retrieve values.y_true = labelsy_pred = classifier.predict(tfidf)# Compute scores.f1_score_ = f1_score(y_true,y_pred,average="weighted")cm = confusion_matrix(y_true,y_pred)# Plot.heat = alt.Chart(source, height=500, title="confusion matrix").mark_rect(opacity=0.7).encode(x='predicted class:N', y='true class:N', color=alt.Color('count:Q', scale=alt.Scale(scheme='blues')), tooltip="count")st.altair_chart(heat) The F1 score is 0.49, so precision and/or recall are low. From the confusion matrix, one can see that the model has difficulties in distinguishing the medical documents. It seems that the used words between the documents are too similar at the moment, i.e. many identical words are used in the different medical specialities — or there are just no patterns to be found. Obviously, the model can now be used for prediction. In that case, a sample has to be provided as input, transformed into tf-idf format, and fed to the classifier, which will then return a probability prediction that this sample belongs to any of the classes. The code inside the app should look something like this: LOGGER = get_logger(__name__)def run(): # code for appif __name__ == "__main__": run() To test it locally, the terminal is opened and rooted to the location with the “app.py” file. Typing the following code start a local testing session. streamlit run app.py To deploy the application on a Cloud provider such as Heroku, an account and git are needed. First, a shell script with file name “setup.sh” and the following content is created. mkdir -p ~/.streamlit/echo "\[general]\n\email = \"email@website.com\"\n\" > ~/.streamlit/credentials.tomlecho "\[server]\n\headless = true\n\enableCORS=false\n\port = $PORT\n\" > ~/.streamlit/config.toml Next, a requirements.txt file is created. Its content should look like this. pandassklearnnumpystreamlitaltair For Heroku, a so-called Procfile with the following line of code has to be written — assuming the app is called “app.py”. Note that the Procfile has no type specification. web: sh setup.sh && streamlit run app.py The app can be deployed in the terminal (here on a Unix/Mac operating system). For this, the shell is rooted to the director with all files. $ cd Documents/Projects/App Next, an app on Heroku has to be created (here named “myapp”). After that, a git repository is initialized in the directory with the “app.py” file. $ git init$ heroku git:remote -a myapp The code is commited to the repository and deployed on Heroku. $ git add .$ git commit -am "make it better"$ git push heroku master Finally, the application should be online.
[ { "code": null, "e": 432, "s": 47, "text": "In the medical world, a lot of (digital) text documents from several specialities are generated, be it patient health records, letters, or documentation of clinical studies. In fact, text data, which is usually unstructured, contributes to the huge increase of data volume globally — social media alone. Hence, retrieving information from texts becomes a more and more important task." }, { "code": null, "e": 466, "s": 432, "text": "The aim of this post is two-fold:" }, { "code": null, "e": 721, "s": 466, "text": "demonstrating methods for text mining and document classification used in natural languague processing (NLP)presenting the development and deployment of an application for automatized text classifier generation in Python using Scikit-Learn and Streamlit." }, { "code": null, "e": 830, "s": 721, "text": "demonstrating methods for text mining and document classification used in natural languague processing (NLP)" }, { "code": null, "e": 977, "s": 830, "text": "presenting the development and deployment of an application for automatized text classifier generation in Python using Scikit-Learn and Streamlit." }, { "code": null, "e": 1115, "s": 977, "text": "The final product will look like this application with the name Medical Language Model Learner (MLML). (Raw data is available on kaggle.)" }, { "code": null, "e": 1433, "s": 1115, "text": "Natural language processing (NLP) is a subfield of linguistics, computer science, information engineering, and artificial intelligence concerned with the interactions between computers and human (natural) languages, in particular how to program computers to process and analyze large amounts of natural language data." }, { "code": null, "e": 2239, "s": 1433, "text": "An important consideration is that text consists of strings, but mathematical models rely on numbers, and there are different ways to convert words to numeric vectors. Addtionally, there are different possibilities to model a language — depending on the problem definition. A common task is mapping sequences (e.g. text/speech in some language) from some domain to sequences in another domain (e.g. text/speech in another languague), known as sequence-to-sequence models. For instance, in order to generate speech from text (text-to-speech), recurrent neural networks together with pretrained word embeddings (for example Global Vectors for Word Representation, GloVe) are used. In that case, a word becomes a vector in a n-dimensional space, similar to data points in a space with n principal components." }, { "code": null, "e": 2805, "s": 2239, "text": "The different dimensions (also known as latent variables) can be thought as properties/attributes that describe the words, e.g. the property “edible” for words like bread, fruit, and apple; words like chair, car, and animal would be found on the opposite direction. Hence, “apple” and “chair” would be farther apart in this dimension, but “apple” and “fruit” much closer. As for the word “animal”, this would be somewhere in the middle, because some animals are eaten. Note that it is generally not possible to extract the meaning of the different latent variables." }, { "code": null, "e": 3194, "s": 2805, "text": "Due to these embeddings, the dimensionality is reduced compared to a 1-out-of-K encoded approach. For instance, a dictionary with K words has K dimensions in a 1-out-of-K space (every word is a vector orthogonal to all other words), but an embedding can reduce the dimension down to 100, and hence decrease computational complexity. (If K=10.000 and n=100, the compression factor is 100.)" }, { "code": null, "e": 3524, "s": 3194, "text": "Pretrained embeddings can be downloaded and do not have to be constructed first. However, every possible word has to be available in the embedding already — or the embedding has to be trained first. The embeddings are context-free, i.e. the word “bank” is treated similar in expressions like “bank account” or “he sat on a bank”." }, { "code": null, "e": 4097, "s": 3524, "text": "Alternatively, there is the possibility to ignore the sequential aspect of a language and model a text as a collection of words (bag-of-words approach). This is the most frequent representation in text mining, which is the process of deriving high-quality information from text. To describe a text in this manner, a dictionary is constructed by using the most frequent words or n-grams (raw count or normalized by the total amount of words in a text), but such a dictionary might not very discriminative as every text contains expressions like “a”, “the”, “is”, and so on." }, { "code": null, "e": 4742, "s": 4097, "text": "To account for this issue, a solution called term frequency-inverse document frequency (tf-idf or TFIDF) was developed; tf-idf is a numerical statistic that is intended to reflect how important a word is to a document in a collection of documents. The tf-idf value increases proportionally to the number of times a word appears in the document and is modified by the number of documents in the corpus that contain the word, which helps to adjust for the fact that some words appear more frequently in general. tf-idf is one of the most popular term-weighting schemes today; 83% of text-based recommender systems in digital libraries use tf–idf." }, { "code": null, "e": 4942, "s": 4742, "text": "The term frequency (calculated for each document) is usually just the count of a specific word i (e.g. “cervix”) divided by the total amount of words in a text L, hence adjusting for document length." }, { "code": null, "e": 5267, "s": 4942, "text": "Inverse document frequency is obtained by calculating the inverse fraction of documents (N/ni) which contain the word i and applying a log transformation. Words that occur in almost every document will have a value close to one before the logarithmic transformation, and hence close to zero after logarithmic transformation." }, { "code": null, "e": 5643, "s": 5267, "text": "The tf-idf is defined for each word i in each document k in a collection of N documents. It is calculated by multiplying tf and idf. This way, a word i that occurs in almost every document k lowers the tf-idf value. For text mining, it does not make sense to keep words in the dictionary with low tf-idf values since they are not discriminative for a specific document class." }, { "code": null, "e": 6464, "s": 5643, "text": "Imagine a data scientist who wants to build a model that distinguishes between biological and legal documents; what words should (s)he focus on? Ubiquitous words like “is” or “a” do not help at all, but terms like “protein” or “contract” do — these are the interesting ones. If the model should distinguish even further between subclasses of biological documents (higher resolution), it needs to refine the dictionary. For instance, words like “DNA”, “enzyme”, or “pathway” are used more frequently in microbiology than in ecology, whereas the opposite is true for words like “biodiversity”, “habitat”, or “population”. If said higher resolution is desired, bigger dictionaries might be needed. Or, one has to be more selective in which maximum and minimum tf-idf values one wants to include in the dictionary of size D." }, { "code": null, "e": 6860, "s": 6464, "text": "The result of the tf-idf computation is a matrix with dimensions NxD, i.e. number of documents times dictionary size, filled with tf-idf values that serve as features. Note that this is likely a sparse matrix. Additionally, there are tunable parameters in the matrix construction process, and it is evident that the tf-idf transformation has some influence with respect to the model performance." }, { "code": null, "e": 6919, "s": 6860, "text": "Scikit-Learn as a built-in transformer for text documents." }, { "code": null, "e": 7634, "s": 6919, "text": "import pandas as pdfrom sklearn.feature_extraction.text import TfidfVectorizerfrom sklearn.preprocessing import LabelEncoderenc = LabelEncoder()# Load data.data = pd.read_csv(\"mtsamples.csv\", index_col=0, usecols=[0,1,2,4])data = data.dropna()samples = data.transcriptiontext_labels = [label_name.lower() for label_name in data.medical_specialty]labels = enc.fit_transform(np.array(text_labels))# Transform data.max_df = 0.2min_df = 0.001max_features = 1000ngram_range = (1,1)tfidf_vectorizer = TfidfVectorizer(max_df=max_df, min_df=min_df, max_features=max_features, stop_words='english', ngram_range=ngram_range)tfidf = tfidf_vectorizer.fit_transform(samples)feature_names = tfidf_vectorizer.get_feature_names()" }, { "code": null, "e": 7839, "s": 7634, "text": "Since there are several free parameters, Streamlit can be used to build sliders to change the values and try out different combinations manually; this way, many different options can be evaluated quickly." }, { "code": null, "e": 8418, "s": 7839, "text": "import streamlit as stfrom streamlit.logger import get_logger# Title.st.sidebar.header(\"Constructing dictonary of words.\")# Upper bound for tf-idf value.max_df = st.sidebar.slider(\"Maximum tf-idf value for a word to be considered.\", min_value=0.05, max_value=0.4, value=0.3, step=0.01)# Lower bound for tf-idf value.min_df = st.sidebar.slider(\"Minimum tf-idf value for a word to be considered.\", min_value=0.00, max_value=0.05, value=0.01, step=0.01)# Size of dictionary.max_features = st.sidebar.slider(\"Size of dictionary.\", min_value=100, max_value=1000, value=500, step=100)" }, { "code": null, "e": 8465, "s": 8418, "text": "The final product looks should look like this." }, { "code": null, "e": 8827, "s": 8465, "text": "One possible application is the classification of medical documents according to their medical speciality. Once the document-word matrix is constructed and the texts are transformed into mathematical representations, they can be visualized using dimensionality reduction methods, e.g. truncated singular value decomposition, and a charting library, e.g. Altair." }, { "code": null, "e": 9268, "s": 8827, "text": "from sklearn.decomposition import TruncatedSVDimport altair as alt# Dimensionality reduction.dim_red = TruncatedSVD(n_components=2)data_red = dim_red.fit_transform(tfidf)# Plot.scatter = alt.Chart(data_red,title=\"dimensionality reduction\",height=400).mark_circle().encode(x='principal component 1', y='principal component 2', color=alt.Color('class', scale=alt.Scale(scheme='blues')),tooltip=[\"class\"]).interactive()st.altair_chart(scatter)" }, { "code": null, "e": 9587, "s": 9268, "text": "The figure shows the different documents in the space of the two principal components explaining the highest variance in the original tf-idf space. It can already be seen that there is a lot of overlap between the classes — at least with the constructed dictionary — and a low classifier performance is to be expected." }, { "code": null, "e": 9875, "s": 9587, "text": "The data set contains 40 classes. However, it is not (yet) known how frequent a particular class is in the data set. For example, one can expect classes of low abundance to be misclassified more frequently in a skewed data set, so it might be reasonable to discard or merge rare classes." }, { "code": null, "e": 10195, "s": 9875, "text": "To build the text model, any algorithm for classification can be used, e.g. a random forest; compared to logistic regression, a random forest has the advantage that it can construct decision boundaries of any shape without basis expansion. To find the best random forest hyperparameters, a grid search can be performed." }, { "code": null, "e": 10911, "s": 10195, "text": "from sklearn.ensemble import RandomForestClassifier# Number of trees.n_estimators = 1000# Define classifier.forest_clf = RandomForestClassifier(n_estimators=n_estimators, max_depth=None, max_leaf_nodes=None, class_weight='balanced', oob_score=True, n_jobs=-1, random_state=0)# Define grid.parameters = {'max_leaf_nodes':np.linspace(20,35,14,dtype='int')}# Balanced accuracy as performance measure.clf = RandomizedSearchCV(forest_clf, parameters, n_iter=10, cv=3,iid=False, scoring='accuracy',n_jobs=-1)# Train/optimize classifier.classifier = clf.fit(tfidf, labels)# Retrieve optimum.forest = classifier.best_estimator_feature_importances = forest.feature_importances_indices = np.argsort(feature_importances)[::-1]" }, { "code": null, "e": 11092, "s": 10911, "text": "It could be again interesting to tune these hyperparameters manually. (In the current version, there is only a text input container, so one has to convert the strings to integers.)" }, { "code": null, "e": 11471, "s": 11092, "text": "st.sidebar.header(\"Customizing the model.\")n_estimators = st.sidebar.text_input('Number of trees in random forest.', '1000')max_leaf_nodes = st.sidebar.text_input('Maximum number of leaf nodes in a tree.', '25')max_depth = st.sidebar.text_input('Maximum depth of a tree.', '5')class_weight = st.sidebar.selectbox(\"Class weights for the model.\",('balanced','balanced_subsample'))" }, { "code": null, "e": 11600, "s": 11471, "text": "To interpret the model, feature importances obtained from the random forest should be evaluated after training with a bar chart." }, { "code": null, "e": 11909, "s": 11600, "text": "# Retrieve values.feature_importance = classifier.feature_importances_# Plot.bars = alt.Chart(feature_importance, height=400, title=\"discriminative power of features\").mark_bar(color='steelblue', opacity=0.7).encode(y='features:N', x='feature importance:Q', tooltip=\"feature importance\")st.altair_chart(bars)" }, { "code": null, "e": 12166, "s": 11909, "text": "It can be seen that most importances are of similar magnitude. The overall performance as determined by the out-of-bag score is low (0.41). It is likely that there is too much overlap between the classes, which is supported by the dimensionality reduction." }, { "code": null, "e": 12270, "s": 12166, "text": "To evaluate the model with respect to precision and recall, F1 score and confusion matrix are computed." }, { "code": null, "e": 12738, "s": 12270, "text": "from sklearn.metrics import f1_score, confusion_matrix# Retrieve values.y_true = labelsy_pred = classifier.predict(tfidf)# Compute scores.f1_score_ = f1_score(y_true,y_pred,average=\"weighted\")cm = confusion_matrix(y_true,y_pred)# Plot.heat = alt.Chart(source, height=500, title=\"confusion matrix\").mark_rect(opacity=0.7).encode(x='predicted class:N', y='true class:N', color=alt.Color('count:Q', scale=alt.Scale(scheme='blues')), tooltip=\"count\")st.altair_chart(heat)" }, { "code": null, "e": 13108, "s": 12738, "text": "The F1 score is 0.49, so precision and/or recall are low. From the confusion matrix, one can see that the model has difficulties in distinguishing the medical documents. It seems that the used words between the documents are too similar at the moment, i.e. many identical words are used in the different medical specialities — or there are just no patterns to be found." }, { "code": null, "e": 13368, "s": 13108, "text": "Obviously, the model can now be used for prediction. In that case, a sample has to be provided as input, transformed into tf-idf format, and fed to the classifier, which will then return a probability prediction that this sample belongs to any of the classes." }, { "code": null, "e": 13425, "s": 13368, "text": "The code inside the app should look something like this:" }, { "code": null, "e": 13517, "s": 13425, "text": "LOGGER = get_logger(__name__)def run(): # code for appif __name__ == \"__main__\": run()" }, { "code": null, "e": 13668, "s": 13517, "text": "To test it locally, the terminal is opened and rooted to the location with the “app.py” file. Typing the following code start a local testing session." }, { "code": null, "e": 13689, "s": 13668, "text": "streamlit run app.py" }, { "code": null, "e": 13868, "s": 13689, "text": "To deploy the application on a Cloud provider such as Heroku, an account and git are needed. First, a shell script with file name “setup.sh” and the following content is created." }, { "code": null, "e": 14073, "s": 13868, "text": "mkdir -p ~/.streamlit/echo \"\\[general]\\n\\email = \\\"email@website.com\\\"\\n\\\" > ~/.streamlit/credentials.tomlecho \"\\[server]\\n\\headless = true\\n\\enableCORS=false\\n\\port = $PORT\\n\\\" > ~/.streamlit/config.toml" }, { "code": null, "e": 14150, "s": 14073, "text": "Next, a requirements.txt file is created. Its content should look like this." }, { "code": null, "e": 14184, "s": 14150, "text": "pandassklearnnumpystreamlitaltair" }, { "code": null, "e": 14356, "s": 14184, "text": "For Heroku, a so-called Procfile with the following line of code has to be written — assuming the app is called “app.py”. Note that the Procfile has no type specification." }, { "code": null, "e": 14397, "s": 14356, "text": "web: sh setup.sh && streamlit run app.py" }, { "code": null, "e": 14538, "s": 14397, "text": "The app can be deployed in the terminal (here on a Unix/Mac operating system). For this, the shell is rooted to the director with all files." }, { "code": null, "e": 14566, "s": 14538, "text": "$ cd Documents/Projects/App" }, { "code": null, "e": 14714, "s": 14566, "text": "Next, an app on Heroku has to be created (here named “myapp”). After that, a git repository is initialized in the directory with the “app.py” file." }, { "code": null, "e": 14753, "s": 14714, "text": "$ git init$ heroku git:remote -a myapp" }, { "code": null, "e": 14816, "s": 14753, "text": "The code is commited to the repository and deployed on Heroku." }, { "code": null, "e": 14885, "s": 14816, "text": "$ git add .$ git commit -am \"make it better\"$ git push heroku master" } ]
Data Scientist vs Software Engineer Salary | Towards Data Science
IntroductionSoftware EngineerData ScientistSummaryReferences Introduction Software Engineer Data Scientist Summary References The goal of this article is to show the differences and similarities between two popular tech roles. This information can be helpful for determining which role you would like to pursue. It can also be interesting to clear up some assumptions between these positions in regards to salary. We will deep dive into the average salary in US dollars by city and skills as well. Disclaimer: Like I have said for the previous articles in this series, this article aims not to compare roles as if one deserves more money or not, but is instead a guide allowing professionals in these two fields to assess against their current or expected salary. Keep in mind that these salary values are more general and no one website can be enough to assess your worth. It is the direction of these values that can be utilized as a tool for you to have when dealing with salary in the future. The role of a software engineer can mean many different things. Some software engineers are strictly back-end, front-end, full-stack, or even machine learning engineers. With that being said, the salary can also be fluctuating quite a bit as well based on a variety of factors. Note: this salary information has been last updated on December 15th, 2021 Here are some of the various seniority levels of software engineers and their respective salaries [3] (rounded): Average Overall Software Engineer → $88k Average Entry-Level Software Engineer → $77k (≤ 1 year) Average Early-Career Software Engineer → $86k (1–4 years) Average Mid-Career Software Engineer → $97k (5–9 years) Average Late-Career Software Engineer → $108k (10–19 years) Do I agree with these numbers? No. I think they are too low, especially the entry-level salary. However, there are certain cities that might have much higher salaries. With that being said, here are some popular cities and some other cities with their respective salary averages for early-career software engineers (avg is 86k): New York, New York → $107,845 Seattle, Washington → $109,061 Austin, Texas → $89,398 Atlanta, Georgia → $84,004 As you can see (and would expect), there is a considerable jump when you update to a specific city. Now, let’s add the most popular skill that can contribute to the highest salary for that city. Below is a breakdown of those same cities from above with certain skills: New York, New York → $135,197 with Apache Hadoop Seattle, Washington → $127,424 with Objective-C Austin, Texas → $121,500 with Microservices Atlanta, Georgia → $109,927 with Cloud Computing The takeaway here is that when you add skills that are not necessarily directly software engineering-focused, you can expect to make more money, according to PayScale. In my personal experience, data scientist salaries can have a pretty big range (we will outline the specifics of the range below). It can depend on a variety of factors, of course, like the number of years of experience you have, the city you live in, or the specific skillset you can employ. With that being said, let’s look into some of these variations of qualifications/characteristics to see how the salary average updates. Note: this salary information has been last updated on December 14th, 2021 Here are some of the various seniority levels of data scientists and their respective salaries [5] (rounded) : Average Overall Data Scientist → $97k Average Entry-Level Data Scientist → $85k (≤ 1 year) Average Early-Career Data Scientist → $96k (1–4 years) Average Mid-Career Data Scientist → $110k (5–9 years) Average Late-Career Data Scientist → $122k (10–19 years) This salary data is gathered from PayScale, and if you would like a more specific estimate, then you can use the salary survey [6]. Do I agree with these numbers? Mostly yes. I believe the numbers should be higher, but again, these are averages, so there can be smaller cities or more rural areas that are not as expensive and those can compose more of the estimates than the cities that cost more. With that being said, here are some popular cities and some other cities with their respective salary averages for early-career data scientists (avg is 96k): New York, New York → $107,092 Seattle, Washington → $111,882 Dallas, Texas → $92,724 Atlanta, Georgia → $92,758 Now, let’s add the most popular skill that can contribute to the highest salary for that city. Below, is a breakdown of those same cities from above with certain skills: New York, New York → $117,186 with Apache Hive Seattle, Washington → $120,533 with Amazon Web Services (AWS) Dallas, Texas → $112,500 with Algorithm Development Atlanta, Georgia → $99,750 with Apache Hadoop To me, the biggest surprise is the Dallas, Texas breakdown of adding the algorithm development skill, from ~92k to ~112k. This jump is pretty big for adding one skill. I am also not sure exactly what this skill means — which, brings me to an important point — be sure to look into all the skills you know, and include them on your resume, because they may provide to be the biggest factor in determining your salary As expected, cities and skills can affect the reported salary for both software engineers and data scientists. However, there were certain skills that contributed to a surprising jump in salary, and those were just the specific cities and skills we looked at. There could be other combinations as well that can be discovered when playing around with this PayScale tool. Here is a salary summary of software engineers and data scientists: * Average Overall Software Engineer → $88k* Average Overall Data Scientist → $97k* Data scientists may have a higher overall salary, but we saw that for the cities we investigated, their opportunity to increase salary by adding specific skills actually lead to a smaller average early-career salary than software engineers* Several factors contribute to salary, the most important most likely being seniority, city, and skills I hope you found my article both interesting and useful. Please feel free to comment down below if you agree or disagree with these salary comparisons. Why or why not? What other factors do you think are important to point out in regards to salary? These can certainly be clarified even further, but I hope I was able to shed some light on the differences between software engineers and data scientist salaries. Lastly, I can ask the same question again, how do you see salaries being impacted by remote positions, especially when the city is such a big factor in determining salary? I am not affiliated with any of these companies. Please feel free to check out my profile, Matt Przybyla, and other articles, as well as subscribe to receive email notifications for my blogs by following the link below, or by clicking on the subscribe icon on the top of the screen by the follow icon, and reach out to me on LinkedIn if you have any questions or comments. Subscribe link: https://datascience2.medium.com/subscribe Referral link: https://datascience2.medium.com/membership (I will receive a commission if you sign up for a membership on Medium) Keep in mind that for this article, the numbers are not my salaries, and are reported by PayScale instead, and other actual data scientists and software engineers. So, this article is in turn, a discussion around real data and is intended for you to better gain an understanding of what makes a role (in general), increase or decrease in salary amount based on certain factors. [1] Photo by NeONBRAND on Unsplash, (2017) [2] Photo by Alexandru Acea on Unsplash, (2018) [3] PayScale, Inc., Average Software Engineer Salary PayScale, (Dec 15th, 2021) [4] Photo by Campaign Creators on Unsplash, (2018) [5] PayScale, Inc., Average Data Scientist Salary PayScale, (Dec 14th, 2021) [6] PayScale, Inc., PayScale Salary Survey, (2021)
[ { "code": null, "e": 108, "s": 47, "text": "IntroductionSoftware EngineerData ScientistSummaryReferences" }, { "code": null, "e": 121, "s": 108, "text": "Introduction" }, { "code": null, "e": 139, "s": 121, "text": "Software Engineer" }, { "code": null, "e": 154, "s": 139, "text": "Data Scientist" }, { "code": null, "e": 162, "s": 154, "text": "Summary" }, { "code": null, "e": 173, "s": 162, "text": "References" }, { "code": null, "e": 545, "s": 173, "text": "The goal of this article is to show the differences and similarities between two popular tech roles. This information can be helpful for determining which role you would like to pursue. It can also be interesting to clear up some assumptions between these positions in regards to salary. We will deep dive into the average salary in US dollars by city and skills as well." }, { "code": null, "e": 557, "s": 545, "text": "Disclaimer:" }, { "code": null, "e": 1044, "s": 557, "text": "Like I have said for the previous articles in this series, this article aims not to compare roles as if one deserves more money or not, but is instead a guide allowing professionals in these two fields to assess against their current or expected salary. Keep in mind that these salary values are more general and no one website can be enough to assess your worth. It is the direction of these values that can be utilized as a tool for you to have when dealing with salary in the future." }, { "code": null, "e": 1322, "s": 1044, "text": "The role of a software engineer can mean many different things. Some software engineers are strictly back-end, front-end, full-stack, or even machine learning engineers. With that being said, the salary can also be fluctuating quite a bit as well based on a variety of factors." }, { "code": null, "e": 1397, "s": 1322, "text": "Note: this salary information has been last updated on December 15th, 2021" }, { "code": null, "e": 1510, "s": 1397, "text": "Here are some of the various seniority levels of software engineers and their respective salaries [3] (rounded):" }, { "code": null, "e": 1551, "s": 1510, "text": "Average Overall Software Engineer → $88k" }, { "code": null, "e": 1607, "s": 1551, "text": "Average Entry-Level Software Engineer → $77k (≤ 1 year)" }, { "code": null, "e": 1665, "s": 1607, "text": "Average Early-Career Software Engineer → $86k (1–4 years)" }, { "code": null, "e": 1721, "s": 1665, "text": "Average Mid-Career Software Engineer → $97k (5–9 years)" }, { "code": null, "e": 1781, "s": 1721, "text": "Average Late-Career Software Engineer → $108k (10–19 years)" }, { "code": null, "e": 1812, "s": 1781, "text": "Do I agree with these numbers?" }, { "code": null, "e": 1816, "s": 1812, "text": "No." }, { "code": null, "e": 1949, "s": 1816, "text": "I think they are too low, especially the entry-level salary. However, there are certain cities that might have much higher salaries." }, { "code": null, "e": 2110, "s": 1949, "text": "With that being said, here are some popular cities and some other cities with their respective salary averages for early-career software engineers (avg is 86k):" }, { "code": null, "e": 2140, "s": 2110, "text": "New York, New York → $107,845" }, { "code": null, "e": 2171, "s": 2140, "text": "Seattle, Washington → $109,061" }, { "code": null, "e": 2195, "s": 2171, "text": "Austin, Texas → $89,398" }, { "code": null, "e": 2222, "s": 2195, "text": "Atlanta, Georgia → $84,004" }, { "code": null, "e": 2417, "s": 2222, "text": "As you can see (and would expect), there is a considerable jump when you update to a specific city. Now, let’s add the most popular skill that can contribute to the highest salary for that city." }, { "code": null, "e": 2491, "s": 2417, "text": "Below is a breakdown of those same cities from above with certain skills:" }, { "code": null, "e": 2540, "s": 2491, "text": "New York, New York → $135,197 with Apache Hadoop" }, { "code": null, "e": 2588, "s": 2540, "text": "Seattle, Washington → $127,424 with Objective-C" }, { "code": null, "e": 2632, "s": 2588, "text": "Austin, Texas → $121,500 with Microservices" }, { "code": null, "e": 2681, "s": 2632, "text": "Atlanta, Georgia → $109,927 with Cloud Computing" }, { "code": null, "e": 2849, "s": 2681, "text": "The takeaway here is that when you add skills that are not necessarily directly software engineering-focused, you can expect to make more money, according to PayScale." }, { "code": null, "e": 3278, "s": 2849, "text": "In my personal experience, data scientist salaries can have a pretty big range (we will outline the specifics of the range below). It can depend on a variety of factors, of course, like the number of years of experience you have, the city you live in, or the specific skillset you can employ. With that being said, let’s look into some of these variations of qualifications/characteristics to see how the salary average updates." }, { "code": null, "e": 3353, "s": 3278, "text": "Note: this salary information has been last updated on December 14th, 2021" }, { "code": null, "e": 3464, "s": 3353, "text": "Here are some of the various seniority levels of data scientists and their respective salaries [5] (rounded) :" }, { "code": null, "e": 3502, "s": 3464, "text": "Average Overall Data Scientist → $97k" }, { "code": null, "e": 3555, "s": 3502, "text": "Average Entry-Level Data Scientist → $85k (≤ 1 year)" }, { "code": null, "e": 3610, "s": 3555, "text": "Average Early-Career Data Scientist → $96k (1–4 years)" }, { "code": null, "e": 3664, "s": 3610, "text": "Average Mid-Career Data Scientist → $110k (5–9 years)" }, { "code": null, "e": 3721, "s": 3664, "text": "Average Late-Career Data Scientist → $122k (10–19 years)" }, { "code": null, "e": 3853, "s": 3721, "text": "This salary data is gathered from PayScale, and if you would like a more specific estimate, then you can use the salary survey [6]." }, { "code": null, "e": 3884, "s": 3853, "text": "Do I agree with these numbers?" }, { "code": null, "e": 3896, "s": 3884, "text": "Mostly yes." }, { "code": null, "e": 4120, "s": 3896, "text": "I believe the numbers should be higher, but again, these are averages, so there can be smaller cities or more rural areas that are not as expensive and those can compose more of the estimates than the cities that cost more." }, { "code": null, "e": 4278, "s": 4120, "text": "With that being said, here are some popular cities and some other cities with their respective salary averages for early-career data scientists (avg is 96k):" }, { "code": null, "e": 4308, "s": 4278, "text": "New York, New York → $107,092" }, { "code": null, "e": 4339, "s": 4308, "text": "Seattle, Washington → $111,882" }, { "code": null, "e": 4363, "s": 4339, "text": "Dallas, Texas → $92,724" }, { "code": null, "e": 4390, "s": 4363, "text": "Atlanta, Georgia → $92,758" }, { "code": null, "e": 4485, "s": 4390, "text": "Now, let’s add the most popular skill that can contribute to the highest salary for that city." }, { "code": null, "e": 4560, "s": 4485, "text": "Below, is a breakdown of those same cities from above with certain skills:" }, { "code": null, "e": 4607, "s": 4560, "text": "New York, New York → $117,186 with Apache Hive" }, { "code": null, "e": 4669, "s": 4607, "text": "Seattle, Washington → $120,533 with Amazon Web Services (AWS)" }, { "code": null, "e": 4721, "s": 4669, "text": "Dallas, Texas → $112,500 with Algorithm Development" }, { "code": null, "e": 4767, "s": 4721, "text": "Atlanta, Georgia → $99,750 with Apache Hadoop" }, { "code": null, "e": 5027, "s": 4767, "text": "To me, the biggest surprise is the Dallas, Texas breakdown of adding the algorithm development skill, from ~92k to ~112k. This jump is pretty big for adding one skill. I am also not sure exactly what this skill means — which, brings me to an important point —" }, { "code": null, "e": 5183, "s": 5027, "text": "be sure to look into all the skills you know, and include them on your resume, because they may provide to be the biggest factor in determining your salary" }, { "code": null, "e": 5553, "s": 5183, "text": "As expected, cities and skills can affect the reported salary for both software engineers and data scientists. However, there were certain skills that contributed to a surprising jump in salary, and those were just the specific cities and skills we looked at. There could be other combinations as well that can be discovered when playing around with this PayScale tool." }, { "code": null, "e": 5621, "s": 5553, "text": "Here is a salary summary of software engineers and data scientists:" }, { "code": null, "e": 6048, "s": 5621, "text": "* Average Overall Software Engineer → $88k* Average Overall Data Scientist → $97k* Data scientists may have a higher overall salary, but we saw that for the cities we investigated, their opportunity to increase salary by adding specific skills actually lead to a smaller average early-career salary than software engineers* Several factors contribute to salary, the most important most likely being seniority, city, and skills" }, { "code": null, "e": 6460, "s": 6048, "text": "I hope you found my article both interesting and useful. Please feel free to comment down below if you agree or disagree with these salary comparisons. Why or why not? What other factors do you think are important to point out in regards to salary? These can certainly be clarified even further, but I hope I was able to shed some light on the differences between software engineers and data scientist salaries." }, { "code": null, "e": 6632, "s": 6460, "text": "Lastly, I can ask the same question again, how do you see salaries being impacted by remote positions, especially when the city is such a big factor in determining salary?" }, { "code": null, "e": 6681, "s": 6632, "text": "I am not affiliated with any of these companies." }, { "code": null, "e": 7005, "s": 6681, "text": "Please feel free to check out my profile, Matt Przybyla, and other articles, as well as subscribe to receive email notifications for my blogs by following the link below, or by clicking on the subscribe icon on the top of the screen by the follow icon, and reach out to me on LinkedIn if you have any questions or comments." }, { "code": null, "e": 7063, "s": 7005, "text": "Subscribe link: https://datascience2.medium.com/subscribe" }, { "code": null, "e": 7121, "s": 7063, "text": "Referral link: https://datascience2.medium.com/membership" }, { "code": null, "e": 7193, "s": 7121, "text": "(I will receive a commission if you sign up for a membership on Medium)" }, { "code": null, "e": 7571, "s": 7193, "text": "Keep in mind that for this article, the numbers are not my salaries, and are reported by PayScale instead, and other actual data scientists and software engineers. So, this article is in turn, a discussion around real data and is intended for you to better gain an understanding of what makes a role (in general), increase or decrease in salary amount based on certain factors." }, { "code": null, "e": 7614, "s": 7571, "text": "[1] Photo by NeONBRAND on Unsplash, (2017)" }, { "code": null, "e": 7662, "s": 7614, "text": "[2] Photo by Alexandru Acea on Unsplash, (2018)" }, { "code": null, "e": 7742, "s": 7662, "text": "[3] PayScale, Inc., Average Software Engineer Salary PayScale, (Dec 15th, 2021)" }, { "code": null, "e": 7793, "s": 7742, "text": "[4] Photo by Campaign Creators on Unsplash, (2018)" }, { "code": null, "e": 7870, "s": 7793, "text": "[5] PayScale, Inc., Average Data Scientist Salary PayScale, (Dec 14th, 2021)" } ]
How can I create directory tree using C++ in Linux?
In this section we will see how to create a directory tree using C++ code in Linux. In Linux terminal we can put some command like “mkdir –p /dir/dir1/dir2” Here –p is used to mark as parent (recursively create inner directories). In C++ code we can use some libraries of Linux system. Then we can use Linux terminal commands as string argument of the system() function. We can create directory tree like this. #include <bits/stdc++.h> #include <iostream> #include <sys/stat.h> #include <sys/types.h> using namespace std; int main() { int status; status = system("mkdir -p TP/My_Folder/test"); // Creating a directory if (status == -1) cerr << "Error : " << strerror(errno) << endl; else cout << "Directories are created" << endl; } Directories are created If we check manually, we can get the directories inside the current directory.
[ { "code": null, "e": 1293, "s": 1062, "text": "In this section we will see how to create a directory tree using C++ code in Linux. In Linux terminal we can put some command like “mkdir –p /dir/dir1/dir2” Here –p is used to mark as parent (recursively create inner directories)." }, { "code": null, "e": 1473, "s": 1293, "text": "In C++ code we can use some libraries of Linux system. Then we can use Linux terminal commands as string argument of the system() function. We can create directory tree like this." }, { "code": null, "e": 1819, "s": 1473, "text": "#include <bits/stdc++.h>\n#include <iostream>\n#include <sys/stat.h>\n#include <sys/types.h>\nusing namespace std;\nint main() {\n int status;\n status = system(\"mkdir -p TP/My_Folder/test\"); // Creating a directory\n if (status == -1)\n cerr << \"Error : \" << strerror(errno) << endl;\n else\n cout << \"Directories are created\" << endl;\n}" }, { "code": null, "e": 1843, "s": 1819, "text": "Directories are created" }, { "code": null, "e": 1922, "s": 1843, "text": "If we check manually, we can get the directories inside the current directory." } ]
Data visualization with Pairplot Seaborn and Pandas - GeeksforGeeks
22 Jun, 2021 Data Visualization is the presentation of data in pictorial format. It is extremely important for Data Analysis, primarily because of the fantastic ecosystem of data-centric Python packages. And it helps to understand the data, however, complex it is, the significance of data by summarizing and presenting a huge amount of data in a simple and easy-to-understand format and helps communicate information clearly and effectively. Pandas and Seaborn is one of those packages and makes importing and analyzing data much easier. In this article, we will use Pandas and Pairplot Seaborn to analyze data. Pandas Offer tools for cleaning and process your data. It is the most popular Python library that is used for data analysis. In pandas, a data table is called a dataframe. So, let’s start with creating a Pandas data frame: Example 1: Python3 # Python code demonstrate creating import pandas as pd # initialise data of lists.data = {'Name':[ 'Mohe' , 'Karnal' , 'Yrik' , 'jack' ], 'Age':[ 30 , 21 , 29 , 28 ]} # Create DataFramedf = pd.DataFrame( data ) # Print the output.display(df) Output: Example 2: load the CSV data from the system and display it through pandas. Python3 # import moduleimport pandas # load the csvdata = pandas.read_csv("nba.csv") # show first 5 columndata.head() Output: To plot multiple pairwise bivariate distributions in a dataset, you can use the pairplot() function. This shows the relationship for (n, 2) combination of variable in a DataFrame as a matrix of plots and the diagonal plots are the univariate plots. Syntax: seaborn.pairplot( data, \*\*kwargs ) Parameter: data: Tidy (long-form) dataframe where each column is a variable and each row is an observation. hue: Variable in “data“ to map plot aspects to different colors. palette: dict or seaborn color palette {x, y}_vars: lists of variable names, optional dropna: boolean, optional Example 1: Python3 # importing packagesimport seabornimport matplotlib.pyplot as plt # loading dataset using seaborndf = seaborn.load_dataset('tips') # pairplot with hue sexseaborn.pairplot(df, hue ='size')plt.show() Output: We see how to create pandas dataframe and Pairplot. We will visualize data with pairplot using pandas Example 1: In this example, we will simply plot a pairplot with pandas data frame. Here we are simply loading nba.csv data and creating a dataframe and although passing as arguments in a pairplot. Python3 # importing packagesimport seabornimport pandas # load the csvdata = pandas.read_csv("nba.csv") # pairplotseaborn.pairplot(data) Output: Example 2: In this example, we will be going to use hue attributes for the visualization of a specific column. Python3 # importing packagesimport seabornimport pandas # load the csvdata = pandas.read_csv("nba.csv")seaborn.pairplot(data.head(), hue = 'Age') Output: Example 3: In this example, we will pass the dictionaries of keyword arguments for bivariate plotting function(plot_kws and diag_kws) Python3 # importing packagesimport seabornimport pandas# load the csvdata = pandas.read_csv("nba.csv") seaborn.pairplot(data, hue = 'Age', diag_kind = 'kde', plot_kws = {'edgecolor': 'k'}, size = 4) Output: sooda367 Data Visualization Python-pandas Python-Seaborn Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Read JSON file using Python Adding new column to existing DataFrame in Pandas Python map() function How to get column names in Pandas dataframe Python Dictionary Taking input in Python Read a file line by line in Python Enumerate() in Python How to Install PIP on Windows ? Iterate over a list in Python
[ { "code": null, "e": 26762, "s": 26734, "text": "\n22 Jun, 2021" }, { "code": null, "e": 27192, "s": 26762, "text": "Data Visualization is the presentation of data in pictorial format. It is extremely important for Data Analysis, primarily because of the fantastic ecosystem of data-centric Python packages. And it helps to understand the data, however, complex it is, the significance of data by summarizing and presenting a huge amount of data in a simple and easy-to-understand format and helps communicate information clearly and effectively." }, { "code": null, "e": 27362, "s": 27192, "text": "Pandas and Seaborn is one of those packages and makes importing and analyzing data much easier. In this article, we will use Pandas and Pairplot Seaborn to analyze data." }, { "code": null, "e": 27534, "s": 27362, "text": "Pandas Offer tools for cleaning and process your data. It is the most popular Python library that is used for data analysis. In pandas, a data table is called a dataframe." }, { "code": null, "e": 27585, "s": 27534, "text": "So, let’s start with creating a Pandas data frame:" }, { "code": null, "e": 27596, "s": 27585, "text": "Example 1:" }, { "code": null, "e": 27604, "s": 27596, "text": "Python3" }, { "code": "# Python code demonstrate creating import pandas as pd # initialise data of lists.data = {'Name':[ 'Mohe' , 'Karnal' , 'Yrik' , 'jack' ], 'Age':[ 30 , 21 , 29 , 28 ]} # Create DataFramedf = pd.DataFrame( data ) # Print the output.display(df)", "e": 27866, "s": 27604, "text": null }, { "code": null, "e": 27878, "s": 27870, "text": "Output:" }, { "code": null, "e": 27958, "s": 27882, "text": "Example 2: load the CSV data from the system and display it through pandas." }, { "code": null, "e": 27968, "s": 27960, "text": "Python3" }, { "code": "# import moduleimport pandas # load the csvdata = pandas.read_csv(\"nba.csv\") # show first 5 columndata.head()", "e": 28078, "s": 27968, "text": null }, { "code": null, "e": 28090, "s": 28082, "text": "Output:" }, { "code": null, "e": 28343, "s": 28094, "text": "To plot multiple pairwise bivariate distributions in a dataset, you can use the pairplot() function. This shows the relationship for (n, 2) combination of variable in a DataFrame as a matrix of plots and the diagonal plots are the univariate plots." }, { "code": null, "e": 28390, "s": 28345, "text": "Syntax: seaborn.pairplot( data, \\*\\*kwargs )" }, { "code": null, "e": 28401, "s": 28390, "text": "Parameter:" }, { "code": null, "e": 28499, "s": 28401, "text": "data: Tidy (long-form) dataframe where each column is a variable and each row is an observation." }, { "code": null, "e": 28564, "s": 28499, "text": "hue: Variable in “data“ to map plot aspects to different colors." }, { "code": null, "e": 28603, "s": 28564, "text": "palette: dict or seaborn color palette" }, { "code": null, "e": 28650, "s": 28603, "text": "{x, y}_vars: lists of variable names, optional" }, { "code": null, "e": 28676, "s": 28650, "text": "dropna: boolean, optional" }, { "code": null, "e": 28690, "s": 28678, "text": "Example 1: " }, { "code": null, "e": 28700, "s": 28692, "text": "Python3" }, { "code": "# importing packagesimport seabornimport matplotlib.pyplot as plt # loading dataset using seaborndf = seaborn.load_dataset('tips') # pairplot with hue sexseaborn.pairplot(df, hue ='size')plt.show()", "e": 28898, "s": 28700, "text": null }, { "code": null, "e": 28906, "s": 28898, "text": "Output:" }, { "code": null, "e": 29008, "s": 28906, "text": "We see how to create pandas dataframe and Pairplot. We will visualize data with pairplot using pandas" }, { "code": null, "e": 29020, "s": 29008, "text": "Example 1: " }, { "code": null, "e": 29206, "s": 29020, "text": "In this example, we will simply plot a pairplot with pandas data frame. Here we are simply loading nba.csv data and creating a dataframe and although passing as arguments in a pairplot." }, { "code": null, "e": 29214, "s": 29206, "text": "Python3" }, { "code": "# importing packagesimport seabornimport pandas # load the csvdata = pandas.read_csv(\"nba.csv\") # pairplotseaborn.pairplot(data)", "e": 29343, "s": 29214, "text": null }, { "code": null, "e": 29351, "s": 29343, "text": "Output:" }, { "code": null, "e": 29362, "s": 29351, "text": "Example 2:" }, { "code": null, "e": 29462, "s": 29362, "text": "In this example, we will be going to use hue attributes for the visualization of a specific column." }, { "code": null, "e": 29470, "s": 29462, "text": "Python3" }, { "code": "# importing packagesimport seabornimport pandas # load the csvdata = pandas.read_csv(\"nba.csv\")seaborn.pairplot(data.head(), hue = 'Age')", "e": 29608, "s": 29470, "text": null }, { "code": null, "e": 29616, "s": 29608, "text": "Output:" }, { "code": null, "e": 29627, "s": 29616, "text": "Example 3:" }, { "code": null, "e": 29750, "s": 29627, "text": "In this example, we will pass the dictionaries of keyword arguments for bivariate plotting function(plot_kws and diag_kws)" }, { "code": null, "e": 29758, "s": 29750, "text": "Python3" }, { "code": "# importing packagesimport seabornimport pandas# load the csvdata = pandas.read_csv(\"nba.csv\") seaborn.pairplot(data, hue = 'Age', diag_kind = 'kde', plot_kws = {'edgecolor': 'k'}, size = 4)", "e": 29961, "s": 29758, "text": null }, { "code": null, "e": 29973, "s": 29965, "text": "Output:" }, { "code": null, "e": 29986, "s": 29977, "text": "sooda367" }, { "code": null, "e": 30005, "s": 29986, "text": "Data Visualization" }, { "code": null, "e": 30019, "s": 30005, "text": "Python-pandas" }, { "code": null, "e": 30034, "s": 30019, "text": "Python-Seaborn" }, { "code": null, "e": 30041, "s": 30034, "text": "Python" }, { "code": null, "e": 30139, "s": 30041, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30167, "s": 30139, "text": "Read JSON file using Python" }, { "code": null, "e": 30217, "s": 30167, "text": "Adding new column to existing DataFrame in Pandas" }, { "code": null, "e": 30239, "s": 30217, "text": "Python map() function" }, { "code": null, "e": 30283, "s": 30239, "text": "How to get column names in Pandas dataframe" }, { "code": null, "e": 30301, "s": 30283, "text": "Python Dictionary" }, { "code": null, "e": 30324, "s": 30301, "text": "Taking input in Python" }, { "code": null, "e": 30359, "s": 30324, "text": "Read a file line by line in Python" }, { "code": null, "e": 30381, "s": 30359, "text": "Enumerate() in Python" }, { "code": null, "e": 30413, "s": 30381, "text": "How to Install PIP on Windows ?" } ]
Switching on and off bulb in JavaScript
Consider this following situation − There are n bulbs that are initially off. We first turn on all the bulbs. Then, we turn off every second bulb. On the third round, we toggle every third bulb (turning on if it's off or turning off if it's on). In general, for the ith round, we toggle every i bulb. And lastly for the nth round, we only toggle the last bulb. We are required to write a JavaScript function that takes n as the only input and finds out how many bulbs are on after n rounds. For example, if the input to the function is − const n = 4; Then the output should be − const output = 2; In the state array, a 0 indicates off whereas 1 indicates on − Hence after the fifth round only two bulbs are on. The code for this will be − const n = 5; const findOn = (n = 1) => { let off = 0; let on = n; while(off <= on){ let mid = Math.floor((off + on) / 2); if(mid * mid > n){ on = mid - 1; }else{ off = mid + 1; }; }; return Math.floor(on); }; console.log(findOn(n)); And the output in the console will be − 2
[ { "code": null, "e": 1098, "s": 1062, "text": "Consider this following situation −" }, { "code": null, "e": 1308, "s": 1098, "text": "There are n bulbs that are initially off. We first turn on all the bulbs. Then, we turn off every\nsecond bulb. On the third round, we toggle every third bulb (turning on if it's off or turning off if\nit's on)." }, { "code": null, "e": 1423, "s": 1308, "text": "In general, for the ith round, we toggle every i bulb. And lastly for the nth round, we only toggle\nthe last bulb." }, { "code": null, "e": 1553, "s": 1423, "text": "We are required to write a JavaScript function that takes n as the only input and finds out how\nmany bulbs are on after n rounds." }, { "code": null, "e": 1600, "s": 1553, "text": "For example, if the input to the function is −" }, { "code": null, "e": 1613, "s": 1600, "text": "const n = 4;" }, { "code": null, "e": 1641, "s": 1613, "text": "Then the output should be −" }, { "code": null, "e": 1659, "s": 1641, "text": "const output = 2;" }, { "code": null, "e": 1722, "s": 1659, "text": "In the state array, a 0 indicates off whereas 1 indicates on −" }, { "code": null, "e": 1773, "s": 1722, "text": "Hence after the fifth round only two bulbs are on." }, { "code": null, "e": 1801, "s": 1773, "text": "The code for this will be −" }, { "code": null, "e": 2091, "s": 1801, "text": "const n = 5;\nconst findOn = (n = 1) => {\n let off = 0;\n let on = n;\n while(off <= on){\n let mid = Math.floor((off + on) / 2);\n if(mid * mid > n){\n on = mid - 1;\n }else{\n off = mid + 1;\n };\n };\n return Math.floor(on);\n};\nconsole.log(findOn(n));" }, { "code": null, "e": 2131, "s": 2091, "text": "And the output in the console will be −" }, { "code": null, "e": 2133, "s": 2131, "text": "2" } ]
Python Program for Subset Sum Problem
In this article, we will learn about the solution to the problem statement given below. Problem statement − We are given a set of non-negative integers in an array, and a value sum, we need to determine if there exists a subset of the given set with a sum equal to a given sum. Now let’s observe the solution in the implementation below − # Naive approach def SubsetSum(set, n, sum) : # Base Cases if (sum == 0) : return True if (n == 0 and sum != 0) : return False # ignore if last element is > sum if (set[n - 1] > sum) : return SubsetSum(set, n - 1, sum); # else,we check the sum # (1) including the last element # (2) excluding the last element return SubsetSum(set, n-1, sum) or SubsetSum(set, n-1, sumset[n-1]) # main set = [2, 14, 6, 22, 4, 8] sum = 10 n = len(set) if (SubsetSum(set, n, sum) == True) : print("Found a subset with given sum") else : print("No subset with given sum") Found a subset with given sum # dynamic approach # maximum number of activities that can be performed by a single person def Activities(s, f ): n = len(f) print ("The selected activities are:") # The first activity is always selected i = 0 print (i,end=" ") # For rest of the activities for j in range(n): # if start time is greater than or equal to that of previous activity if s[j] >= f[i]: print (j,end=" ") i = j # main s = [1, 2, 0, 3, 2, 4] f = [2, 5, 4, 6, 8, 8] Activities(s, f) Found a subset with given sum In this article, we have learned about how we can make a Python Program for Subset Sum Problem
[ { "code": null, "e": 1150, "s": 1062, "text": "In this article, we will learn about the solution to the problem statement given below." }, { "code": null, "e": 1340, "s": 1150, "text": "Problem statement − We are given a set of non-negative integers in an array, and a value sum, we need to determine if there exists a subset of the given set with a sum equal to a given sum." }, { "code": null, "e": 1401, "s": 1340, "text": "Now let’s observe the solution in the implementation below −" }, { "code": null, "e": 1418, "s": 1401, "text": "# Naive approach" }, { "code": null, "e": 2004, "s": 1418, "text": "def SubsetSum(set, n, sum) :\n # Base Cases\n if (sum == 0) :\n return True\n if (n == 0 and sum != 0) :\n return False\n # ignore if last element is > sum\n if (set[n - 1] > sum) :\n return SubsetSum(set, n - 1, sum);\n # else,we check the sum\n # (1) including the last element\n # (2) excluding the last element\n return SubsetSum(set, n-1, sum) or SubsetSum(set, n-1, sumset[n-1])\n# main\nset = [2, 14, 6, 22, 4, 8]\nsum = 10\nn = len(set)\nif (SubsetSum(set, n, sum) == True) :\n print(\"Found a subset with given sum\")\nelse :\n print(\"No subset with given sum\")" }, { "code": null, "e": 2034, "s": 2004, "text": "Found a subset with given sum" }, { "code": null, "e": 2053, "s": 2034, "text": "# dynamic approach" }, { "code": null, "e": 2542, "s": 2053, "text": "# maximum number of activities that can be performed by a single person\ndef Activities(s, f ):\n n = len(f)\n print (\"The selected activities are:\")\n # The first activity is always selected\n i = 0\n print (i,end=\" \")\n # For rest of the activities\n for j in range(n):\n # if start time is greater than or equal to that of previous activity\n if s[j] >= f[i]:\n print (j,end=\" \")\n i = j\n# main\ns = [1, 2, 0, 3, 2, 4]\nf = [2, 5, 4, 6, 8, 8]\nActivities(s, f)" }, { "code": null, "e": 2572, "s": 2542, "text": "Found a subset with given sum" }, { "code": null, "e": 2667, "s": 2572, "text": "In this article, we have learned about how we can make a Python Program for Subset Sum Problem" } ]
Find nth term of a given recurrence relation in Python
Suppose we have a sequence of numbers called bn, this is represented using a recurrence relation like b1=1 and bn+1/bn=2n . We have to find the value of log2(bn) for a given n. So, if the input is like 6, then the output will be 5 as log2(bn) = (n * (n - 1)) / 2 = (6*(6-1))/2 = 15 We can solve this problem by solving this relation as follows − bn+1/bn = 2n bn/bn-1 = 2n-1 ... b2/b1 = 21 , If we multiply all of above, we can get (bn+1/bn).(bn/bn-1)......(b2/b1) = 2n + (n-1)+..........+1 So, bn+1/b1 = 2n(n+1)/2 As 1 + 2 + 3 + .......... + (n-1) + n = n(n+1)/2 So, bn+1 = 2n(n+1)/2 * b1; We are assuming that initial value b1 = 1 So, bn+1 = 2n(n+1)/2 After substituting (n+1) for n, we get, bn = 2n(n-1)/2 By taking log both sides, we get, log2(bn) = n(n-1)/2 Let us see the following implementation to get better understanding − Live Demo def add_upto_n(n): res = (n * (n - 1)) / 2 return res n = 6 print(int(add_upto_n(n))) 6 15
[ { "code": null, "e": 1239, "s": 1062, "text": "Suppose we have a sequence of numbers called bn, this is represented using a recurrence relation like b1=1 and bn+1/bn=2n . We have to find the value of log2(bn) for a given n." }, { "code": null, "e": 1344, "s": 1239, "text": "So, if the input is like 6, then the output will be 5 as log2(bn) = (n * (n - 1)) / 2 = (6*(6-1))/2 = 15" }, { "code": null, "e": 1408, "s": 1344, "text": "We can solve this problem by solving this relation as follows −" }, { "code": null, "e": 1421, "s": 1408, "text": "bn+1/bn = 2n" }, { "code": null, "e": 1436, "s": 1421, "text": "bn/bn-1 = 2n-1" }, { "code": null, "e": 1440, "s": 1436, "text": "..." }, { "code": null, "e": 1493, "s": 1440, "text": "b2/b1 = 21 , If we multiply all of above, we can get" }, { "code": null, "e": 1552, "s": 1493, "text": "(bn+1/bn).(bn/bn-1)......(b2/b1) = 2n + (n-1)+..........+1" }, { "code": null, "e": 1576, "s": 1552, "text": "So, bn+1/b1 = 2n(n+1)/2" }, { "code": null, "e": 1625, "s": 1576, "text": "As 1 + 2 + 3 + .......... + (n-1) + n = n(n+1)/2" }, { "code": null, "e": 1694, "s": 1625, "text": "So, bn+1 = 2n(n+1)/2 * b1; We are assuming that initial value b1 = 1" }, { "code": null, "e": 1715, "s": 1694, "text": "So, bn+1 = 2n(n+1)/2" }, { "code": null, "e": 1755, "s": 1715, "text": "After substituting (n+1) for n, we get," }, { "code": null, "e": 1770, "s": 1755, "text": "bn = 2n(n-1)/2" }, { "code": null, "e": 1804, "s": 1770, "text": "By taking log both sides, we get," }, { "code": null, "e": 1824, "s": 1804, "text": "log2(bn) = n(n-1)/2" }, { "code": null, "e": 1894, "s": 1824, "text": "Let us see the following implementation to get better understanding −" }, { "code": null, "e": 1905, "s": 1894, "text": " Live Demo" }, { "code": null, "e": 1997, "s": 1905, "text": "def add_upto_n(n):\n res = (n * (n - 1)) / 2\n return res\nn = 6\nprint(int(add_upto_n(n)))" }, { "code": null, "e": 1999, "s": 1997, "text": "6" }, { "code": null, "e": 2002, "s": 1999, "text": "15" } ]
Area Charts with Plotly Express. Traces & Layout | by Darío Weitz | Towards Data Science
Plotly Express, an object-oriented interface to figure creation, was released in 2019. It is a high-level wrapper for Plotly.py that includes functions to plot standard 2D & 3D charts and choropleth maps. Fully compatible with the rest of the Plotly ecosystem, is an excellent tool for the rapid development of exploratory charts. But if you want to enhance your plots, you need to import a group of classes named graph objects. import plotly.graph_objects as gofig = go.Figure() The plotly.graph_objects module contains a hierarchy of Python classes. Figure is a primary class. Figure has a data attribute and a layout attribute. The data attribute has more than 40 objects, each one refers to a specific type of chart (trace) with its corresponding parameters. The layout attribute specifies the properties of the figure as a whole (axes, title, shapes, legends, etc.). The conceptual idea is to use fig.add_trace() and fig.update_layout() to manipulate these attributes in order to enhance already constructed figures. Let’s analyze this methodology with different types of area charts. An area chart is a form of line chart with the area between the horizontal axis and the line that connects data points filled with color. They are used to communicate an overall trend without being concerned about showing exact values. The vertical axis represents a quantitative variable while the horizontal axis is a timeline or a sequence of numerical intervals. Data points are connected by line segments forming a polyline, and the area between the polyline and the horizontal axis is filled with color or some type of shading. There are four types of area charts (AC): 1) Standard AC; 2) Stacked AC; 3) Percent Stacked AC; 4) Overlapping AC. 1. — Standard Area Chart (AKA Area Graph): they are particularly effective to show the evolution of a numerical variable over time. The idea is to put more emphasis on the overall trend and on the peaks and troughs of the line that connects the data points. 2. — Stacked Area Chart: it’s like several area charts stacked on top of one another. In this type of chart, there is a third variable, usually categorical, with its corresponding data series. Each data series representation begins where the previous data series ends (they do not overlap). The final figure indicates the sum of all the data represented. 3. — Percent Stacked Area Chart (AKA 100% Stacked Area Chart): just like the previous chart, several areas are stacked on top of one another and a third categorical variable is represented. It is a Part-to-whole chart where each area indicates the percentage of each part referred to the total of the category. The final height of the vertical axis is always 100%. This means that there is a second baseline on the top of the chart that helps to track some particular trends. 4. — Overlapping Area Charts: in this kind of graph there is some overlapping between areas. Colors and transparency must be properly adjusted so particular lines can be easily seen. They allow us to make very good comparisons between trends. We worked with a dataset downloaded from Kaggle [1]. The dataset contains records related to Video Games Sales & Game Ratings Data Scraped from VzCharts. We particularly selected a csv file with 1031 records about Video Games sales on the Playstation 4 platform by Sony. We would like to know how sales were distributed in different regions of the world in the period 2013–2018. First, we imported Plotly Express as px, the Pandas library as pd and converted our csv file into a dataframe: import pandas as pdimport plotly.express as pxpath ='your path'df = pd.read_csv(path + 'PS4_GamesSales2.csv', index_col = False, header = 0, sep = ';', engine='python') The screenshot below shows the first ten records of the dataset: Remember: real-world data is dirty. So we did some cleaning before using the data. Particularly, we used dropna to eliminate rows with N/A values in the Year column, and used drop to delete rows with 0 values in the Global column. Then we split the data into groups based on the Year column and applied the function sum() on each group. df.dropna(subset = ['Year'], inplace = True)df.drop(df[df['Global'] == 0.0].index, inplace = True)df_area = df.groupby(['Year']).sum().reset_index() Now we are ready to draw our first chart. For the standard area chart in this article, the Plotly Express function is px.area and the corresponding parameters are: data_frame; x= a name of a column in data_frame representing the timeline; y= a name of a column in data_frame representing the statistic calculated. We updated the chart with update.layout: set the title, the size of the font, and set the figure dimensions with width and height. Then we updated the x-axis and the y-axis (text, font, tickfont). We saved the chart as a static png file and finally, we drew the chart using the default template (plotly, “Histograms with Plotly Express, Themes & Templates”, https://towardsdatascience.com/histograms-with-plotly-express-e9e134ae37ad). fig1 = px.area( df_area, x = 'Year', y = 'Global')fig1.update_layout( title = "PS4 Global Sales", title_font_size = 40, width = 1600, height = 1400)fig1.update_xaxes( title_text = 'Year', title_font=dict(size=30, family='Verdana', color='black'), tickfont=dict(family='Calibri', color='darkred', size=25))fig1.update_yaxes( title_text = "Sales (MM)", range = (0,160), title_font=dict(size=30,family='Verdana',color='black'), tickfont=dict(family='Calibri', color='darkred', size=25))fig1.write_image(path + "figarea1.png")fig1.show() The graph above indicates the evolution in the number of PS4 global sales for the period 2013–2018. The same story could have been told with a line graph but without the visual power of the area chart. But remember that we would like to know how sales were distributed in different regions of the world during the same period. So we need a stacked area chart where each area (each region) contributes to the total (the whole, sum of sales). The height of each area represents the value of each particular region whilst the final height is the sum of those values. Now we used the module plotly.graph_objects with a different methodology [fig.add_trace()] and a different trace [go.Scatter()]. x= is the name of a column in data_frame representing the timeline while y= is the name of a column in data_frame representing a particular region. The stackgroup parameter is used to add the y values of the different traces in the same group. We must include mode = ‘lines’ to draw lines instead of points. import plotly.graph_objects as gofig2 = go.Figure()fig2.add_trace(go.Scatter( x= df_area['Year'], y = df_area['North America'], name = 'North America', mode = 'lines', line=dict(width=0.5, color='orange'), stackgroup = 'one'))fig2.add_trace(go.Scatter( x= df_area['Year'], y = df_area['Europe'], name = 'Europe', mode = 'lines', line=dict(width=0.5,color='lightgreen'), stackgroup = 'one'))fig2.add_trace(go.Scatter( x= df_area['Year'], y = df_area['Japan'], name = 'Japan', mode = 'lines', line=dict(width=0.5, color='blue'), stackgroup = 'one'))fig2.add_trace(go.Scatter( x= df_area['Year'], y = df_area['Rest of World'], name = 'Rest of World', mode = 'lines', line=dict(width=0.5, color='darkred'), stackgroup = 'one'))fig2.update_layout( title = "PS4 Global Sales per Region", title_font_size = 40, legend_font_size = 20, width = 1600, height = 1400)fig2.update_xaxes( title_text = 'Year', title_font=dict(size=30, family='Verdana', color='black'), tickfont=dict(family='Calibri', color='darkred', size=25))fig2.update_yaxes( title_text = "Sales (MM)", range = (0,160), title_font=dict(size=30, family='Verdana', color='black'), tickfont=dict(family='Calibri', color='darkred', size=25))fig2.write_image(path + "figarea2.png")fig2.show() Let’s see if a percent stacked area chart improves the storytelling. We only need to make one small change: add groupnorm = ‘percent’ to the first add_trace(). fig3 = go.Figure()fig3.add_trace(go.Scatter( x= df_area['Year'], y = df_area['North America'], name = 'North America', mode = 'lines', line=dict(width=0.5, color='orange'), stackgroup = 'one', groupnorm = 'percent'))fig3.add_trace(go.Scatter( x= df_area['Year'], y = df_area['Europe'], name = 'Europe', mode = 'lines', line=dict(width=0.5,color='lightgreen'), stackgroup = 'one'))fig3.add_trace(go.Scatter( x= df_area['Year'], y = df_area['Japan'], name = 'Japan', mode = 'lines', line=dict(width=0.5, color='blue'), stackgroup = 'one'))fig3.add_trace(go.Scatter( x= df_area['Year'], y = df_area['Rest of World'], name = 'Rest of World', mode = 'lines', line=dict(width=0.5, color='darkred'), stackgroup = 'one'))fig3.update_layout( title = "PS4 Global Sales per Region", title_font_size = 40, legend_font_size = 20, yaxis=dict(type='linear',ticksuffix='%'), width = 1600, height = 1400)fig3.update_xaxes( title_text = 'Year', title_font=dict(size=30, family='Verdana', color='black'), tickfont=dict(family='Calibri', color='darkred', size=25))fig3.update_yaxes( title_text = "Sales (%)", range = (0,100), title_font=dict(size=30, family='Verdana', color='black'), tickfont=dict(family='Calibri', color='darkred', size=25))fig3.write_image(path + "figarea3.png")fig3.show() Figure 3 is a Part-to-whole chart where each area indicates the percentage of each region referred to the total of the world sales. The emphasis is on the trend, how the percentage of each category changes over time, and not on the exact values. Finally, we can compare the regions with the highest sales using an overlapping area chart. Instead of stackgroup, we add fill = ‘tozeroy’ to the first add_trace() and fill = ‘tonexty’ to the second add_trace(). fig4 = go.Figure()fig4.add_trace(go.Scatter( x= df_area['Year'], y = df_area['North America'], name = 'North America', mode = 'lines', line=dict(width=0.5,color='lightgreen'), fill = 'tozeroy'))fig4.add_trace(go.Scatter( x= df_area['Year'], y = df_area['Europe'], name = 'Europe', mode = 'lines', line=dict(width=0.5, color='darkred'), fill = 'tonexty'))fig4.update_layout( title = "PS4 Sales North America vs Europe", title_font_size=40, legend_font_size = 20, width = 1600, height = 1400)fig4.update_xaxes( title_text = 'Year', title_font=dict(size=30, family='Verdana', color='black'), tickfont=dict(family='Calibri', color='darkred', size=25))fig4.update_yaxes( title_text = "Sales (MM)", range = (0,70), title_font=dict(size=30, family='Verdana', color='black'), tickfont=dict(family='Calibri', color='darkred', size=25))fig4.write_image(path + "figarea4.png")fig4.show() To sum up: We use Area Charts to communicate the overall trend and the relative contribution of each part to the whole without being concerned about showing exact values. We use the plotly.graph_objects module to add traces sequentially by means of the add_trace method. Then we manipulate the chart attributes through update_layout, update_xaxes, and update_yaxes. If you find this article of interest, please read my previous (https://medium.com/@dar.wtz): “Scatter Plots with Plotly Express, Trendlines & Faceting” towardsdatascience.com “Histograms with Plotly Express, Themes & Templates”
[ { "code": null, "e": 503, "s": 172, "text": "Plotly Express, an object-oriented interface to figure creation, was released in 2019. It is a high-level wrapper for Plotly.py that includes functions to plot standard 2D & 3D charts and choropleth maps. Fully compatible with the rest of the Plotly ecosystem, is an excellent tool for the rapid development of exploratory charts." }, { "code": null, "e": 601, "s": 503, "text": "But if you want to enhance your plots, you need to import a group of classes named graph objects." }, { "code": null, "e": 652, "s": 601, "text": "import plotly.graph_objects as gofig = go.Figure()" }, { "code": null, "e": 1044, "s": 652, "text": "The plotly.graph_objects module contains a hierarchy of Python classes. Figure is a primary class. Figure has a data attribute and a layout attribute. The data attribute has more than 40 objects, each one refers to a specific type of chart (trace) with its corresponding parameters. The layout attribute specifies the properties of the figure as a whole (axes, title, shapes, legends, etc.)." }, { "code": null, "e": 1194, "s": 1044, "text": "The conceptual idea is to use fig.add_trace() and fig.update_layout() to manipulate these attributes in order to enhance already constructed figures." }, { "code": null, "e": 1262, "s": 1194, "text": "Let’s analyze this methodology with different types of area charts." }, { "code": null, "e": 1498, "s": 1262, "text": "An area chart is a form of line chart with the area between the horizontal axis and the line that connects data points filled with color. They are used to communicate an overall trend without being concerned about showing exact values." }, { "code": null, "e": 1796, "s": 1498, "text": "The vertical axis represents a quantitative variable while the horizontal axis is a timeline or a sequence of numerical intervals. Data points are connected by line segments forming a polyline, and the area between the polyline and the horizontal axis is filled with color or some type of shading." }, { "code": null, "e": 1911, "s": 1796, "text": "There are four types of area charts (AC): 1) Standard AC; 2) Stacked AC; 3) Percent Stacked AC; 4) Overlapping AC." }, { "code": null, "e": 2169, "s": 1911, "text": "1. — Standard Area Chart (AKA Area Graph): they are particularly effective to show the evolution of a numerical variable over time. The idea is to put more emphasis on the overall trend and on the peaks and troughs of the line that connects the data points." }, { "code": null, "e": 2524, "s": 2169, "text": "2. — Stacked Area Chart: it’s like several area charts stacked on top of one another. In this type of chart, there is a third variable, usually categorical, with its corresponding data series. Each data series representation begins where the previous data series ends (they do not overlap). The final figure indicates the sum of all the data represented." }, { "code": null, "e": 3000, "s": 2524, "text": "3. — Percent Stacked Area Chart (AKA 100% Stacked Area Chart): just like the previous chart, several areas are stacked on top of one another and a third categorical variable is represented. It is a Part-to-whole chart where each area indicates the percentage of each part referred to the total of the category. The final height of the vertical axis is always 100%. This means that there is a second baseline on the top of the chart that helps to track some particular trends." }, { "code": null, "e": 3243, "s": 3000, "text": "4. — Overlapping Area Charts: in this kind of graph there is some overlapping between areas. Colors and transparency must be properly adjusted so particular lines can be easily seen. They allow us to make very good comparisons between trends." }, { "code": null, "e": 3622, "s": 3243, "text": "We worked with a dataset downloaded from Kaggle [1]. The dataset contains records related to Video Games Sales & Game Ratings Data Scraped from VzCharts. We particularly selected a csv file with 1031 records about Video Games sales on the Playstation 4 platform by Sony. We would like to know how sales were distributed in different regions of the world in the period 2013–2018." }, { "code": null, "e": 3733, "s": 3622, "text": "First, we imported Plotly Express as px, the Pandas library as pd and converted our csv file into a dataframe:" }, { "code": null, "e": 3908, "s": 3733, "text": "import pandas as pdimport plotly.express as pxpath ='your path'df = pd.read_csv(path + 'PS4_GamesSales2.csv', index_col = False, header = 0, sep = ';', engine='python')" }, { "code": null, "e": 3973, "s": 3908, "text": "The screenshot below shows the first ten records of the dataset:" }, { "code": null, "e": 4310, "s": 3973, "text": "Remember: real-world data is dirty. So we did some cleaning before using the data. Particularly, we used dropna to eliminate rows with N/A values in the Year column, and used drop to delete rows with 0 values in the Global column. Then we split the data into groups based on the Year column and applied the function sum() on each group." }, { "code": null, "e": 4459, "s": 4310, "text": "df.dropna(subset = ['Year'], inplace = True)df.drop(df[df['Global'] == 0.0].index, inplace = True)df_area = df.groupby(['Year']).sum().reset_index()" }, { "code": null, "e": 4501, "s": 4459, "text": "Now we are ready to draw our first chart." }, { "code": null, "e": 5208, "s": 4501, "text": "For the standard area chart in this article, the Plotly Express function is px.area and the corresponding parameters are: data_frame; x= a name of a column in data_frame representing the timeline; y= a name of a column in data_frame representing the statistic calculated. We updated the chart with update.layout: set the title, the size of the font, and set the figure dimensions with width and height. Then we updated the x-axis and the y-axis (text, font, tickfont). We saved the chart as a static png file and finally, we drew the chart using the default template (plotly, “Histograms with Plotly Express, Themes & Templates”, https://towardsdatascience.com/histograms-with-plotly-express-e9e134ae37ad)." }, { "code": null, "e": 5793, "s": 5208, "text": "fig1 = px.area( df_area, x = 'Year', y = 'Global')fig1.update_layout( title = \"PS4 Global Sales\", title_font_size = 40, width = 1600, height = 1400)fig1.update_xaxes( title_text = 'Year', title_font=dict(size=30, family='Verdana', color='black'), tickfont=dict(family='Calibri', color='darkred', size=25))fig1.update_yaxes( title_text = \"Sales (MM)\", range = (0,160), title_font=dict(size=30,family='Verdana',color='black'), tickfont=dict(family='Calibri', color='darkred', size=25))fig1.write_image(path + \"figarea1.png\")fig1.show()" }, { "code": null, "e": 5995, "s": 5793, "text": "The graph above indicates the evolution in the number of PS4 global sales for the period 2013–2018. The same story could have been told with a line graph but without the visual power of the area chart." }, { "code": null, "e": 6357, "s": 5995, "text": "But remember that we would like to know how sales were distributed in different regions of the world during the same period. So we need a stacked area chart where each area (each region) contributes to the total (the whole, sum of sales). The height of each area represents the value of each particular region whilst the final height is the sum of those values." }, { "code": null, "e": 6794, "s": 6357, "text": "Now we used the module plotly.graph_objects with a different methodology [fig.add_trace()] and a different trace [go.Scatter()]. x= is the name of a column in data_frame representing the timeline while y= is the name of a column in data_frame representing a particular region. The stackgroup parameter is used to add the y values of the different traces in the same group. We must include mode = ‘lines’ to draw lines instead of points." }, { "code": null, "e": 8155, "s": 6794, "text": "import plotly.graph_objects as gofig2 = go.Figure()fig2.add_trace(go.Scatter( x= df_area['Year'], y = df_area['North America'], name = 'North America', mode = 'lines', line=dict(width=0.5, color='orange'), stackgroup = 'one'))fig2.add_trace(go.Scatter( x= df_area['Year'], y = df_area['Europe'], name = 'Europe', mode = 'lines', line=dict(width=0.5,color='lightgreen'), stackgroup = 'one'))fig2.add_trace(go.Scatter( x= df_area['Year'], y = df_area['Japan'], name = 'Japan', mode = 'lines', line=dict(width=0.5, color='blue'), stackgroup = 'one'))fig2.add_trace(go.Scatter( x= df_area['Year'], y = df_area['Rest of World'], name = 'Rest of World', mode = 'lines', line=dict(width=0.5, color='darkred'), stackgroup = 'one'))fig2.update_layout( title = \"PS4 Global Sales per Region\", title_font_size = 40, legend_font_size = 20, width = 1600, height = 1400)fig2.update_xaxes( title_text = 'Year', title_font=dict(size=30, family='Verdana', color='black'), tickfont=dict(family='Calibri', color='darkred', size=25))fig2.update_yaxes( title_text = \"Sales (MM)\", range = (0,160), title_font=dict(size=30, family='Verdana', color='black'), tickfont=dict(family='Calibri', color='darkred', size=25))fig2.write_image(path + \"figarea2.png\")fig2.show()" }, { "code": null, "e": 8315, "s": 8155, "text": "Let’s see if a percent stacked area chart improves the storytelling. We only need to make one small change: add groupnorm = ‘percent’ to the first add_trace()." }, { "code": null, "e": 9717, "s": 8315, "text": "fig3 = go.Figure()fig3.add_trace(go.Scatter( x= df_area['Year'], y = df_area['North America'], name = 'North America', mode = 'lines', line=dict(width=0.5, color='orange'), stackgroup = 'one', groupnorm = 'percent'))fig3.add_trace(go.Scatter( x= df_area['Year'], y = df_area['Europe'], name = 'Europe', mode = 'lines', line=dict(width=0.5,color='lightgreen'), stackgroup = 'one'))fig3.add_trace(go.Scatter( x= df_area['Year'], y = df_area['Japan'], name = 'Japan', mode = 'lines', line=dict(width=0.5, color='blue'), stackgroup = 'one'))fig3.add_trace(go.Scatter( x= df_area['Year'], y = df_area['Rest of World'], name = 'Rest of World', mode = 'lines', line=dict(width=0.5, color='darkred'), stackgroup = 'one'))fig3.update_layout( title = \"PS4 Global Sales per Region\", title_font_size = 40, legend_font_size = 20, yaxis=dict(type='linear',ticksuffix='%'), width = 1600, height = 1400)fig3.update_xaxes( title_text = 'Year', title_font=dict(size=30, family='Verdana', color='black'), tickfont=dict(family='Calibri', color='darkred', size=25))fig3.update_yaxes( title_text = \"Sales (%)\", range = (0,100), title_font=dict(size=30, family='Verdana', color='black'), tickfont=dict(family='Calibri', color='darkred', size=25))fig3.write_image(path + \"figarea3.png\")fig3.show()" }, { "code": null, "e": 9963, "s": 9717, "text": "Figure 3 is a Part-to-whole chart where each area indicates the percentage of each region referred to the total of the world sales. The emphasis is on the trend, how the percentage of each category changes over time, and not on the exact values." }, { "code": null, "e": 10175, "s": 9963, "text": "Finally, we can compare the regions with the highest sales using an overlapping area chart. Instead of stackgroup, we add fill = ‘tozeroy’ to the first add_trace() and fill = ‘tonexty’ to the second add_trace()." }, { "code": null, "e": 11188, "s": 10175, "text": "fig4 = go.Figure()fig4.add_trace(go.Scatter( x= df_area['Year'], y = df_area['North America'], name = 'North America', mode = 'lines', line=dict(width=0.5,color='lightgreen'), fill = 'tozeroy'))fig4.add_trace(go.Scatter( x= df_area['Year'], y = df_area['Europe'], name = 'Europe', mode = 'lines', line=dict(width=0.5, color='darkred'), fill = 'tonexty'))fig4.update_layout( title = \"PS4 Sales North America vs Europe\", title_font_size=40, legend_font_size = 20, width = 1600, height = 1400)fig4.update_xaxes( title_text = 'Year', title_font=dict(size=30, family='Verdana', color='black'), tickfont=dict(family='Calibri', color='darkred', size=25))fig4.update_yaxes( title_text = \"Sales (MM)\", range = (0,70), title_font=dict(size=30, family='Verdana', color='black'), tickfont=dict(family='Calibri', color='darkred', size=25))fig4.write_image(path + \"figarea4.png\")fig4.show()" }, { "code": null, "e": 11199, "s": 11188, "text": "To sum up:" }, { "code": null, "e": 11359, "s": 11199, "text": "We use Area Charts to communicate the overall trend and the relative contribution of each part to the whole without being concerned about showing exact values." }, { "code": null, "e": 11554, "s": 11359, "text": "We use the plotly.graph_objects module to add traces sequentially by means of the add_trace method. Then we manipulate the chart attributes through update_layout, update_xaxes, and update_yaxes." }, { "code": null, "e": 11647, "s": 11554, "text": "If you find this article of interest, please read my previous (https://medium.com/@dar.wtz):" }, { "code": null, "e": 11706, "s": 11647, "text": "“Scatter Plots with Plotly Express, Trendlines & Faceting”" }, { "code": null, "e": 11729, "s": 11706, "text": "towardsdatascience.com" } ]
Apache Derby - Syntax
This chapter gives you the syntax of all the Apache Derby SQL statements. All the statements start with any of the keywords like SELECT, INSERT, UPDATE, DELETE, ALTER, DROP, CREATE, USE, SHOW and all the statements end with a semicolon (;). The SQL statements of Apache Derby are case in sensitives including table names. CREATE TABLE table_name ( column_name1 column_data_type1 constraint (optional), column_name2 column_data_type2 constraint (optional), column_name3 column_data_type3 constraint (optional) ); DROP TABLE table_name; INSERT INTO table_name VALUES (column_name1, column_name2, ...); SELECT column_name, column_name, ... FROM table_name; UPDATE table_name SET column_name = value, column_name = value, ... WHERE conditions; DELETE FROM table_name WHERE condition; Describe table_name TRUNCATE TABLE table_name; ALTER TABLE table_name ADD COLUMN column_name column_type; ALTER TABLE table_name ADD CONSTRAINT constraint_name constraint (column_name); ALTER TABLE table_name DROP COLUMN column_name; ALTER TABLE table_name DROP CONSTRAINT constraint_name; SELECT * from table_name WHERE condition; or, DELETE from table_name WHERE condition; or, UPDATE table_name SET column_name = value WHERE condition; SELECT column1, column2, . . . table_name GROUP BY column1, column2, . . .; SELECT * FROM table_name ORDER BY column_name ASC|DESC. SELECT column1, column2 . . . from table_name GROUP BY column having condition; CTREATE INDEX index_name on table_name (column_name); CREATE UNIQUE INDEX index_name on table_name (column_name); CREATE INDEX index_name on table_name (column_name1, column_name2); SHOW INDEXES FROM table_name; DROP INDEX index_name; 46 Lectures 3.5 hours Arnab Chakraborty 23 Lectures 1.5 hours Mukund Kumar Mishra 16 Lectures 1 hours Nilay Mehta 52 Lectures 1.5 hours Bigdata Engineer 14 Lectures 1 hours Bigdata Engineer 23 Lectures 1 hours Bigdata Engineer Print Add Notes Bookmark this page
[ { "code": null, "e": 2254, "s": 2180, "text": "This chapter gives you the syntax of all the Apache Derby SQL statements." }, { "code": null, "e": 2421, "s": 2254, "text": "All the statements start with any of the keywords like SELECT, INSERT, UPDATE, DELETE, ALTER, DROP, CREATE, USE, SHOW and all the statements end with a semicolon (;)." }, { "code": null, "e": 2502, "s": 2421, "text": "The SQL statements of Apache Derby are case in sensitives including table names." }, { "code": null, "e": 2702, "s": 2502, "text": "CREATE TABLE table_name (\n column_name1 column_data_type1 constraint (optional),\n column_name2 column_data_type2 constraint (optional),\n column_name3 column_data_type3 constraint (optional)\n);\n" }, { "code": null, "e": 2726, "s": 2702, "text": "DROP TABLE table_name;\n" }, { "code": null, "e": 2792, "s": 2726, "text": "INSERT INTO table_name VALUES (column_name1, column_name2, ...);\n" }, { "code": null, "e": 2847, "s": 2792, "text": "SELECT column_name, column_name, ... FROM table_name;\n" }, { "code": null, "e": 2940, "s": 2847, "text": "UPDATE table_name\n SET column_name = value, column_name = value, ...\n WHERE conditions;\n" }, { "code": null, "e": 2981, "s": 2940, "text": "DELETE FROM table_name WHERE condition;\n" }, { "code": null, "e": 3002, "s": 2981, "text": "Describe table_name\n" }, { "code": null, "e": 3030, "s": 3002, "text": "TRUNCATE TABLE table_name;\n" }, { "code": null, "e": 3090, "s": 3030, "text": "ALTER TABLE table_name ADD COLUMN column_name column_type;\n" }, { "code": null, "e": 3171, "s": 3090, "text": "ALTER TABLE table_name ADD CONSTRAINT constraint_name constraint (column_name);\n" }, { "code": null, "e": 3220, "s": 3171, "text": "ALTER TABLE table_name DROP COLUMN column_name;\n" }, { "code": null, "e": 3277, "s": 3220, "text": "ALTER TABLE table_name DROP CONSTRAINT constraint_name;\n" }, { "code": null, "e": 3427, "s": 3277, "text": "SELECT * from table_name WHERE condition;\nor,\nDELETE from table_name WHERE condition;\nor,\nUPDATE table_name SET column_name = value WHERE condition;\n" }, { "code": null, "e": 3504, "s": 3427, "text": "SELECT column1, column2, . . . table_name GROUP BY column1, column2, . . .;\n" }, { "code": null, "e": 3561, "s": 3504, "text": "SELECT * FROM table_name ORDER BY column_name ASC|DESC.\n" }, { "code": null, "e": 3642, "s": 3561, "text": "SELECT column1, column2 . . . from table_name GROUP BY column having\ncondition;\n" }, { "code": null, "e": 3697, "s": 3642, "text": "CTREATE INDEX index_name on table_name (column_name);\n" }, { "code": null, "e": 3758, "s": 3697, "text": "CREATE UNIQUE INDEX index_name on table_name (column_name);\n" }, { "code": null, "e": 3827, "s": 3758, "text": "CREATE INDEX index_name on table_name (column_name1, column_name2);\n" }, { "code": null, "e": 3858, "s": 3827, "text": "SHOW INDEXES FROM table_name;\n" }, { "code": null, "e": 3882, "s": 3858, "text": "DROP INDEX index_name;\n" }, { "code": null, "e": 3917, "s": 3882, "text": "\n 46 Lectures \n 3.5 hours \n" }, { "code": null, "e": 3936, "s": 3917, "text": " Arnab Chakraborty" }, { "code": null, "e": 3971, "s": 3936, "text": "\n 23 Lectures \n 1.5 hours \n" }, { "code": null, "e": 3992, "s": 3971, "text": " Mukund Kumar Mishra" }, { "code": null, "e": 4025, "s": 3992, "text": "\n 16 Lectures \n 1 hours \n" }, { "code": null, "e": 4038, "s": 4025, "text": " Nilay Mehta" }, { "code": null, "e": 4073, "s": 4038, "text": "\n 52 Lectures \n 1.5 hours \n" }, { "code": null, "e": 4091, "s": 4073, "text": " Bigdata Engineer" }, { "code": null, "e": 4124, "s": 4091, "text": "\n 14 Lectures \n 1 hours \n" }, { "code": null, "e": 4142, "s": 4124, "text": " Bigdata Engineer" }, { "code": null, "e": 4175, "s": 4142, "text": "\n 23 Lectures \n 1 hours \n" }, { "code": null, "e": 4193, "s": 4175, "text": " Bigdata Engineer" }, { "code": null, "e": 4200, "s": 4193, "text": " Print" }, { "code": null, "e": 4211, "s": 4200, "text": " Add Notes" } ]
RxJava - ReplaySubject
ReplaySubject replays events/items to current and late Observers. Following is the declaration for io.reactivex.subjects.ReplaySubject<T> class − public final class ReplaySubject<T> extends Subject<T> Create the following Java program using any editor of your choice in, say, C:\> RxJava. import io.reactivex.subjects.ReplaySubject; public class ObservableTester { public static void main(String[] args) { final StringBuilder result1 = new StringBuilder(); final StringBuilder result2 = new StringBuilder(); ReplaySubject<String> subject = ReplaySubject.create(); subject.subscribe(value -> result1.append(value) ); subject.onNext("a"); subject.onNext("b"); subject.onNext("c"); subject.subscribe(value -> result2.append(value)); subject.onNext("d"); subject.onComplete(); //Output will be abcd System.out.println(result1); //Output will be abcd being ReplaySubject //as ReplaySubject emits all the items System.out.println(result2); } } Compile the class using javac compiler as follows − C:\RxJava>javac ObservableTester.java Now run the ObservableTester as follows − C:\RxJava>java ObservableTester It should produce the following output − abcd abcd Print Add Notes Bookmark this page
[ { "code": null, "e": 2467, "s": 2401, "text": "ReplaySubject replays events/items to current and late Observers." }, { "code": null, "e": 2547, "s": 2467, "text": "Following is the declaration for io.reactivex.subjects.ReplaySubject<T> class −" }, { "code": null, "e": 2603, "s": 2547, "text": "public final class ReplaySubject<T>\nextends Subject<T>\n" }, { "code": null, "e": 2691, "s": 2603, "text": "Create the following Java program using any editor of your choice in, say, C:\\> RxJava." }, { "code": null, "e": 3458, "s": 2691, "text": "import io.reactivex.subjects.ReplaySubject;\npublic class ObservableTester {\n public static void main(String[] args) { \n final StringBuilder result1 = new StringBuilder();\n final StringBuilder result2 = new StringBuilder(); \n\n ReplaySubject<String> subject = ReplaySubject.create(); \n subject.subscribe(value -> result1.append(value) ); \n subject.onNext(\"a\"); \n subject.onNext(\"b\"); \n subject.onNext(\"c\"); \n subject.subscribe(value -> result2.append(value)); \n subject.onNext(\"d\"); \n subject.onComplete();\n\n //Output will be abcd\n System.out.println(result1);\n //Output will be abcd being ReplaySubject\n //as ReplaySubject emits all the items\n System.out.println(result2);\n }\n}" }, { "code": null, "e": 3510, "s": 3458, "text": "Compile the class using javac compiler as follows −" }, { "code": null, "e": 3549, "s": 3510, "text": "C:\\RxJava>javac ObservableTester.java\n" }, { "code": null, "e": 3591, "s": 3549, "text": "Now run the ObservableTester as follows −" }, { "code": null, "e": 3624, "s": 3591, "text": "C:\\RxJava>java ObservableTester\n" }, { "code": null, "e": 3665, "s": 3624, "text": "It should produce the following output −" }, { "code": null, "e": 3676, "s": 3665, "text": "abcd\nabcd\n" }, { "code": null, "e": 3683, "s": 3676, "text": " Print" }, { "code": null, "e": 3694, "s": 3683, "text": " Add Notes" } ]