title
stringlengths
3
221
text
stringlengths
17
477k
parsed
listlengths
0
3.17k
Spatial Interpolation With Kernels | by Arun Jagota | Towards Data Science
California has been on fire recently. Well, actually fires. Fire breeds smoke. That there’s been plenty of. A heat map revealing the air quality in various regions is clearly useful. What are the modeling issues in building such a heat map? Seriously, entrepreneurs are pondering this question [1]. Well, we do have air quality sensors. But not everywhere. We want to estimate air quality in sparsely covered areas from measurements on nearby sensors. We’ll call this spatial interpolation. There are also measurement errors. Sensors have varying quality. The expensive sensors are more accurate, but also fewer. So their coverage is sparse. Inexpensive sensors are much more abundant. However, less accurate. Given these trade-offs, we should combine all data (within sufficient proximity) rather than choosing some over others. Taking into account sensor locations and their varying error rates. There can also be anomalous readings. Sensors sometimes return whacky results. Or get sick, even die. They can also produce biased results, i.e., those that are consistently off. Anomalies need detection so they can be discarded. Biases need estimation so they can be corrected. Frequent anomalies from the same sensor are symptoms of malfunction. All this is interesting, right? Useful as well. Spatial interpolation also applies to temperature, wind speed, amount of rainfall, humidity, to name a few. Let’s dig in. Problem Statement We have sensors located at n points (x1,y1), ..., (xn, yn). We will refer to anyone such a point as ij. The sensor at the location ij emits a reading Sij. We view this reading as a corrupted version of the unknown true value Tij at that location. We seek to estimate Txy at every point (x, y) in the region from these readings. Example: Say we have two sensors in the San Francisco bay area. One in San Francisco, the other in San Jose. We are interested in estimating air quality in between. (Of course, we only have two sensors, so our estimates may not be great.) Think of this as one-dimensional spatial interpolation. Estimate air qualities on the line connecting San Francisco to San Jose. Kernels: Let’s now discuss kernels. To each location ij fitted with a sensor, we attach a kernel Kij. Kij weighs the influence of the reading Sij to locations near ij. The influence decays with distance. Formally, we express this weight as K(d(xy, ij)). Here d(xy, ij) denotes the distance between xy and ij. K(d) decreases with d, with K(0) being 1. A natural choice for K(d) is e^-ad, where a is a parameter that controls the rate of decay of the influence with distance. Example: In our SF-SJ example, say we set the Kernel K(d) to be 1/(a*d+1) where d is in units of miles. Consider a = 1. The influence of the reading in SF would be 1⁄2 =50% one mile away from SF, and 1⁄4 =25% two miles away from SF. Why this kernel function, and why a=1 over some other choice? As we’ll see soon, the interpolation is not particularly sensitive to the decisions we make here. First Interpolator Consider any point xy. Consider the AQIs { Sij } measured at sensors located near xy. The weighted average of these measurements is a good estimate of the AQI at xy. Sensors closer to xy influence the estimate more. More formally S^xy = sum_ij pij(xy)*Sij where pij(xy) = K(d(ij, xy))/ sum_i’j’ K(d(i’j’,xy)) Here S^xy denotes the intensity estimate obtained at xy this way. Example: Consider our SF-SJ example, with the Kernel function we chose earlier. Say SF and SJ are 50 miles apart. Consider a point midway between the two, which we will call San Mateo (SM). We want to estimate the AQI at SM from SF and SJ readings, which we will take to be 160 and 180 AQI, respectively. (AQI is short for “air quality index.”) K(SM,SF) = K(SM,SJ) = 1/(25+1)=1/26 From this, we get pSF(SM) = pSJ(SM) = 1⁄2 So our estimated AQI at SM is 170, the average of 160 and 180. This example also reveals that the interpolation is not as sensitive to the Kernel function's choice and its parameters as we might have imagined. What’s important are the probabilities pij derived from the Kernel function’s values, not the values themselves. We are good so long as the Kernel function helps us estimate the relative influences the readings from the various nearby sensors should have towards the interpolation. Incorporating Domain Knowledge Say we have some knowledge about the various sensors. We might know a sensor’s price or brand. From this information, we might be able to estimate its error rate. Even better, perhaps the error rate has already been estimated from tests. Companies selling premium sensors are inclined to do so, to highlight their value propositions. Below is a simple heuristic extension of pij to leverage this knowledge. pij = K(d(ij, xy)*wij Here wij is a positive weight that captures the quality of the sensor at location ij. Higher value equates to higher quality. With this addition, a low-quality sensor influences S^xy less than a high-quality one. That said, the cumulative influence of multiple low-quality sensors in nearby locations giving similar readings is as if there were a single higher-quality sensor with a similar reading. This is as desired. Example: Say we set wSF = 2 and wSJ = 1. We trust the sensor at San Francisco twice as much as the one at San Jose. This modifies the probabilities to pSF(SM) = 2⁄3, pSJ(SM) = 1⁄3. Consequently, our AQI estimate at SM is about 166, closer to the reading in SF. Coping With Anomalous Readings Sensors may sometimes give anomalous readings. By definition, such readings can be “off the chart.” Left unchecked, they can significantly skew interpolations in their proximity. Clearly, we should detect anomalous readings and discount them. To do this, we’ll add a new term to pij: pij = K(d(ij, xy)*wij*aij Here aij is an anomaly discount weight. Its value is close to 1 if the sensor’s reading is deemed normal and close to 0 if its deemed anomalous. How can we estimate aij? The basic idea is simple. If most neighboring sensors have similar readings and differ very much from ij’s, ij’s is probably anomalous. In more detail, obtain S^ij at that sensor based on the readings at neighboring sensors using the formula described earlier. Be sure to exclude ij itself from contributing to this formula. Compare S^ij with Sij. If the two are far apart, the reading at ij is likely anomalous. This can be enhanced further to take into account the variability in the readings at the neighboring sensors. The more similar the neighboring sensors' readings are, the higher the confidence that the sensor (whose reading differs significantly) is anomalous. Interestingly, the modeling here is similar to the modeling described in [3], specifically denoising images. The two-sheet architecture described there is interesting to look into in this connection. Example: Let’s add a new sensor to our SF-SJ example, at SM, midway between the two. Also, let’s revert to trusting the SF and SJ sensors equally. Say the SM's sensor reading is 5 AQI, whereas the SF and SJ readings were 180 and 160 AQI. The AQI estimate at SM from the SF and SJ readings is 170. 170 is very different from 5. This calls into question the SM reading. Given this, when estimating the AQI somewhere between SF and SJ (say in Palo Alto) from the three sensors, we might want to discard the SM sensor’s reading. Detecting Temporal Changes A sensor may have been reporting similar readings over a time period, then suddenly reports a very different reading. Something happened. If nearby sensors did not report an abrupt change simultaneously, whatever happened is likely local to this sensor. Using such temporal information and the spatial information, we can often increase the confidence in our inference that the reading is anomalous. Example: Consider our trio of sensors at SF, SM, and SJ. Say we measured their readings every hour over the past 5 hours and got the following: Hour 1 2 3 4 5SF reading 159 163 161 166 157SM reading 170 168 174 169 5SJ reading 181 178 172 178 182 Clearly, by looking at the three sensors' readings over the entire duration (not just at hour=5), we can say with higher confidence that the reading in bold is anomalous. Using such temporal information can also help assess whether a sensor seems biased. Consider a variant of the above example. Hour 1 2 3 4 5SF reading 159 163 161 166 157SM reading 129 121 125 122 124SJ reading 181 178 172 178 182 Either the SM sensor is biased, or there really is something else going on in SM to account for the consistently lower reading in SM than those in SF and SJ. Either way, this is good to know. Further Reading How accurate is AirVisual’s air quality data? | AirVisual Support CenterSpatial interpolationMarkov Random Fields And Image Processing | by Arun Jagota | Aug 2020 How accurate is AirVisual’s air quality data? | AirVisual Support Center Spatial interpolation Markov Random Fields And Image Processing | by Arun Jagota | Aug 2020
[ { "code": null, "e": 279, "s": 171, "text": "California has been on fire recently. Well, actually fires. Fire breeds smoke. That there’s been plenty of." }, { "code": null, "e": 470, "s": 279, "text": "A heat map revealing the air quality in various regions is clearly useful. What are the modeling issues in building such a heat map? Seriously, entrepreneurs are pondering this question [1]." }, { "code": null, "e": 662, "s": 470, "text": "Well, we do have air quality sensors. But not everywhere. We want to estimate air quality in sparsely covered areas from measurements on nearby sensors. We’ll call this spatial interpolation." }, { "code": null, "e": 881, "s": 662, "text": "There are also measurement errors. Sensors have varying quality. The expensive sensors are more accurate, but also fewer. So their coverage is sparse. Inexpensive sensors are much more abundant. However, less accurate." }, { "code": null, "e": 1069, "s": 881, "text": "Given these trade-offs, we should combine all data (within sufficient proximity) rather than choosing some over others. Taking into account sensor locations and their varying error rates." }, { "code": null, "e": 1248, "s": 1069, "text": "There can also be anomalous readings. Sensors sometimes return whacky results. Or get sick, even die. They can also produce biased results, i.e., those that are consistently off." }, { "code": null, "e": 1417, "s": 1248, "text": "Anomalies need detection so they can be discarded. Biases need estimation so they can be corrected. Frequent anomalies from the same sensor are symptoms of malfunction." }, { "code": null, "e": 1573, "s": 1417, "text": "All this is interesting, right? Useful as well. Spatial interpolation also applies to temperature, wind speed, amount of rainfall, humidity, to name a few." }, { "code": null, "e": 1587, "s": 1573, "text": "Let’s dig in." }, { "code": null, "e": 1605, "s": 1587, "text": "Problem Statement" }, { "code": null, "e": 1933, "s": 1605, "text": "We have sensors located at n points (x1,y1), ..., (xn, yn). We will refer to anyone such a point as ij. The sensor at the location ij emits a reading Sij. We view this reading as a corrupted version of the unknown true value Tij at that location. We seek to estimate Txy at every point (x, y) in the region from these readings." }, { "code": null, "e": 2172, "s": 1933, "text": "Example: Say we have two sensors in the San Francisco bay area. One in San Francisco, the other in San Jose. We are interested in estimating air quality in between. (Of course, we only have two sensors, so our estimates may not be great.)" }, { "code": null, "e": 2301, "s": 2172, "text": "Think of this as one-dimensional spatial interpolation. Estimate air qualities on the line connecting San Francisco to San Jose." }, { "code": null, "e": 2775, "s": 2301, "text": "Kernels: Let’s now discuss kernels. To each location ij fitted with a sensor, we attach a kernel Kij. Kij weighs the influence of the reading Sij to locations near ij. The influence decays with distance. Formally, we express this weight as K(d(xy, ij)). Here d(xy, ij) denotes the distance between xy and ij. K(d) decreases with d, with K(0) being 1. A natural choice for K(d) is e^-ad, where a is a parameter that controls the rate of decay of the influence with distance." }, { "code": null, "e": 3008, "s": 2775, "text": "Example: In our SF-SJ example, say we set the Kernel K(d) to be 1/(a*d+1) where d is in units of miles. Consider a = 1. The influence of the reading in SF would be 1⁄2 =50% one mile away from SF, and 1⁄4 =25% two miles away from SF." }, { "code": null, "e": 3168, "s": 3008, "text": "Why this kernel function, and why a=1 over some other choice? As we’ll see soon, the interpolation is not particularly sensitive to the decisions we make here." }, { "code": null, "e": 3187, "s": 3168, "text": "First Interpolator" }, { "code": null, "e": 3403, "s": 3187, "text": "Consider any point xy. Consider the AQIs { Sij } measured at sensors located near xy. The weighted average of these measurements is a good estimate of the AQI at xy. Sensors closer to xy influence the estimate more." }, { "code": null, "e": 3417, "s": 3403, "text": "More formally" }, { "code": null, "e": 3443, "s": 3417, "text": "S^xy = sum_ij pij(xy)*Sij" }, { "code": null, "e": 3449, "s": 3443, "text": "where" }, { "code": null, "e": 3496, "s": 3449, "text": "pij(xy) = K(d(ij, xy))/ sum_i’j’ K(d(i’j’,xy))" }, { "code": null, "e": 3562, "s": 3496, "text": "Here S^xy denotes the intensity estimate obtained at xy this way." }, { "code": null, "e": 3907, "s": 3562, "text": "Example: Consider our SF-SJ example, with the Kernel function we chose earlier. Say SF and SJ are 50 miles apart. Consider a point midway between the two, which we will call San Mateo (SM). We want to estimate the AQI at SM from SF and SJ readings, which we will take to be 160 and 180 AQI, respectively. (AQI is short for “air quality index.”)" }, { "code": null, "e": 3943, "s": 3907, "text": "K(SM,SF) = K(SM,SJ) = 1/(25+1)=1/26" }, { "code": null, "e": 3961, "s": 3943, "text": "From this, we get" }, { "code": null, "e": 3985, "s": 3961, "text": "pSF(SM) = pSJ(SM) = 1⁄2" }, { "code": null, "e": 4048, "s": 3985, "text": "So our estimated AQI at SM is 170, the average of 160 and 180." }, { "code": null, "e": 4477, "s": 4048, "text": "This example also reveals that the interpolation is not as sensitive to the Kernel function's choice and its parameters as we might have imagined. What’s important are the probabilities pij derived from the Kernel function’s values, not the values themselves. We are good so long as the Kernel function helps us estimate the relative influences the readings from the various nearby sensors should have towards the interpolation." }, { "code": null, "e": 4508, "s": 4477, "text": "Incorporating Domain Knowledge" }, { "code": null, "e": 4842, "s": 4508, "text": "Say we have some knowledge about the various sensors. We might know a sensor’s price or brand. From this information, we might be able to estimate its error rate. Even better, perhaps the error rate has already been estimated from tests. Companies selling premium sensors are inclined to do so, to highlight their value propositions." }, { "code": null, "e": 4915, "s": 4842, "text": "Below is a simple heuristic extension of pij to leverage this knowledge." }, { "code": null, "e": 4937, "s": 4915, "text": "pij = K(d(ij, xy)*wij" }, { "code": null, "e": 5063, "s": 4937, "text": "Here wij is a positive weight that captures the quality of the sensor at location ij. Higher value equates to higher quality." }, { "code": null, "e": 5357, "s": 5063, "text": "With this addition, a low-quality sensor influences S^xy less than a high-quality one. That said, the cumulative influence of multiple low-quality sensors in nearby locations giving similar readings is as if there were a single higher-quality sensor with a similar reading. This is as desired." }, { "code": null, "e": 5618, "s": 5357, "text": "Example: Say we set wSF = 2 and wSJ = 1. We trust the sensor at San Francisco twice as much as the one at San Jose. This modifies the probabilities to pSF(SM) = 2⁄3, pSJ(SM) = 1⁄3. Consequently, our AQI estimate at SM is about 166, closer to the reading in SF." }, { "code": null, "e": 5649, "s": 5618, "text": "Coping With Anomalous Readings" }, { "code": null, "e": 5892, "s": 5649, "text": "Sensors may sometimes give anomalous readings. By definition, such readings can be “off the chart.” Left unchecked, they can significantly skew interpolations in their proximity. Clearly, we should detect anomalous readings and discount them." }, { "code": null, "e": 5933, "s": 5892, "text": "To do this, we’ll add a new term to pij:" }, { "code": null, "e": 5959, "s": 5933, "text": "pij = K(d(ij, xy)*wij*aij" }, { "code": null, "e": 6104, "s": 5959, "text": "Here aij is an anomaly discount weight. Its value is close to 1 if the sensor’s reading is deemed normal and close to 0 if its deemed anomalous." }, { "code": null, "e": 6265, "s": 6104, "text": "How can we estimate aij? The basic idea is simple. If most neighboring sensors have similar readings and differ very much from ij’s, ij’s is probably anomalous." }, { "code": null, "e": 6542, "s": 6265, "text": "In more detail, obtain S^ij at that sensor based on the readings at neighboring sensors using the formula described earlier. Be sure to exclude ij itself from contributing to this formula. Compare S^ij with Sij. If the two are far apart, the reading at ij is likely anomalous." }, { "code": null, "e": 6802, "s": 6542, "text": "This can be enhanced further to take into account the variability in the readings at the neighboring sensors. The more similar the neighboring sensors' readings are, the higher the confidence that the sensor (whose reading differs significantly) is anomalous." }, { "code": null, "e": 7002, "s": 6802, "text": "Interestingly, the modeling here is similar to the modeling described in [3], specifically denoising images. The two-sheet architecture described there is interesting to look into in this connection." }, { "code": null, "e": 7149, "s": 7002, "text": "Example: Let’s add a new sensor to our SF-SJ example, at SM, midway between the two. Also, let’s revert to trusting the SF and SJ sensors equally." }, { "code": null, "e": 7370, "s": 7149, "text": "Say the SM's sensor reading is 5 AQI, whereas the SF and SJ readings were 180 and 160 AQI. The AQI estimate at SM from the SF and SJ readings is 170. 170 is very different from 5. This calls into question the SM reading." }, { "code": null, "e": 7527, "s": 7370, "text": "Given this, when estimating the AQI somewhere between SF and SJ (say in Palo Alto) from the three sensors, we might want to discard the SM sensor’s reading." }, { "code": null, "e": 7554, "s": 7527, "text": "Detecting Temporal Changes" }, { "code": null, "e": 7808, "s": 7554, "text": "A sensor may have been reporting similar readings over a time period, then suddenly reports a very different reading. Something happened. If nearby sensors did not report an abrupt change simultaneously, whatever happened is likely local to this sensor." }, { "code": null, "e": 7954, "s": 7808, "text": "Using such temporal information and the spatial information, we can often increase the confidence in our inference that the reading is anomalous." }, { "code": null, "e": 8098, "s": 7954, "text": "Example: Consider our trio of sensors at SF, SM, and SJ. Say we measured their readings every hour over the past 5 hours and got the following:" }, { "code": null, "e": 8222, "s": 8098, "text": "Hour 1 2 3 4 5SF reading 159 163 161 166 157SM reading 170 168 174 169 5SJ reading 181 178 172 178 182" }, { "code": null, "e": 8393, "s": 8222, "text": "Clearly, by looking at the three sensors' readings over the entire duration (not just at hour=5), we can say with higher confidence that the reading in bold is anomalous." }, { "code": null, "e": 8518, "s": 8393, "text": "Using such temporal information can also help assess whether a sensor seems biased. Consider a variant of the above example." }, { "code": null, "e": 8642, "s": 8518, "text": "Hour 1 2 3 4 5SF reading 159 163 161 166 157SM reading 129 121 125 122 124SJ reading 181 178 172 178 182" }, { "code": null, "e": 8834, "s": 8642, "text": "Either the SM sensor is biased, or there really is something else going on in SM to account for the consistently lower reading in SM than those in SF and SJ. Either way, this is good to know." }, { "code": null, "e": 8850, "s": 8834, "text": "Further Reading" }, { "code": null, "e": 9013, "s": 8850, "text": "How accurate is AirVisual’s air quality data? | AirVisual Support CenterSpatial interpolationMarkov Random Fields And Image Processing | by Arun Jagota | Aug 2020" }, { "code": null, "e": 9086, "s": 9013, "text": "How accurate is AirVisual’s air quality data? | AirVisual Support Center" }, { "code": null, "e": 9108, "s": 9086, "text": "Spatial interpolation" } ]
PyCaret is an open-source, low-code machine learning library and end-to-end model management tool built in Python for automating ML workflows | Towards Data Science
Time series data is data collected on the same subject at different points in time, such as GDP of a country by year, a stock price of a particular company over a period of time, or your own heartbeat recorded at each second, as a matter of fact, anything that you can capture continuously at different time-intervals is a time series data. See below as an example of time series data, the chart below is the daily stock price of Tesla Inc. (Ticker Symbol: TSLA) for last year. The y-axis on the right-hand side is the value in US$ (The last point on the chart i.e. $701.91 is the latest stock price as of the writing of this article on April 12, 2021). On the other hand, more conventional datasets such as customer information, product information, company information, etc. which store information at a single point in time are known as cross-sectional data. See the example below of a dataset that tracks America’s best-selling electric cars in the first half of 2020. Notice that instead of tracking the cars sold over a period of time, the chart below tracks different cars such as Tesla, Chevy, and Nissan in the same time period. It is not very hard to distinguish the difference between cross-sectional and time-series data as the objective of analysis for both datasets are widely different. For the first analysis, we were interested in tracking Tesla stock price over a period of time, whereas for the latter, we wanted to analyze different companies in the same time period i.e. first half of 2020. However, a typical real-world dataset is likely to be a hybrid. Imagine a retailer like Walmart that sold thousand’s of products every day. If you analyze the sale by-product on a particular day, for example, if you want to find out what’s the number 1 selling item on Christmas eve, this will be a cross-sectional analysis. As opposed to, If you want to find out the sale of one particular item such as PS4 over a period of time (let’s say last 5 years), this now becomes a time-series analysis. Precisely, the objective of the analysis for time-series and cross-sectional data is different and a real-world dataset is likely to be a hybrid of both time-series as well as cross-sectional data. Time series forecasting is exactly what it sounds like i.e. predicting the future unknown values. However, unlike sci-fi movies, it’s a little less thrilling in the real world. It involves the collection of historical data, preparing it for algorithms to consume (the algorithm is simply put the maths that goes behind the scene), and then predict the future values based on patterns learned from the historical data. Can you think of a reason why would companies or anybody be interested in forecasting future values for any time series (GDP, monthly sales, inventory, unemployment, global temperatures, etc.). Let me give you some business perspective: A retailer may be interested in predicting future sales at an SKU level for planning and budgeting. A small merchant may be interested in forecasting sales by store, so it can schedule the right resources (more people during busy periods and vice versa). A software giant like Google may be interested in knowing the busiest hour of the day or busiest day of the week so that it can schedule server resources accordingly. The health department may be interested in predicting the cumulative COVID vaccination administered so that it can know the point of consolidation where herd immunity is expected to kick in. Time series forecasting can broadly be categorized into the following categories: Classical / Statistical Models — Moving Averages, Exponential smoothing, ARIMA, SARIMA, TBATS Machine Learning — Linear Regression, XGBoost, Random Forest, or any ML model with reduction methods Deep Learning — RNN, LSTM This tutorial is focused on forecasting time series using Machine Learning. For this tutorial, I will use the Regression Module of an open-source, low-code machine library in Python called PyCaret. If you haven’t used PyCaret before, you can get quickly started here. Although, you don’t require any prior knowledge of PyCaret to follow along with this tutorial. PyCaret Regression Module is a supervised machine learning module used for estimating the relationships between a dependent variable (often called the ‘outcome variable’, or ‘target’) and one or more independent variables (often called ‘features’, or ‘predictors’). The objective of regression is to predict continuous values such as sales amount, quantity, temperature, number of customers, etc. All modules in PyCaret provide many pre-processing features to prepare the data for modeling through the setup function. It has over 25 ready-to-use algorithms and several plots to analyze the performance of trained models. For this tutorial, I have used the US airline passengers dataset. You can download the dataset from Kaggle. This dataset provides monthly totals of US airline passengers from 1949 to 1960. # read csv fileimport pandas as pddata = pd.read_csv('AirPassengers.csv')data['Date'] = pd.to_datetime(data['Date'])data.head() # create 12 month moving averagedata['MA12'] = data['Passengers'].rolling(12).mean()# plot the data and MAimport plotly.express as pxfig = px.line(data, x="Date", y=["Passengers", "MA12"], template = 'plotly_dark')fig.show() Since machine learning algorithms cannot directly deal with dates, let’s extract some simple features from dates such as month and year, and drop the original date column. # extract month and year from datesdata['Month'] = [i.month for i in data['Date']]data['Year'] = [i.year for i in data['Date']]# create a sequence of numbersdata['Series'] = np.arange(1,len(data)+1)# drop unnecessary columns and re-arrangedata.drop(['Date', 'MA12'], axis=1, inplace=True)data = data[['Series', 'Year', 'Month', 'Passengers']] # check the head of the datasetdata.head() # split data into train-test settrain = data[data['Year'] < 1960]test = data[data['Year'] >= 1960]# check shapetrain.shape, test.shape>>> ((132, 4), (12, 4)) I have manually split the dataset before initializing the setup . An alternate would be to pass the entire dataset to PyCaret and let it handle the split, in which case you will have to pass data_split_shuffle = False in the setup function to avoid shuffling the dataset before the split. Now it’s time to initialize the setup function, where we will explicitly pass the training data, test data, and cross-validation strategy using the fold_strategy parameter. # import the regression modulefrom pycaret.regression import *# initialize setups = setup(data = train, test_data = test, target = 'Passengers', fold_strategy = 'timeseries', numeric_features = ['Year', 'Series'], fold = 3, transform_target = True, session_id = 123) best = compare_models(sort = 'MAE') The best model based on cross-validated MAE is Least Angle Regression (MAE: 22.3). Let’s check the score on the test set. prediction_holdout = predict_model(best); MAE on the test set is 12% higher than the cross-validated MAE. Not so good, but we will work with it. Let’s plot the actual and predicted lines to visualize the fit. # generate predictions on the original datasetpredictions = predict_model(best, data=data)# add a date column in the datasetpredictions['Date'] = pd.date_range(start='1949-01-01', end = '1960-12-01', freq = 'MS')# line plotfig = px.line(predictions, x='Date', y=["Passengers", "Label"], template = 'plotly_dark')# add a vertical rectange for test-set separationfig.add_vrect(x0="1960-01-01", x1="1960-12-01", fillcolor="grey", opacity=0.25, line_width=0)fig.show() The grey backdrop towards the end is the test period (i.e. 1960). Now let’s finalize the model i.e. train the best model i.e. Least Angle Regression on the entire dataset (this time, including the test set). final_best = finalize_model(best) Now that we have trained our model on the entire dataset (1949 to 1960), let’s predict five years out in the future through 1964. To use our final model to generate future predictions, we first need to create a dataset consisting of the Month, Year, Series column on the future dates. future_dates = pd.date_range(start = '1961-01-01', end = '1965-01-01', freq = 'MS')future_df = pd.DataFrame()future_df['Month'] = [i.month for i in future_dates]future_df['Year'] = [i.year for i in future_dates] future_df['Series'] = np.arange(145 (145+len(future_dates)))future_df.head() Now, let’s use the future_df to score and generate predictions. predictions_future = predict_model(final_best, data=future_df)predictions_future.head() concat_df = pd.concat([data,predictions_future], axis=0)concat_df_i = pd.date_range(start='1949-01-01', end = '1965-01-01', freq = 'MS')concat_df.set_index(concat_df_i, inplace=True)fig = px.line(concat_df, x=concat_df.index, y=["Passengers", "Label"], template = 'plotly_dark')fig.show() I hope you find this tutorial easy. If you think you are ready for the next level, you can check out my advanced time-series tutorial on Multiple Time Series Forecasting with PyCaret. I will soon be writing a tutorial on unsupervised anomaly detection on time-series data using PyCaret Anomaly Detection Module. If you would like to get more updates, you can follow me on Medium, LinkedIn, and Twitter. There is no limit to what you can achieve using this lightweight workflow automation library in Python. If you find this useful, please do not forget to give ⭐️ on our GitHub repository. To learn more about PyCaret follow us on LinkedIn and Youtube. Join us on our slack channel. Invite link here. Build your own AutoML in Power BI using PyCaret 2.0Deploy Machine Learning Pipeline on Azure using DockerDeploy Machine Learning Pipeline on Google Kubernetes EngineDeploy Machine Learning Pipeline on AWS FargateBuild and deploy your first machine learning web appDeploy PyCaret and Streamlit app using AWS Fargate serverlessBuild and deploy machine learning web app using PyCaret and StreamlitDeploy Machine Learning App built using Streamlit and PyCaret on GKE DocumentationBlogGitHubStackOverflowInstall PyCaretNotebook TutorialsContribute in PyCaret Click on the links below to see the documentation and working examples. ClassificationRegressionClusteringAnomaly DetectionNatural Language ProcessingAssociation Rule Mining
[ { "code": null, "e": 513, "s": 172, "text": "Time series data is data collected on the same subject at different points in time, such as GDP of a country by year, a stock price of a particular company over a period of time, or your own heartbeat recorded at each second, as a matter of fact, anything that you can capture continuously at different time-intervals is a time series data." }, { "code": null, "e": 826, "s": 513, "text": "See below as an example of time series data, the chart below is the daily stock price of Tesla Inc. (Ticker Symbol: TSLA) for last year. The y-axis on the right-hand side is the value in US$ (The last point on the chart i.e. $701.91 is the latest stock price as of the writing of this article on April 12, 2021)." }, { "code": null, "e": 1034, "s": 826, "text": "On the other hand, more conventional datasets such as customer information, product information, company information, etc. which store information at a single point in time are known as cross-sectional data." }, { "code": null, "e": 1310, "s": 1034, "text": "See the example below of a dataset that tracks America’s best-selling electric cars in the first half of 2020. Notice that instead of tracking the cars sold over a period of time, the chart below tracks different cars such as Tesla, Chevy, and Nissan in the same time period." }, { "code": null, "e": 1684, "s": 1310, "text": "It is not very hard to distinguish the difference between cross-sectional and time-series data as the objective of analysis for both datasets are widely different. For the first analysis, we were interested in tracking Tesla stock price over a period of time, whereas for the latter, we wanted to analyze different companies in the same time period i.e. first half of 2020." }, { "code": null, "e": 2181, "s": 1684, "text": "However, a typical real-world dataset is likely to be a hybrid. Imagine a retailer like Walmart that sold thousand’s of products every day. If you analyze the sale by-product on a particular day, for example, if you want to find out what’s the number 1 selling item on Christmas eve, this will be a cross-sectional analysis. As opposed to, If you want to find out the sale of one particular item such as PS4 over a period of time (let’s say last 5 years), this now becomes a time-series analysis." }, { "code": null, "e": 2379, "s": 2181, "text": "Precisely, the objective of the analysis for time-series and cross-sectional data is different and a real-world dataset is likely to be a hybrid of both time-series as well as cross-sectional data." }, { "code": null, "e": 2797, "s": 2379, "text": "Time series forecasting is exactly what it sounds like i.e. predicting the future unknown values. However, unlike sci-fi movies, it’s a little less thrilling in the real world. It involves the collection of historical data, preparing it for algorithms to consume (the algorithm is simply put the maths that goes behind the scene), and then predict the future values based on patterns learned from the historical data." }, { "code": null, "e": 3034, "s": 2797, "text": "Can you think of a reason why would companies or anybody be interested in forecasting future values for any time series (GDP, monthly sales, inventory, unemployment, global temperatures, etc.). Let me give you some business perspective:" }, { "code": null, "e": 3134, "s": 3034, "text": "A retailer may be interested in predicting future sales at an SKU level for planning and budgeting." }, { "code": null, "e": 3289, "s": 3134, "text": "A small merchant may be interested in forecasting sales by store, so it can schedule the right resources (more people during busy periods and vice versa)." }, { "code": null, "e": 3456, "s": 3289, "text": "A software giant like Google may be interested in knowing the busiest hour of the day or busiest day of the week so that it can schedule server resources accordingly." }, { "code": null, "e": 3647, "s": 3456, "text": "The health department may be interested in predicting the cumulative COVID vaccination administered so that it can know the point of consolidation where herd immunity is expected to kick in." }, { "code": null, "e": 3729, "s": 3647, "text": "Time series forecasting can broadly be categorized into the following categories:" }, { "code": null, "e": 3823, "s": 3729, "text": "Classical / Statistical Models — Moving Averages, Exponential smoothing, ARIMA, SARIMA, TBATS" }, { "code": null, "e": 3924, "s": 3823, "text": "Machine Learning — Linear Regression, XGBoost, Random Forest, or any ML model with reduction methods" }, { "code": null, "e": 3950, "s": 3924, "text": "Deep Learning — RNN, LSTM" }, { "code": null, "e": 4313, "s": 3950, "text": "This tutorial is focused on forecasting time series using Machine Learning. For this tutorial, I will use the Regression Module of an open-source, low-code machine library in Python called PyCaret. If you haven’t used PyCaret before, you can get quickly started here. Although, you don’t require any prior knowledge of PyCaret to follow along with this tutorial." }, { "code": null, "e": 4579, "s": 4313, "text": "PyCaret Regression Module is a supervised machine learning module used for estimating the relationships between a dependent variable (often called the ‘outcome variable’, or ‘target’) and one or more independent variables (often called ‘features’, or ‘predictors’)." }, { "code": null, "e": 4934, "s": 4579, "text": "The objective of regression is to predict continuous values such as sales amount, quantity, temperature, number of customers, etc. All modules in PyCaret provide many pre-processing features to prepare the data for modeling through the setup function. It has over 25 ready-to-use algorithms and several plots to analyze the performance of trained models." }, { "code": null, "e": 5123, "s": 4934, "text": "For this tutorial, I have used the US airline passengers dataset. You can download the dataset from Kaggle. This dataset provides monthly totals of US airline passengers from 1949 to 1960." }, { "code": null, "e": 5251, "s": 5123, "text": "# read csv fileimport pandas as pddata = pd.read_csv('AirPassengers.csv')data['Date'] = pd.to_datetime(data['Date'])data.head()" }, { "code": null, "e": 5476, "s": 5251, "text": "# create 12 month moving averagedata['MA12'] = data['Passengers'].rolling(12).mean()# plot the data and MAimport plotly.express as pxfig = px.line(data, x=\"Date\", y=[\"Passengers\", \"MA12\"], template = 'plotly_dark')fig.show()" }, { "code": null, "e": 5648, "s": 5476, "text": "Since machine learning algorithms cannot directly deal with dates, let’s extract some simple features from dates such as month and year, and drop the original date column." }, { "code": null, "e": 6034, "s": 5648, "text": "# extract month and year from datesdata['Month'] = [i.month for i in data['Date']]data['Year'] = [i.year for i in data['Date']]# create a sequence of numbersdata['Series'] = np.arange(1,len(data)+1)# drop unnecessary columns and re-arrangedata.drop(['Date', 'MA12'], axis=1, inplace=True)data = data[['Series', 'Year', 'Month', 'Passengers']] # check the head of the datasetdata.head()" }, { "code": null, "e": 6192, "s": 6034, "text": "# split data into train-test settrain = data[data['Year'] < 1960]test = data[data['Year'] >= 1960]# check shapetrain.shape, test.shape>>> ((132, 4), (12, 4))" }, { "code": null, "e": 6481, "s": 6192, "text": "I have manually split the dataset before initializing the setup . An alternate would be to pass the entire dataset to PyCaret and let it handle the split, in which case you will have to pass data_split_shuffle = False in the setup function to avoid shuffling the dataset before the split." }, { "code": null, "e": 6654, "s": 6481, "text": "Now it’s time to initialize the setup function, where we will explicitly pass the training data, test data, and cross-validation strategy using the fold_strategy parameter." }, { "code": null, "e": 6921, "s": 6654, "text": "# import the regression modulefrom pycaret.regression import *# initialize setups = setup(data = train, test_data = test, target = 'Passengers', fold_strategy = 'timeseries', numeric_features = ['Year', 'Series'], fold = 3, transform_target = True, session_id = 123)" }, { "code": null, "e": 6957, "s": 6921, "text": "best = compare_models(sort = 'MAE')" }, { "code": null, "e": 7079, "s": 6957, "text": "The best model based on cross-validated MAE is Least Angle Regression (MAE: 22.3). Let’s check the score on the test set." }, { "code": null, "e": 7121, "s": 7079, "text": "prediction_holdout = predict_model(best);" }, { "code": null, "e": 7288, "s": 7121, "text": "MAE on the test set is 12% higher than the cross-validated MAE. Not so good, but we will work with it. Let’s plot the actual and predicted lines to visualize the fit." }, { "code": null, "e": 7753, "s": 7288, "text": "# generate predictions on the original datasetpredictions = predict_model(best, data=data)# add a date column in the datasetpredictions['Date'] = pd.date_range(start='1949-01-01', end = '1960-12-01', freq = 'MS')# line plotfig = px.line(predictions, x='Date', y=[\"Passengers\", \"Label\"], template = 'plotly_dark')# add a vertical rectange for test-set separationfig.add_vrect(x0=\"1960-01-01\", x1=\"1960-12-01\", fillcolor=\"grey\", opacity=0.25, line_width=0)fig.show()" }, { "code": null, "e": 7961, "s": 7753, "text": "The grey backdrop towards the end is the test period (i.e. 1960). Now let’s finalize the model i.e. train the best model i.e. Least Angle Regression on the entire dataset (this time, including the test set)." }, { "code": null, "e": 7995, "s": 7961, "text": "final_best = finalize_model(best)" }, { "code": null, "e": 8280, "s": 7995, "text": "Now that we have trained our model on the entire dataset (1949 to 1960), let’s predict five years out in the future through 1964. To use our final model to generate future predictions, we first need to create a dataset consisting of the Month, Year, Series column on the future dates." }, { "code": null, "e": 8572, "s": 8280, "text": "future_dates = pd.date_range(start = '1961-01-01', end = '1965-01-01', freq = 'MS')future_df = pd.DataFrame()future_df['Month'] = [i.month for i in future_dates]future_df['Year'] = [i.year for i in future_dates] future_df['Series'] = np.arange(145 (145+len(future_dates)))future_df.head()" }, { "code": null, "e": 8636, "s": 8572, "text": "Now, let’s use the future_df to score and generate predictions." }, { "code": null, "e": 8724, "s": 8636, "text": "predictions_future = predict_model(final_best, data=future_df)predictions_future.head()" }, { "code": null, "e": 9013, "s": 8724, "text": "concat_df = pd.concat([data,predictions_future], axis=0)concat_df_i = pd.date_range(start='1949-01-01', end = '1965-01-01', freq = 'MS')concat_df.set_index(concat_df_i, inplace=True)fig = px.line(concat_df, x=concat_df.index, y=[\"Passengers\", \"Label\"], template = 'plotly_dark')fig.show()" }, { "code": null, "e": 9197, "s": 9013, "text": "I hope you find this tutorial easy. If you think you are ready for the next level, you can check out my advanced time-series tutorial on Multiple Time Series Forecasting with PyCaret." }, { "code": null, "e": 9416, "s": 9197, "text": "I will soon be writing a tutorial on unsupervised anomaly detection on time-series data using PyCaret Anomaly Detection Module. If you would like to get more updates, you can follow me on Medium, LinkedIn, and Twitter." }, { "code": null, "e": 9603, "s": 9416, "text": "There is no limit to what you can achieve using this lightweight workflow automation library in Python. If you find this useful, please do not forget to give ⭐️ on our GitHub repository." }, { "code": null, "e": 9666, "s": 9603, "text": "To learn more about PyCaret follow us on LinkedIn and Youtube." }, { "code": null, "e": 9714, "s": 9666, "text": "Join us on our slack channel. Invite link here." }, { "code": null, "e": 10177, "s": 9714, "text": "Build your own AutoML in Power BI using PyCaret 2.0Deploy Machine Learning Pipeline on Azure using DockerDeploy Machine Learning Pipeline on Google Kubernetes EngineDeploy Machine Learning Pipeline on AWS FargateBuild and deploy your first machine learning web appDeploy PyCaret and Streamlit app using AWS Fargate serverlessBuild and deploy machine learning web app using PyCaret and StreamlitDeploy Machine Learning App built using Streamlit and PyCaret on GKE" }, { "code": null, "e": 10268, "s": 10177, "text": "DocumentationBlogGitHubStackOverflowInstall PyCaretNotebook TutorialsContribute in PyCaret" }, { "code": null, "e": 10340, "s": 10268, "text": "Click on the links below to see the documentation and working examples." } ]
How to use Twitter’s API. Why use an API? API stands for... | by Robert Miller | Towards Data Science
Why use an API? API stands for Application Programming Interfaces (APIs) and they allow you to access resources only available on the server. Lets learn how to use twitters API. Firstly you will need a twitter account with your phone number attached for verification purposes. You will then need to go to apps.twitter.com and create app so we can reference the coresponding keys Twitter generates for this app. These are the keys that we will use with our application to communicate with the Twitter API. Now going into the code, we will need to install python-twitter API library !pip install python-twitter Make sure you understand Twitters rules for using their API, if you do not follow their rules they can block you from accessing data. Here is a link to some of their rate limits https://dev.twitter.com/rest/public/rate-limiting Now that we have our app, we have keys associated with the app. consumer_key — Find this in your app page under the “Keys and Access Tokens” consumer_secret — Right under consumer_key in the “Keys and Access Tokens” tab access_token_key — You will need to click the “generate tokens” button to get this access_token_secret — Also available after “generate tokens” is pressed We will plug those specific keys into our function below import twitter, re, datetime, pandas as pdclass twitterminer():request_limit = 20 api = False data = [] twitter_keys = { 'consumer_key': , #add your consumer key 'consumer_secret': , #add your consumer secret key 'access_token_key': , #add your access token key 'access_token_secret': #add your access token secret key } def __init__(self, request_limit = 20): self.request_limit = request_limit # This sets the twitter API object for use internall within the class self.set_api() def set_api(self): self.api = twitter.Api( consumer_key = self.twitter_keys['consumer_key'], consumer_secret = self.twitter_keys['consumer_secret'], access_token_key = self.twitter_keys['access_token_key'], access_token_secret = self.twitter_keys['access_token_secret'] )def mine_user_tweets(self, user=" set default user to get data from", mine_retweets=False):statuses = self.api.GetUserTimeline(screen_name=user, count=self.request_limit) data = [] for item in statuses:mined = { 'tweet_id': item.id, 'handle': item.user.name, 'retweet_count': item.retweet_count, 'text': item.text, 'mined_at': datetime.datetime.now(), 'created_at': item.created_at, } data.append(mined) return data We then need to instantiate our class to be able to use our functions above. mine = twitterminer() Lets use the API to get some tweets from Donald Trumps twitter # insert handle we liketrump_tweets = miner.mine_user_tweets("realDonaldTrump")trump_df = pd.DataFrame(trump_tweets) We have now successfully pulled tweets from Donald Trumps twitter onto our local machine to analyze. Good luck gathering your data.
[ { "code": null, "e": 349, "s": 171, "text": "Why use an API? API stands for Application Programming Interfaces (APIs) and they allow you to access resources only available on the server. Lets learn how to use twitters API." }, { "code": null, "e": 676, "s": 349, "text": "Firstly you will need a twitter account with your phone number attached for verification purposes. You will then need to go to apps.twitter.com and create app so we can reference the coresponding keys Twitter generates for this app. These are the keys that we will use with our application to communicate with the Twitter API." }, { "code": null, "e": 752, "s": 676, "text": "Now going into the code, we will need to install python-twitter API library" }, { "code": null, "e": 780, "s": 752, "text": "!pip install python-twitter" }, { "code": null, "e": 1008, "s": 780, "text": "Make sure you understand Twitters rules for using their API, if you do not follow their rules they can block you from accessing data. Here is a link to some of their rate limits https://dev.twitter.com/rest/public/rate-limiting" }, { "code": null, "e": 1072, "s": 1008, "text": "Now that we have our app, we have keys associated with the app." }, { "code": null, "e": 1149, "s": 1072, "text": "consumer_key — Find this in your app page under the “Keys and Access Tokens”" }, { "code": null, "e": 1228, "s": 1149, "text": "consumer_secret — Right under consumer_key in the “Keys and Access Tokens” tab" }, { "code": null, "e": 1311, "s": 1228, "text": "access_token_key — You will need to click the “generate tokens” button to get this" }, { "code": null, "e": 1383, "s": 1311, "text": "access_token_secret — Also available after “generate tokens” is pressed" }, { "code": null, "e": 1440, "s": 1383, "text": "We will plug those specific keys into our function below" }, { "code": null, "e": 3026, "s": 1440, "text": "import twitter, re, datetime, pandas as pdclass twitterminer():request_limit = 20 api = False data = [] twitter_keys = { 'consumer_key': , #add your consumer key 'consumer_secret': , #add your consumer secret key 'access_token_key': , #add your access token key 'access_token_secret': #add your access token secret key } def __init__(self, request_limit = 20): self.request_limit = request_limit # This sets the twitter API object for use internall within the class self.set_api() def set_api(self): self.api = twitter.Api( consumer_key = self.twitter_keys['consumer_key'], consumer_secret = self.twitter_keys['consumer_secret'], access_token_key = self.twitter_keys['access_token_key'], access_token_secret = self.twitter_keys['access_token_secret'] )def mine_user_tweets(self, user=\" set default user to get data from\", mine_retweets=False):statuses = self.api.GetUserTimeline(screen_name=user, count=self.request_limit) data = [] for item in statuses:mined = { 'tweet_id': item.id, 'handle': item.user.name, 'retweet_count': item.retweet_count, 'text': item.text, 'mined_at': datetime.datetime.now(), 'created_at': item.created_at, } data.append(mined) return data" }, { "code": null, "e": 3103, "s": 3026, "text": "We then need to instantiate our class to be able to use our functions above." }, { "code": null, "e": 3125, "s": 3103, "text": "mine = twitterminer()" }, { "code": null, "e": 3188, "s": 3125, "text": "Lets use the API to get some tweets from Donald Trumps twitter" }, { "code": null, "e": 3305, "s": 3188, "text": "# insert handle we liketrump_tweets = miner.mine_user_tweets(\"realDonaldTrump\")trump_df = pd.DataFrame(trump_tweets)" } ]
CSS Rain and lightning effect - GeeksforGeeks
07 Sep, 2020 To generate the rain and lightning effect, we will make use of CSS animations that allow animation of HTML elements. We will use @keyframes that allow the animation to gradually change from the current style to the new style at certain times then we will use the filter:hue-rotate() to give the lightning effect. Approach: Add a background image in the section. To generate the rain effect add a background image of rain to the same section using section:before property of CSS. We will create an animation for a lightening effect named color-change for 10s and infinite time. To create a color-change animation we will use @keyframes and give the effect using property filter:hue-rotate(deg). To create a rain effect again we will use the @keyframes property and change the position of the background image for some interval. Example: <!DOCTYPE html><html> <head> <style> body { margin: 0; padding: 0; } /*adding background to section and animation named color-change*/ section { position: relative; width: 100%; height: 100vh; background-image: url(https://media.geeksforgeeks.org/wp-content/uploads/20200828184536/download-200x200.png); background-size: cover; background-position: center; animation: color-change 10s linear infinite; animation-delay: 1s; } /*adding rain img and making opacity 0*/ section:before { content: ""; position: absolute; top: 0; left: 0; width: 100%; height: 100%; background-image: url(https://media.geeksforgeeks.org/wp-content/uploads/20200828184719/rain-300x300.png); animation: rain 0.4s linear infinite; opacity: 0; } /* just changing the position of image of rain using keyframes*/ @keyframes rain { 0% { background-position: 0 0; opacity: 1; } 100% { background-position: 8% 80%; opacity: 1; } } /* applying filter at different angle on diffrent interval using keyframe*/ @keyframes color-change { 0% { filter: hue-rotate(0deg); } 50% { filter: hue-rotate(0deg); } 100% { filter: hue-rotate(360deg); } } </style> </head> <body> <section></section> </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. CSS-Misc CSS HTML Web Technologies HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Design a web page using HTML and CSS Form validation using jQuery How to set space between the flexbox ? Search Bar using HTML, CSS and JavaScript How to style a checkbox using CSS? How to set the default value for an HTML <select> element ? How to set input type date in dd-mm-yyyy format using HTML ? Hide or show elements in HTML using display property How to Insert Form Data into Database using PHP ? REST API (Introduction)
[ { "code": null, "e": 25402, "s": 25374, "text": "\n07 Sep, 2020" }, { "code": null, "e": 25519, "s": 25402, "text": "To generate the rain and lightning effect, we will make use of CSS animations that allow animation of HTML elements." }, { "code": null, "e": 25715, "s": 25519, "text": "We will use @keyframes that allow the animation to gradually change from the current style to the new style at certain times then we will use the filter:hue-rotate() to give the lightning effect." }, { "code": null, "e": 25725, "s": 25715, "text": "Approach:" }, { "code": null, "e": 25764, "s": 25725, "text": "Add a background image in the section." }, { "code": null, "e": 25881, "s": 25764, "text": "To generate the rain effect add a background image of rain to the same section using section:before property of CSS." }, { "code": null, "e": 25979, "s": 25881, "text": "We will create an animation for a lightening effect named color-change for 10s and infinite time." }, { "code": null, "e": 26096, "s": 25979, "text": "To create a color-change animation we will use @keyframes and give the effect using property filter:hue-rotate(deg)." }, { "code": null, "e": 26229, "s": 26096, "text": "To create a rain effect again we will use the @keyframes property and change the position of the background image for some interval." }, { "code": null, "e": 26238, "s": 26229, "text": "Example:" }, { "code": "<!DOCTYPE html><html> <head> <style> body { margin: 0; padding: 0; } /*adding background to section and animation named color-change*/ section { position: relative; width: 100%; height: 100vh; background-image: url(https://media.geeksforgeeks.org/wp-content/uploads/20200828184536/download-200x200.png); background-size: cover; background-position: center; animation: color-change 10s linear infinite; animation-delay: 1s; } /*adding rain img and making opacity 0*/ section:before { content: \"\"; position: absolute; top: 0; left: 0; width: 100%; height: 100%; background-image: url(https://media.geeksforgeeks.org/wp-content/uploads/20200828184719/rain-300x300.png); animation: rain 0.4s linear infinite; opacity: 0; } /* just changing the position of image of rain using keyframes*/ @keyframes rain { 0% { background-position: 0 0; opacity: 1; } 100% { background-position: 8% 80%; opacity: 1; } } /* applying filter at different angle on diffrent interval using keyframe*/ @keyframes color-change { 0% { filter: hue-rotate(0deg); } 50% { filter: hue-rotate(0deg); } 100% { filter: hue-rotate(360deg); } } </style> </head> <body> <section></section> </body></html>", "e": 28189, "s": 26238, "text": null }, { "code": null, "e": 28197, "s": 28189, "text": "Output:" }, { "code": null, "e": 28334, "s": 28197, "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": 28343, "s": 28334, "text": "CSS-Misc" }, { "code": null, "e": 28347, "s": 28343, "text": "CSS" }, { "code": null, "e": 28352, "s": 28347, "text": "HTML" }, { "code": null, "e": 28369, "s": 28352, "text": "Web Technologies" }, { "code": null, "e": 28374, "s": 28369, "text": "HTML" }, { "code": null, "e": 28472, "s": 28374, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28481, "s": 28472, "text": "Comments" }, { "code": null, "e": 28494, "s": 28481, "text": "Old Comments" }, { "code": null, "e": 28531, "s": 28494, "text": "Design a web page using HTML and CSS" }, { "code": null, "e": 28560, "s": 28531, "text": "Form validation using jQuery" }, { "code": null, "e": 28599, "s": 28560, "text": "How to set space between the flexbox ?" }, { "code": null, "e": 28641, "s": 28599, "text": "Search Bar using HTML, CSS and JavaScript" }, { "code": null, "e": 28676, "s": 28641, "text": "How to style a checkbox using CSS?" }, { "code": null, "e": 28736, "s": 28676, "text": "How to set the default value for an HTML <select> element ?" }, { "code": null, "e": 28797, "s": 28736, "text": "How to set input type date in dd-mm-yyyy format using HTML ?" }, { "code": null, "e": 28850, "s": 28797, "text": "Hide or show elements in HTML using display property" }, { "code": null, "e": 28900, "s": 28850, "text": "How to Insert Form Data into Database using PHP ?" } ]
C# | Explicit Interface Implementation - GeeksforGeeks
24 Sep, 2021 An Interface is a collection of loosely bound items that have a common functionality or attributes. Interfaces contain method signatures, properties, events etc. Interfaces are used so that one class or struct can implement multiple behaviors. C# doesn’t support the concept of Multiple Inheritance because of the ambiguity it causes. But a lot of real-life objects inherit properties of more than just one type, therefore interfaces are used instead of extending classes. An Interface consists only of the signatures and not its implementation, therefore, any class or struct that implements it has to provide the implementation by overriding. Explicitly telling the compiler that a particular member belongs to that particular interface is called Explicit interface implementation. If a class implements from more than one interface that has methods with the same signature then the call to such a method will implement the same method and not the interface-specific methods. This will defeat the whole purpose of using different Interfaces. That is when Explicit implementation comes into the picture. Using explicit implementation you can tell the compiler which interface’s method you are Overloading and can provide different functionalities for methods of different interfaces. The same is the case for any other type of member like a property, event. Syntax: class ClassName : InterfaceName { returnType InterfaceName.method() { // Your Code } } Example 1: This program shows the use of explicit interface implementation. Here we have two interfaces I1 and I2 that have the same method signature named printMethod with return type as void. Class C implements these two Interfaces, therefore we use explicit interface implementation to distinguish between the methods. C# // C# Program to show the use of// Explicit interface implementationusing System; interface I1 { void printMethod();} interface I2 { void printMethod();} // class C implements two interfacesclass C : I1, I2 { // Explicitly implements method of I1 void I1.printMethod() { Console.WriteLine("I1 printMethod"); } // Explicitly implements method of I2 void I2.printMethod() { Console.WriteLine("I2 printMethod"); }} // Driver Classclass GFG { // Main Method static void Main(string[] args) { I1 i1 = new C(); I2 i2 = new C(); // call to method of I1 i1.printMethod(); // call to method of I2 i2.printMethod(); }} I1 printMethod I2 printMethod Example 2: Here, we have an Interface Pyramid with a method drawPyramid. The class Display inherits this method and provides an implementation that prints a ‘*‘ pyramid on the screen. We use Explicit implementation to override drawPyramid method. C# // C# Program to show the use of// Explicit interface implementationusing System; interface Pyramid { // Method signature void drawPyramid();} // Implements Pyramidclass Display : Pyramid { // Using Explicit implementation void Pyramid.drawPyramid() { for (int i = 1; i <= 10; i++) { for (int k = i; k < 10; k++) Console.Write(" "); for (int j = 1; j <= (2 * i - 1); j++) Console.Write("*"); Console.WriteLine(); } }} // Driver Codeclass GFG { // Main Method static void Main(string[] args) { // Create object of the class using Interface Pyramid obj = new Display(); // call method obj.drawPyramid(); }} * *** ***** ******* ********* *********** ************* *************** ***************** ******************* Example 3: We can use explicit interface implementation for even properties and basically any other members of the interface. Here, we have property X and method X in interface I1 and I2 respectively with the same names and return types. We only use explicit interface implementation on method X. This way the compiler will use the property X unless specified otherwise. C# // C# Program to show the use of// Explicit interface implementationusing System; interface I1 { // Property X int X { set; get; }} interface I2 { // Method X int X();} class C : I1, I2 { int x; // Implicit implementation of // the property public int X { set { x = value; } get { return x; } } // Explicit implementation of // the method int I2.X() { return 0; }} // Driver Codeclass GFG { // Main Method static void Main(string[] args) { C c = new C(); I2 i2 = new C(); // Invokes set accessor c.X = 10; // Invokes get accessor Console.WriteLine("Value of x set using X"+ " from I1 is " + c.X); // Call to the X method Console.WriteLine("Value returned by I2.X()"+ " is " + i2.X()); }} Value of x set using X from I1 is 10 Value returned by I2.X() is 0 erohsik CSharp-Interfaces C# Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Destructors in C# Difference between Ref and Out keywords in C# C# | Constructors C# | String.IndexOf( ) Method | Set - 1 Introduction to .NET Framework C# | Class and Object C# | Abstract Classes HashSet in C# with Examples C# | Encapsulation C# | Replace() Method
[ { "code": null, "e": 23920, "s": 23892, "text": "\n24 Sep, 2021" }, { "code": null, "e": 24394, "s": 23920, "text": "An Interface is a collection of loosely bound items that have a common functionality or attributes. Interfaces contain method signatures, properties, events etc. Interfaces are used so that one class or struct can implement multiple behaviors. C# doesn’t support the concept of Multiple Inheritance because of the ambiguity it causes. But a lot of real-life objects inherit properties of more than just one type, therefore interfaces are used instead of extending classes. " }, { "code": null, "e": 24566, "s": 24394, "text": "An Interface consists only of the signatures and not its implementation, therefore, any class or struct that implements it has to provide the implementation by overriding." }, { "code": null, "e": 25280, "s": 24566, "text": "Explicitly telling the compiler that a particular member belongs to that particular interface is called Explicit interface implementation. If a class implements from more than one interface that has methods with the same signature then the call to such a method will implement the same method and not the interface-specific methods. This will defeat the whole purpose of using different Interfaces. That is when Explicit implementation comes into the picture. Using explicit implementation you can tell the compiler which interface’s method you are Overloading and can provide different functionalities for methods of different interfaces. The same is the case for any other type of member like a property, event." }, { "code": null, "e": 25288, "s": 25280, "text": "Syntax:" }, { "code": null, "e": 25399, "s": 25288, "text": "class ClassName : InterfaceName\n{\n returnType InterfaceName.method()\n { \n // Your Code \n }\n}" }, { "code": null, "e": 25721, "s": 25399, "text": "Example 1: This program shows the use of explicit interface implementation. Here we have two interfaces I1 and I2 that have the same method signature named printMethod with return type as void. Class C implements these two Interfaces, therefore we use explicit interface implementation to distinguish between the methods." }, { "code": null, "e": 25724, "s": 25721, "text": "C#" }, { "code": "// C# Program to show the use of// Explicit interface implementationusing System; interface I1 { void printMethod();} interface I2 { void printMethod();} // class C implements two interfacesclass C : I1, I2 { // Explicitly implements method of I1 void I1.printMethod() { Console.WriteLine(\"I1 printMethod\"); } // Explicitly implements method of I2 void I2.printMethod() { Console.WriteLine(\"I2 printMethod\"); }} // Driver Classclass GFG { // Main Method static void Main(string[] args) { I1 i1 = new C(); I2 i2 = new C(); // call to method of I1 i1.printMethod(); // call to method of I2 i2.printMethod(); }}", "e": 26438, "s": 25724, "text": null }, { "code": null, "e": 26468, "s": 26438, "text": "I1 printMethod\nI2 printMethod" }, { "code": null, "e": 26717, "s": 26470, "text": "Example 2: Here, we have an Interface Pyramid with a method drawPyramid. The class Display inherits this method and provides an implementation that prints a ‘*‘ pyramid on the screen. We use Explicit implementation to override drawPyramid method." }, { "code": null, "e": 26720, "s": 26717, "text": "C#" }, { "code": "// C# Program to show the use of// Explicit interface implementationusing System; interface Pyramid { // Method signature void drawPyramid();} // Implements Pyramidclass Display : Pyramid { // Using Explicit implementation void Pyramid.drawPyramid() { for (int i = 1; i <= 10; i++) { for (int k = i; k < 10; k++) Console.Write(\" \"); for (int j = 1; j <= (2 * i - 1); j++) Console.Write(\"*\"); Console.WriteLine(); } }} // Driver Codeclass GFG { // Main Method static void Main(string[] args) { // Create object of the class using Interface Pyramid obj = new Display(); // call method obj.drawPyramid(); }}", "e": 27473, "s": 26720, "text": null }, { "code": null, "e": 27628, "s": 27473, "text": " *\n ***\n *****\n *******\n *********\n ***********\n *************\n ***************\n *****************\n*******************" }, { "code": null, "e": 28001, "s": 27630, "text": "Example 3: We can use explicit interface implementation for even properties and basically any other members of the interface. Here, we have property X and method X in interface I1 and I2 respectively with the same names and return types. We only use explicit interface implementation on method X. This way the compiler will use the property X unless specified otherwise." }, { "code": null, "e": 28004, "s": 28001, "text": "C#" }, { "code": "// C# Program to show the use of// Explicit interface implementationusing System; interface I1 { // Property X int X { set; get; }} interface I2 { // Method X int X();} class C : I1, I2 { int x; // Implicit implementation of // the property public int X { set { x = value; } get { return x; } } // Explicit implementation of // the method int I2.X() { return 0; }} // Driver Codeclass GFG { // Main Method static void Main(string[] args) { C c = new C(); I2 i2 = new C(); // Invokes set accessor c.X = 10; // Invokes get accessor Console.WriteLine(\"Value of x set using X\"+ \" from I1 is \" + c.X); // Call to the X method Console.WriteLine(\"Value returned by I2.X()\"+ \" is \" + i2.X()); }}", "e": 28918, "s": 28004, "text": null }, { "code": null, "e": 28985, "s": 28918, "text": "Value of x set using X from I1 is 10\nValue returned by I2.X() is 0" }, { "code": null, "e": 28995, "s": 28987, "text": "erohsik" }, { "code": null, "e": 29013, "s": 28995, "text": "CSharp-Interfaces" }, { "code": null, "e": 29016, "s": 29013, "text": "C#" }, { "code": null, "e": 29114, "s": 29016, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29132, "s": 29114, "text": "Destructors in C#" }, { "code": null, "e": 29178, "s": 29132, "text": "Difference between Ref and Out keywords in C#" }, { "code": null, "e": 29196, "s": 29178, "text": "C# | Constructors" }, { "code": null, "e": 29236, "s": 29196, "text": "C# | String.IndexOf( ) Method | Set - 1" }, { "code": null, "e": 29267, "s": 29236, "text": "Introduction to .NET Framework" }, { "code": null, "e": 29289, "s": 29267, "text": "C# | Class and Object" }, { "code": null, "e": 29311, "s": 29289, "text": "C# | Abstract Classes" }, { "code": null, "e": 29339, "s": 29311, "text": "HashSet in C# with Examples" }, { "code": null, "e": 29358, "s": 29339, "text": "C# | Encapsulation" } ]
Program to find parity
08 Jul, 2022 Parity: Parity of a number refers to whether it contains an odd or even number of 1-bits. The number has “odd parity” if it contains an odd number of 1-bits and is “even parity” if it contains an even number of 1-bits. The main idea of the below solution is – Loop while n is not 0 and in loop unset one of the set bits and invert parity. Algorithm: getParity(n) 1. Initialize parity = 0 2. Loop while n != 0 a. Invert parity parity = !parity b. Unset rightmost set bit n = n & (n-1) 3. return parity Example: Initialize: n = 13 (1101) parity = 0 n = 13 & 12 = 12 (1100) parity = 1 n = 12 & 11 = 8 (1000) parity = 0 n = 8 & 7 = 0 (0000) parity = 1 Program: C++ C Java Python3 C# PHP Javascript // C++ program to find parity// of an integer# include<bits/stdc++.h># define bool intusing namespace std; // Function to get parity of number n. It returns 1// if n has odd parity, and returns 0 if n has even// paritybool getParity(unsigned int n){ bool parity = 0; while (n) { parity = !parity; n = n & (n - 1); } return parity;} /* Driver program to test getParity() */int main(){ unsigned int n = 7; cout<<"Parity of no "<<n<<" = "<<(getParity(n)? "odd": "even"); getchar(); return 0;} // C program to find parity// of an integer# include <stdio.h># define bool int /* Function to get parity of number n. It returns 1 if n has odd parity, and returns 0 if n has even parity */bool getParity(unsigned int n){ bool parity = 0; while (n) { parity = !parity; n = n & (n - 1); } return parity;} /* Driver program to test getParity() */int main(){ unsigned int n = 7; printf("Parity of no %d = %s", n, (getParity(n)? "odd": "even")); getchar(); return 0;} // Java program to find parity// of an integerimport java.util.*;import java.lang.*;import java.io.*;import java.math.BigInteger; class GFG { /* Function to get parity of number n. It returns 1 if n has odd parity, and returns 0 if n has even parity */ static boolean getParity(int n) { boolean parity = false; while(n != 0) { parity = !parity; n = n & (n-1); } return parity; } /* Driver program to test getParity() */ public static void main (String[] args) { int n = 7; System.out.println("Parity of no " + n + " = " + (getParity(n)? "odd": "even")); }}/* This code is contributed by Amit khandelwal*/ # Python3 code to get parity. # Function to get parity of number n.# It returns 1 if n has odd parity,# and returns 0 if n has even paritydef getParity( n ): parity = 0 while n: parity = ~parity n = n & (n - 1) return parity # Driver program to test getParity()n = 7print ("Parity of no ", n," = ", ( "odd" if getParity(n) else "even")) # This code is contributed by "Sharad_Bhardwaj". // C# program to find parity of an integerusing System; class GFG { /* Function to get parity of number n. It returns 1 if n has odd parity, and returns 0 if n has even parity */ static bool getParity(int n) { bool parity = false; while(n != 0) { parity = !parity; n = n & (n-1); } return parity; } // Driver code public static void Main () { int n = 7; Console.Write("Parity of no " + n + " = " + (getParity(n)? "odd": "even")); }} // This code is contributed by nitin mittal. <?php// PHP program to find the parity// of an unsigned integer // Function to get parity of// number n. It returns 1// if n has odd parity, and// returns 0 if n has even// parityfunction getParity( $n){ $parity = 0; while ($n) { $parity = !$parity; $n = $n & ($n - 1); } return $parity;} // Driver Code $n = 7; echo "Parity of no ",$n ," = " , getParity($n)? "odd": "even"; // This code is contributed by anuj_67.?> <script> // Javascript program to find parity// of an integer // Function to get parity of number n.// It returns 1 if n has odd parity, and// returns 0 if n has even parityfunction getParity(n){ var parity = false; while(n != 0) { parity = !parity; n = n & (n - 1); } return parity;} // Driver codevar n = 7;document.write("Parity of no " + n + " = " + (getParity(n) ? "odd": "even")); // This code is contributed by Kirti </script> Parity of no 7 = odd Above solution can be optimized by using lookup table. Please refer to Bit Twiddle Hacks[1st reference] for details.Time Complexity: The time taken by above algorithm is proportional to the number of bits set. Worst case complexity is O(Log n).Auxiliary Space: O(1) Another approach: (Using built-in-function) C++ // C++ program to find parity// of an integer# include<bits/stdc++.h># define bool intusing namespace std; // Function to get parity of number n. It returns 1// if n has odd parity, and returns 0 if n has even// paritybool getParity(unsigned int n){ return __builtin_parity(n);} // Driver codeint main(){ unsigned int n = 7; cout<<"Parity of no "<<n<<" = "<<(getParity(n)? "odd": "even"); getchar(); return 0;} // This code is contributed by Kasina Dheeraj Parity of no 7 = odd Time Complexity: O(1) Auxiliary Space: O(1) Another Approach: Mapping numbers with the bit We can use a map or an array of the number of bits to form a nibble (a nibble consists of 4 bits, so a 16 – length array would be required). Then, we can get the nibbles of a given number. This approach can be summarized into the following steps: 1. Build the 16 length array of the number of bits to form a nibble – { 0, 1, 1, 2, 1, 2, 2, 3, 1, 2, 2, 3, 2, 3, 3, 4 } 2. Recursively count the set of the bits by taking the last nibble (4 bits) from the array using the formula num & 0xf and then getting each successive nibble by discarding the last 4 bits using >> operator. 3. Check the parity: if the number of set bits is even, ie numOfSetBits % 2 == 0, then the number is of even parity. Else, it is of odd parity. C++ Java Python3 C# Javascript // C++ program to get the parity of the// binary representation of a number #include <bits/stdc++.h>using namespace std; int nibble_to_bits[16] = { 0, 1, 1, 2, 1, 2, 2, 3, 1, 2, 2, 3, 2, 3, 3, 4 }; // Function to recursively get the nibble// of a given number and map them in the array unsigned int countSetBits(unsigned int num){ int nibble = 0; if (0 == num) return nibble_to_bits[0]; // Find last nibble nibble = num & 0xf; // Use pre-stored values to find count // in last nibble plus recursively add // remaining nibbles. return nibble_to_bits[nibble] + countSetBits(num >> 4);} // Function to get the parity of a numberbool getParity(int num) { return countSetBits(num) % 2; } // Driver codeint main(){ unsigned int n = 7; // Function call cout << "Parity of no " << n << " = " << (getParity(n) ? "odd" : "even"); return 0;} // This code is contributed by phasing17 // Java program to get the parity of the// binary representation of a numberimport java.util.*; class GFG{ static int[] nibble_to_bits = { 0, 1, 1, 2, 1, 2, 2, 3, 1, 2, 2, 3, 2, 3, 3, 4 }; // Function to recursively get the nibble // of a given number and map them in the array static int countSetBits(int num) { int nibble = 0; if (0 == num) return nibble_to_bits[0]; // Find last nibble nibble = num & 0xf; // Use pre-stored values to find count // in last nibble plus recursively add // remaining nibbles. return nibble_to_bits[nibble] + countSetBits(num >> 4); } // Function to get the parity of a number static boolean getParity(int num) { return countSetBits(num) % 2 == 1; } // Driver codepublic static void main(String[] args){ int n = 7; // Function call System.out.print( "Parity of no " + n + " = " + (getParity(n) ? "odd" : "even"));}} // This code is contributed by sanjoy_62. # Python3 program to get the parity of the# binary representation of a numbernibble_to_bits = [0, 1, 1, 2, 1, 2, 2, 3, 1, 2, 2, 3, 2, 3, 3, 4] # Function to recursively get the nibble# of a given number and map them in the arraydef countSetBits(num): nibble = 0 if (0 == num): return nibble_to_bits[0] # Find last nibble nibble = num & 0xf # Use pre-stored values to find count # in last nibble plus recursively add # remaining nibbles. return nibble_to_bits[nibble] + countSetBits(num >> 4) # Function to get the parity of a numberdef getParity(num): return countSetBits(num) % 2 # Driver coden = 7 # Function callprint("Parity of no", n, " = ", ["even", "odd"][getParity(n)]) # This code is contributed by phasing17 // C# program to get the parity of the// binary representation of a numberusing System; class GFG { static int[] nibble_to_bits = { 0, 1, 1, 2, 1, 2, 2, 3, 1, 2, 2, 3, 2, 3, 3, 4 }; // Function to recursively get the nibble // of a given number and map them in the array static int countSetBits(int num) { int nibble = 0; if (0 == num) return nibble_to_bits[0]; // Find last nibble nibble = num & 0xf; // Use pre-stored values to find count // in last nibble plus recursively add // remaining nibbles. return nibble_to_bits[nibble] + countSetBits(num >> 4); } // Function to get the parity of a number static bool getParity(int num) { return countSetBits(num) % 2 == 1; } // Driver code public static void Main(string[] args) { int n = 7; // Function call Console.WriteLine( "Parity of no " + n + " = " + (getParity(n) ? "odd" : "even")); }} // This code is contributed by phasing17 // JavaScript program to get the parity of the// binary representation of a number let nibble_to_bits = [ 0, 1, 1, 2, 1, 2, 2, 3, 1, 2, 2, 3, 2, 3, 3, 4 ]; // Function to recursively get the nibble// of a given number and map them in the array function countSetBits(num){ let nibble = 0; if (0 == num) return nibble_to_bits[0]; // Find last nibble nibble = num & 0xf; // Use pre-stored values to find count // in last nibble plus recursively add // remaining nibbles. return nibble_to_bits[nibble] + countSetBits(num >> 4);} // Function to get the parity of a numberfunction getParity(num) { return countSetBits(num) % 2; } // Driver codelet n = 7; // Function callconsole.log("Parity of no " + n + " = "+ (getParity(n) ? "odd" : "even")); // This code is contributed by phasing17 Parity of no 7 = odd Time Complexity: O(1) Auxiliary Space: O(1) Uses: Parity is used in error detection and cryptography. Compute the parity of a number using XOR and table look-up References: http://graphics.stanford.edu/~seander/bithacks.html#ParityNaive – last checked on 30 May 2009. nitin mittal vt_m SURENDRA_GANGWAR Kirti_Mangal rishavmahato348 dheerukd2002 ranjanrohit840 phasing17 sweetyty sanjoy_62 cryptography Bit Magic Mathematical Mathematical Bit Magic cryptography Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Little and Big Endian Mystery Program to find whether a given number is power of 2 Binary representation of a given number Josephus problem | Set 1 (A O(n) Solution) Divide two integers without using multiplication, division and mod operator Program for Fibonacci numbers Set in C++ Standard Template Library (STL) Write a program to print all permutations of a given string C++ Data Types Merge two sorted arrays
[ { "code": null, "e": 54, "s": 26, "text": "\n08 Jul, 2022" }, { "code": null, "e": 393, "s": 54, "text": "Parity: Parity of a number refers to whether it contains an odd or even number of 1-bits. The number has “odd parity” if it contains an odd number of 1-bits and is “even parity” if it contains an even number of 1-bits. The main idea of the below solution is – Loop while n is not 0 and in loop unset one of the set bits and invert parity." }, { "code": null, "e": 762, "s": 393, "text": "Algorithm: getParity(n)\n1. Initialize parity = 0\n2. Loop while n != 0 \n a. Invert parity \n parity = !parity\n b. Unset rightmost set bit\n n = n & (n-1)\n3. return parity\n\nExample:\n Initialize: n = 13 (1101) parity = 0\n\nn = 13 & 12 = 12 (1100) parity = 1\nn = 12 & 11 = 8 (1000) parity = 0\nn = 8 & 7 = 0 (0000) parity = 1" }, { "code": null, "e": 772, "s": 762, "text": "Program: " }, { "code": null, "e": 776, "s": 772, "text": "C++" }, { "code": null, "e": 778, "s": 776, "text": "C" }, { "code": null, "e": 783, "s": 778, "text": "Java" }, { "code": null, "e": 791, "s": 783, "text": "Python3" }, { "code": null, "e": 794, "s": 791, "text": "C#" }, { "code": null, "e": 798, "s": 794, "text": "PHP" }, { "code": null, "e": 809, "s": 798, "text": "Javascript" }, { "code": "// C++ program to find parity// of an integer# include<bits/stdc++.h># define bool intusing namespace std; // Function to get parity of number n. It returns 1// if n has odd parity, and returns 0 if n has even// paritybool getParity(unsigned int n){ bool parity = 0; while (n) { parity = !parity; n = n & (n - 1); } return parity;} /* Driver program to test getParity() */int main(){ unsigned int n = 7; cout<<\"Parity of no \"<<n<<\" = \"<<(getParity(n)? \"odd\": \"even\"); getchar(); return 0;}", "e": 1353, "s": 809, "text": null }, { "code": "// C program to find parity// of an integer# include <stdio.h># define bool int /* Function to get parity of number n. It returns 1 if n has odd parity, and returns 0 if n has even parity */bool getParity(unsigned int n){ bool parity = 0; while (n) { parity = !parity; n = n & (n - 1); } return parity;} /* Driver program to test getParity() */int main(){ unsigned int n = 7; printf(\"Parity of no %d = %s\", n, (getParity(n)? \"odd\": \"even\")); getchar(); return 0;}", "e": 1893, "s": 1353, "text": null }, { "code": "// Java program to find parity// of an integerimport java.util.*;import java.lang.*;import java.io.*;import java.math.BigInteger; class GFG { /* Function to get parity of number n. It returns 1 if n has odd parity, and returns 0 if n has even parity */ static boolean getParity(int n) { boolean parity = false; while(n != 0) { parity = !parity; n = n & (n-1); } return parity; } /* Driver program to test getParity() */ public static void main (String[] args) { int n = 7; System.out.println(\"Parity of no \" + n + \" = \" + (getParity(n)? \"odd\": \"even\")); }}/* This code is contributed by Amit khandelwal*/", "e": 2637, "s": 1893, "text": null }, { "code": "# Python3 code to get parity. # Function to get parity of number n.# It returns 1 if n has odd parity,# and returns 0 if n has even paritydef getParity( n ): parity = 0 while n: parity = ~parity n = n & (n - 1) return parity # Driver program to test getParity()n = 7print (\"Parity of no \", n,\" = \", ( \"odd\" if getParity(n) else \"even\")) # This code is contributed by \"Sharad_Bhardwaj\".", "e": 3050, "s": 2637, "text": null }, { "code": "// C# program to find parity of an integerusing System; class GFG { /* Function to get parity of number n. It returns 1 if n has odd parity, and returns 0 if n has even parity */ static bool getParity(int n) { bool parity = false; while(n != 0) { parity = !parity; n = n & (n-1); } return parity; } // Driver code public static void Main () { int n = 7; Console.Write(\"Parity of no \" + n + \" = \" + (getParity(n)? \"odd\": \"even\")); }} // This code is contributed by nitin mittal.", "e": 3689, "s": 3050, "text": null }, { "code": "<?php// PHP program to find the parity// of an unsigned integer // Function to get parity of// number n. It returns 1// if n has odd parity, and// returns 0 if n has even// parityfunction getParity( $n){ $parity = 0; while ($n) { $parity = !$parity; $n = $n & ($n - 1); } return $parity;} // Driver Code $n = 7; echo \"Parity of no \",$n ,\" = \" , getParity($n)? \"odd\": \"even\"; // This code is contributed by anuj_67.?>", "e": 4158, "s": 3689, "text": null }, { "code": "<script> // Javascript program to find parity// of an integer // Function to get parity of number n.// It returns 1 if n has odd parity, and// returns 0 if n has even parityfunction getParity(n){ var parity = false; while(n != 0) { parity = !parity; n = n & (n - 1); } return parity;} // Driver codevar n = 7;document.write(\"Parity of no \" + n + \" = \" + (getParity(n) ? \"odd\": \"even\")); // This code is contributed by Kirti </script>", "e": 4639, "s": 4158, "text": null }, { "code": null, "e": 4660, "s": 4639, "text": "Parity of no 7 = odd" }, { "code": null, "e": 4926, "s": 4660, "text": "Above solution can be optimized by using lookup table. Please refer to Bit Twiddle Hacks[1st reference] for details.Time Complexity: The time taken by above algorithm is proportional to the number of bits set. Worst case complexity is O(Log n).Auxiliary Space: O(1)" }, { "code": null, "e": 4970, "s": 4926, "text": "Another approach: (Using built-in-function)" }, { "code": null, "e": 4974, "s": 4970, "text": "C++" }, { "code": "// C++ program to find parity// of an integer# include<bits/stdc++.h># define bool intusing namespace std; // Function to get parity of number n. It returns 1// if n has odd parity, and returns 0 if n has even// paritybool getParity(unsigned int n){ return __builtin_parity(n);} // Driver codeint main(){ unsigned int n = 7; cout<<\"Parity of no \"<<n<<\" = \"<<(getParity(n)? \"odd\": \"even\"); getchar(); return 0;} // This code is contributed by Kasina Dheeraj", "e": 5451, "s": 4974, "text": null }, { "code": null, "e": 5472, "s": 5451, "text": "Parity of no 7 = odd" }, { "code": null, "e": 5494, "s": 5472, "text": "Time Complexity: O(1)" }, { "code": null, "e": 5516, "s": 5494, "text": "Auxiliary Space: O(1)" }, { "code": null, "e": 5564, "s": 5516, "text": "Another Approach: Mapping numbers with the bit " }, { "code": null, "e": 5753, "s": 5564, "text": "We can use a map or an array of the number of bits to form a nibble (a nibble consists of 4 bits, so a 16 – length array would be required). Then, we can get the nibbles of a given number." }, { "code": null, "e": 5811, "s": 5753, "text": "This approach can be summarized into the following steps:" }, { "code": null, "e": 5932, "s": 5811, "text": "1. Build the 16 length array of the number of bits to form a nibble – { 0, 1, 1, 2, 1, 2, 2, 3, 1, 2, 2, 3, 2, 3, 3, 4 }" }, { "code": null, "e": 6140, "s": 5932, "text": "2. Recursively count the set of the bits by taking the last nibble (4 bits) from the array using the formula num & 0xf and then getting each successive nibble by discarding the last 4 bits using >> operator." }, { "code": null, "e": 6284, "s": 6140, "text": "3. Check the parity: if the number of set bits is even, ie numOfSetBits % 2 == 0, then the number is of even parity. Else, it is of odd parity." }, { "code": null, "e": 6288, "s": 6284, "text": "C++" }, { "code": null, "e": 6293, "s": 6288, "text": "Java" }, { "code": null, "e": 6301, "s": 6293, "text": "Python3" }, { "code": null, "e": 6304, "s": 6301, "text": "C#" }, { "code": null, "e": 6315, "s": 6304, "text": "Javascript" }, { "code": "// C++ program to get the parity of the// binary representation of a number #include <bits/stdc++.h>using namespace std; int nibble_to_bits[16] = { 0, 1, 1, 2, 1, 2, 2, 3, 1, 2, 2, 3, 2, 3, 3, 4 }; // Function to recursively get the nibble// of a given number and map them in the array unsigned int countSetBits(unsigned int num){ int nibble = 0; if (0 == num) return nibble_to_bits[0]; // Find last nibble nibble = num & 0xf; // Use pre-stored values to find count // in last nibble plus recursively add // remaining nibbles. return nibble_to_bits[nibble] + countSetBits(num >> 4);} // Function to get the parity of a numberbool getParity(int num) { return countSetBits(num) % 2; } // Driver codeint main(){ unsigned int n = 7; // Function call cout << \"Parity of no \" << n << \" = \" << (getParity(n) ? \"odd\" : \"even\"); return 0;} // This code is contributed by phasing17", "e": 7245, "s": 6315, "text": null }, { "code": "// Java program to get the parity of the// binary representation of a numberimport java.util.*; class GFG{ static int[] nibble_to_bits = { 0, 1, 1, 2, 1, 2, 2, 3, 1, 2, 2, 3, 2, 3, 3, 4 }; // Function to recursively get the nibble // of a given number and map them in the array static int countSetBits(int num) { int nibble = 0; if (0 == num) return nibble_to_bits[0]; // Find last nibble nibble = num & 0xf; // Use pre-stored values to find count // in last nibble plus recursively add // remaining nibbles. return nibble_to_bits[nibble] + countSetBits(num >> 4); } // Function to get the parity of a number static boolean getParity(int num) { return countSetBits(num) % 2 == 1; } // Driver codepublic static void main(String[] args){ int n = 7; // Function call System.out.print( \"Parity of no \" + n + \" = \" + (getParity(n) ? \"odd\" : \"even\"));}} // This code is contributed by sanjoy_62.", "e": 8310, "s": 7245, "text": null }, { "code": "# Python3 program to get the parity of the# binary representation of a numbernibble_to_bits = [0, 1, 1, 2, 1, 2, 2, 3, 1, 2, 2, 3, 2, 3, 3, 4] # Function to recursively get the nibble# of a given number and map them in the arraydef countSetBits(num): nibble = 0 if (0 == num): return nibble_to_bits[0] # Find last nibble nibble = num & 0xf # Use pre-stored values to find count # in last nibble plus recursively add # remaining nibbles. return nibble_to_bits[nibble] + countSetBits(num >> 4) # Function to get the parity of a numberdef getParity(num): return countSetBits(num) % 2 # Driver coden = 7 # Function callprint(\"Parity of no\", n, \" = \", [\"even\", \"odd\"][getParity(n)]) # This code is contributed by phasing17", "e": 9064, "s": 8310, "text": null }, { "code": "// C# program to get the parity of the// binary representation of a numberusing System; class GFG { static int[] nibble_to_bits = { 0, 1, 1, 2, 1, 2, 2, 3, 1, 2, 2, 3, 2, 3, 3, 4 }; // Function to recursively get the nibble // of a given number and map them in the array static int countSetBits(int num) { int nibble = 0; if (0 == num) return nibble_to_bits[0]; // Find last nibble nibble = num & 0xf; // Use pre-stored values to find count // in last nibble plus recursively add // remaining nibbles. return nibble_to_bits[nibble] + countSetBits(num >> 4); } // Function to get the parity of a number static bool getParity(int num) { return countSetBits(num) % 2 == 1; } // Driver code public static void Main(string[] args) { int n = 7; // Function call Console.WriteLine( \"Parity of no \" + n + \" = \" + (getParity(n) ? \"odd\" : \"even\")); }} // This code is contributed by phasing17", "e": 10135, "s": 9064, "text": null }, { "code": "// JavaScript program to get the parity of the// binary representation of a number let nibble_to_bits = [ 0, 1, 1, 2, 1, 2, 2, 3, 1, 2, 2, 3, 2, 3, 3, 4 ]; // Function to recursively get the nibble// of a given number and map them in the array function countSetBits(num){ let nibble = 0; if (0 == num) return nibble_to_bits[0]; // Find last nibble nibble = num & 0xf; // Use pre-stored values to find count // in last nibble plus recursively add // remaining nibbles. return nibble_to_bits[nibble] + countSetBits(num >> 4);} // Function to get the parity of a numberfunction getParity(num) { return countSetBits(num) % 2; } // Driver codelet n = 7; // Function callconsole.log(\"Parity of no \" + n + \" = \"+ (getParity(n) ? \"odd\" : \"even\")); // This code is contributed by phasing17", "e": 10954, "s": 10135, "text": null }, { "code": null, "e": 10975, "s": 10954, "text": "Parity of no 7 = odd" }, { "code": null, "e": 10997, "s": 10975, "text": "Time Complexity: O(1)" }, { "code": null, "e": 11019, "s": 10997, "text": "Auxiliary Space: O(1)" }, { "code": null, "e": 11136, "s": 11019, "text": "Uses: Parity is used in error detection and cryptography. Compute the parity of a number using XOR and table look-up" }, { "code": null, "e": 11243, "s": 11136, "text": "References: http://graphics.stanford.edu/~seander/bithacks.html#ParityNaive – last checked on 30 May 2009." }, { "code": null, "e": 11256, "s": 11243, "text": "nitin mittal" }, { "code": null, "e": 11261, "s": 11256, "text": "vt_m" }, { "code": null, "e": 11278, "s": 11261, "text": "SURENDRA_GANGWAR" }, { "code": null, "e": 11291, "s": 11278, "text": "Kirti_Mangal" }, { "code": null, "e": 11307, "s": 11291, "text": "rishavmahato348" }, { "code": null, "e": 11320, "s": 11307, "text": "dheerukd2002" }, { "code": null, "e": 11335, "s": 11320, "text": "ranjanrohit840" }, { "code": null, "e": 11345, "s": 11335, "text": "phasing17" }, { "code": null, "e": 11354, "s": 11345, "text": "sweetyty" }, { "code": null, "e": 11364, "s": 11354, "text": "sanjoy_62" }, { "code": null, "e": 11377, "s": 11364, "text": "cryptography" }, { "code": null, "e": 11387, "s": 11377, "text": "Bit Magic" }, { "code": null, "e": 11400, "s": 11387, "text": "Mathematical" }, { "code": null, "e": 11413, "s": 11400, "text": "Mathematical" }, { "code": null, "e": 11423, "s": 11413, "text": "Bit Magic" }, { "code": null, "e": 11436, "s": 11423, "text": "cryptography" }, { "code": null, "e": 11534, "s": 11436, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 11564, "s": 11534, "text": "Little and Big Endian Mystery" }, { "code": null, "e": 11617, "s": 11564, "text": "Program to find whether a given number is power of 2" }, { "code": null, "e": 11657, "s": 11617, "text": "Binary representation of a given number" }, { "code": null, "e": 11700, "s": 11657, "text": "Josephus problem | Set 1 (A O(n) Solution)" }, { "code": null, "e": 11776, "s": 11700, "text": "Divide two integers without using multiplication, division and mod operator" }, { "code": null, "e": 11806, "s": 11776, "text": "Program for Fibonacci numbers" }, { "code": null, "e": 11849, "s": 11806, "text": "Set in C++ Standard Template Library (STL)" }, { "code": null, "e": 11909, "s": 11849, "text": "Write a program to print all permutations of a given string" }, { "code": null, "e": 11924, "s": 11909, "text": "C++ Data Types" } ]
Quantum Teleportation in Python
23 Sep, 2021 In this article, we are going to see Quantum teleportation using Python. How many times have the Rick and Morty episodes have their storylines started through Rick and Morty walking through their portal to some crazy alternate dimension? If it weren’t for the portal, we might not have had everyone’s favorite animated TV show. But have you ever given some thought to how that portal works? That is what we will be talking about today Quantum Teleportation. Aside from the fact that it would be completely awesome? Well, as we already know, Quantum Computers are not really similar to Classical computers. One such difference between the two is copying data. If you need to copy off your friend’s assignment, all that you do is that you click on the data and make a copy of it, right? Well, the thing about Quantum bits is that they remain in the Quantum state till they are unobserved. As soon as we observe (or click) on them, they collapse to one of the known states. This is also called the no-cloning theorem. Hence, to copy data on a Quantum Computer, we need the process of Quantum Teleportation. With technological advancements, however, Quantum Teleportation has gone from this to become an application for completely secure transmissions. For simplicity, let’s assume there are two friends, Kartik and Sharanya. Sharanya wants to send some form of Quantum data, possibly a qubit to Kartik. Since she can’t observe what the state of the qubit is due to the no-cloning theorem, she takes the help of the so-called ‘portal’, to transfer the data. So what the portal basically does is, that it creates entanglement between one qubit from Sharanya and one qubit of its own and sends the entangled pair towards Kartik. Then, Kartik would have to perform some actions to remove the entanglement and receive the output. For those of you who don’t have much of an idea as to what Quantum Entanglement is, in a nutshell, it states that if something happens to one qubit, we can expect the other qubit to also have some impact, even if the two qubits are nowhere near each other. Also, another interesting thing to note why this is called Quantum Teleportation is that Sharanya no longer has the exact same qubit that she did, which is now with Kartik. Step 1: The portal creates an entangled pair of Qubits, which is a special pair known as Bell’s pair. In order to create a Bell’s pair using Quantum Circuits, we need to take one qubit and turn it into the (|+> or |->) state using a Hadamard gate and then using a CNOT gate on the other qubit, which will be controlled by the first qubit. One of the qubits is given to Sharanya (say Q1), the other to Kartik (say Q2). Step 2: Let’s say that the qubit Sharanya wants to send is |Ψ> = |∝> + |β>. She needs to applied a CNOT gate to Q1, controlled by |Ψ>. A CNOT gate is basically the ‘if this, then that’ condition of the Quantum world. Step 3: Sharanya takes a measurement of the two qubits that she has, and stores them in two classical bits. She then sends this information to Kartik (A transfer can be made since classical bits are being sent). Since qubits can handle 2n classical bits, we can say that the outputs Sharanya will get with her calculation will always be a probabilistic answer containing 00, 01, 10, and 11 (all permutations of 0 and 1). Step 4: Now, all that Kartik needs to do is perform certain transformations on the qubit he has, Q2, which is a part of an entangled pair. This part comes from Quantum Mechanics, so you can just know it as a fact, or the complexity of the article will increase manifolds. So, if Kartik gets a 00, he needs to apply for an I gate. For 01, a X gate needs to be applied, for 10, a Z gate needs to be applied and for 11, a ZX gate needs to be applied. And there, we have it. Kartik now has a qubit in the same state as the state Sharanya initially had her qubit in. Qiskit: Qiskit is an open-source framework for quantum computing. It provides tools for creating and manipulating quantum programs and running them on prototype quantum devices on IBM Q Experience or on simulators on a local computer. Let’s see how we can create a simple Quantum circuit and test it on a real Quantum computer or simulate it in our computer locally. Installation: pip install qiskit Step 1: Creating the Quantum Circuit on which we will be doing operations. QuantumCircuit takes in 2 arguments, the number of qubits that we want to take and the number of classical bits that we want to take. Python from qiskit import * circuit = QuantumCircuit(3, 3)%matplotlib inline # Whenever during any point of the program we# want to see how our circuit looks like,# this is what we will be doing.circuit.draw(output='mpl') Output: This is how our circuit looks right now. We have three quantum bits and 3 classical bits, which will be used to measure the values of these Qubits, whenever we want. Right now they don’t have any value in them. Step 2: Applying an X gate on the qubit which we have to teleport. We will also be adding a barrier, just to make the circuit more clear. Now here, what we have done till now is that we have 3 qubits. What we’ll be doing is that we will be using q1 to transport data from q0 to q3. For this, we will use an X gate to init q0 to 1 state Python circuit.x(0) # used to apply an X gate. # This is done to make the circuit look more # organized and clear.circuit.barrier()circuit.draw(output='mpl') Output: This is how our circuit looks right now. On one of the Qubits, we have added an X gate, shown by the X. A barrier is added to make the circuit more organized as we keep on adding gates and other things. The classical bits are still untouched. Step 3: Creating entanglement between Q1 and Q2 by applying a Hadamard gate on Q1, and a CX gate on Q1 and Q2 in such a way that the behavior of Q1 affects the behavior of Q2. Here, what we’ll do is that we will create entanglement so that the behavior of the first qubit affects the behavior of the second qubit. Python # This is how we apply a Hadamard gate on Q1.circuit.h(1) # This is the CX gate, which takes two parameters,# one being the control qubit and the# other being the target qubit.circuit.cx(1, 2)circuit.draw(output='mpl') Output: Here we can see that after this step, this is how our circuit looks. We have a Hadamard gate applied to Q1, shown by the ‘H’ Symbol, and a Controlled NOT(CX) gate on Q1 and Q2. The classical bits are still untouched. Creating entanglement between Q0 and Q1 by applying a Hadamard gate on Q0, and a CX gate on Q0 and Q1 in such a way that the behavior of Q1 affects the behavior of Q0. So essentially, we have a system where the behavior of either of the Qubits will affect the behavior of all the Qubits. Q1 can be considered as the portal we talked of, above. We will also now project the Qubits on the classical bits and measure the values of Q0 and Q1. Python # The next step is to create a controlled# gate between qubit 0 and qubit 1.# Also we will be applying a Hadamard gate to q0.circuit.cx(0, 1)circuit.h(0) # Done for clarification of the circuit again.circuit.barrier() # the next step is to do the two measurements# on q0 and q1.circuit.measure([0, 1], [0, 1]) # circuit.measure can take any number of arguments,# and has the following parameters:# [qubit whos value is to be measured,# classical bit where the value is stored]circuit.draw(output='mpl') Output: Here we can see how our circuit looks. With the help of barriers, you can easily distinguish what was done in this step. We have a Hadamard gate applied to Q0, shown by the ‘H’ Symbol, and a Controlled NOT(CX) gate on Q0 and Q1. The classical bits are now put to use, with the black symbols showing that we have taken the value of Q0 and Q1 and stored it in classical bit 1 and classical bit 2. The actual explanation will require an understanding of Quantum mechanics, so one can just understand that for a 00 measurement of the classical bits, we need to apply an I gate. For 01, an X gate needs to be applied, for 10, a Z gate needs to be applied and for 11, a ZX gate needs to be applied. Since we don’t know what the value will be stored in classical bits, we are applying the more generalized Control X gates and Control Z gates. The last step is to add two more gates, a controlled x gate and a controlled z gate (We have talked about this step in the text above, which tells what gates to apply for different measurements). Python circuit.barrier()circuit.cx(1, 2)circuit.cz(0, 2)circuit.draw(output='mpl') Output: This is the final required circuit for Quantum Teleportation. After the barrier, we can see that a Controlled X gate has been applied on Q1 and Q2, such that the behavior of Q2 affects the behavior of Q1. Also, a Control Z gate has been applied as shown between Q0 and Q2. Now that our circuit has been made, all we need to do is to pass that circuit into a simulator so that we can get the results from the circuit back. Once we get the results back, we are plotting a histogram from the values of the classical bits that we have received. You can think of whatever we have done now as an Abstract Data Type created by us, and the code below is the main function where we will put it to use. Each step has been explained in complete detail for easy understanding of the reader. Python # The first step is to call a simulator# which we will use to perform simulations.from qiskit.tools.visualization import plot_histogramsim = Aer.get_backend('qasm_simulator') # here, like before, we have given the# classical bit 2 the value of the Quantum bit 2.circuit.measure(2, 2) # Now, we run the execute function,# which takes our quantum circuit,# the backend which we are using and# the number of shots we want# (shots are to increase accuracy and# mitigate errors in Quantum Computing).# All of this is stored in a variable called result result = execute(circuit, backend=sim, shots=1000).result()counts = result.get_counts() # This counts variable shows that for each possible combination,# how many times the circuit gave a similar output# (for example, 111 came x times, 101 came y times etc.) # importing plot_histogram which will help us visualize the results.plot_histogram(counts) Output: Well, let’s see here. For 3 qubits, we can have states like 100, 101, 111, 001, and so on (8 of them to be precise, basic P&C stuff). Now, if I take one value from the x-axis, it is read in the following way: [100] = [Value stored in classical bit 2, value stored in classical bit 1, value stored in classical bit 0] We said that we will produce the same state on the first qubit on the second qubit. The state on the first qubit (the one which Sharanya had (Q0)) was 1, And look here, we have only received the permutations, where the value of the second classical bit is 1, which proves that the value on the second qubit (the one which Kartik had (Q2)) was 1 as well! Blogathon-2021 python-utility Blogathon Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Import JSON Data into SQL Server? SQL Query to Convert Datetime to Date Python program to convert XML to Dictionary Scrape LinkedIn Using Selenium And Beautiful Soup in Python How to toggle password visibility in forms using Bootstrap-icons ? Read JSON file using Python Python map() function Adding new column to existing DataFrame in Pandas Python Dictionary How to get column names in Pandas dataframe
[ { "code": null, "e": 54, "s": 26, "text": "\n23 Sep, 2021" }, { "code": null, "e": 127, "s": 54, "text": "In this article, we are going to see Quantum teleportation using Python." }, { "code": null, "e": 512, "s": 127, "text": "How many times have the Rick and Morty episodes have their storylines started through Rick and Morty walking through their portal to some crazy alternate dimension? If it weren’t for the portal, we might not have had everyone’s favorite animated TV show. But have you ever given some thought to how that portal works? That is what we will be talking about today Quantum Teleportation." }, { "code": null, "e": 1304, "s": 512, "text": "Aside from the fact that it would be completely awesome? Well, as we already know, Quantum Computers are not really similar to Classical computers. One such difference between the two is copying data. If you need to copy off your friend’s assignment, all that you do is that you click on the data and make a copy of it, right? Well, the thing about Quantum bits is that they remain in the Quantum state till they are unobserved. As soon as we observe (or click) on them, they collapse to one of the known states. This is also called the no-cloning theorem. Hence, to copy data on a Quantum Computer, we need the process of Quantum Teleportation. With technological advancements, however, Quantum Teleportation has gone from this to become an application for completely secure transmissions. " }, { "code": null, "e": 1878, "s": 1304, "text": "For simplicity, let’s assume there are two friends, Kartik and Sharanya. Sharanya wants to send some form of Quantum data, possibly a qubit to Kartik. Since she can’t observe what the state of the qubit is due to the no-cloning theorem, she takes the help of the so-called ‘portal’, to transfer the data. So what the portal basically does is, that it creates entanglement between one qubit from Sharanya and one qubit of its own and sends the entangled pair towards Kartik. Then, Kartik would have to perform some actions to remove the entanglement and receive the output. " }, { "code": null, "e": 2310, "s": 1878, "text": "For those of you who don’t have much of an idea as to what Quantum Entanglement is, in a nutshell, it states that if something happens to one qubit, we can expect the other qubit to also have some impact, even if the two qubits are nowhere near each other. Also, another interesting thing to note why this is called Quantum Teleportation is that Sharanya no longer has the exact same qubit that she did, which is now with Kartik. " }, { "code": null, "e": 2729, "s": 2310, "text": "Step 1: The portal creates an entangled pair of Qubits, which is a special pair known as Bell’s pair. In order to create a Bell’s pair using Quantum Circuits, we need to take one qubit and turn it into the (|+> or |->) state using a Hadamard gate and then using a CNOT gate on the other qubit, which will be controlled by the first qubit. One of the qubits is given to Sharanya (say Q1), the other to Kartik (say Q2). " }, { "code": null, "e": 2947, "s": 2729, "text": "Step 2: Let’s say that the qubit Sharanya wants to send is |Ψ> = |∝> + |β>. She needs to applied a CNOT gate to Q1, controlled by |Ψ>. A CNOT gate is basically the ‘if this, then that’ condition of the Quantum world. " }, { "code": null, "e": 3369, "s": 2947, "text": "Step 3: Sharanya takes a measurement of the two qubits that she has, and stores them in two classical bits. She then sends this information to Kartik (A transfer can be made since classical bits are being sent). Since qubits can handle 2n classical bits, we can say that the outputs Sharanya will get with her calculation will always be a probabilistic answer containing 00, 01, 10, and 11 (all permutations of 0 and 1). " }, { "code": null, "e": 3818, "s": 3369, "text": "Step 4: Now, all that Kartik needs to do is perform certain transformations on the qubit he has, Q2, which is a part of an entangled pair. This part comes from Quantum Mechanics, so you can just know it as a fact, or the complexity of the article will increase manifolds. So, if Kartik gets a 00, he needs to apply for an I gate. For 01, a X gate needs to be applied, for 10, a Z gate needs to be applied and for 11, a ZX gate needs to be applied. " }, { "code": null, "e": 3933, "s": 3818, "text": "And there, we have it. Kartik now has a qubit in the same state as the state Sharanya initially had her qubit in. " }, { "code": null, "e": 4301, "s": 3933, "text": "Qiskit: Qiskit is an open-source framework for quantum computing. It provides tools for creating and manipulating quantum programs and running them on prototype quantum devices on IBM Q Experience or on simulators on a local computer. Let’s see how we can create a simple Quantum circuit and test it on a real Quantum computer or simulate it in our computer locally." }, { "code": null, "e": 4315, "s": 4301, "text": "Installation:" }, { "code": null, "e": 4334, "s": 4315, "text": "pip install qiskit" }, { "code": null, "e": 4410, "s": 4334, "text": "Step 1: Creating the Quantum Circuit on which we will be doing operations. " }, { "code": null, "e": 4545, "s": 4410, "text": "QuantumCircuit takes in 2 arguments, the number of qubits that we want to take and the number of classical bits that we want to take. " }, { "code": null, "e": 4552, "s": 4545, "text": "Python" }, { "code": "from qiskit import * circuit = QuantumCircuit(3, 3)%matplotlib inline # Whenever during any point of the program we# want to see how our circuit looks like,# this is what we will be doing.circuit.draw(output='mpl')", "e": 4769, "s": 4552, "text": null }, { "code": null, "e": 4778, "s": 4769, "text": "Output: " }, { "code": null, "e": 4990, "s": 4778, "text": "This is how our circuit looks right now. We have three quantum bits and 3 classical bits, which will be used to measure the values of these Qubits, whenever we want. Right now they don’t have any value in them. " }, { "code": null, "e": 5129, "s": 4990, "text": "Step 2: Applying an X gate on the qubit which we have to teleport. We will also be adding a barrier, just to make the circuit more clear. " }, { "code": null, "e": 5328, "s": 5129, "text": "Now here, what we have done till now is that we have 3 qubits. What we’ll be doing is that we will be using q1 to transport data from q0 to q3. For this, we will use an X gate to init q0 to 1 state " }, { "code": null, "e": 5335, "s": 5328, "text": "Python" }, { "code": "circuit.x(0) # used to apply an X gate. # This is done to make the circuit look more # organized and clear.circuit.barrier()circuit.draw(output='mpl')", "e": 5488, "s": 5335, "text": null }, { "code": null, "e": 5496, "s": 5488, "text": "Output:" }, { "code": null, "e": 5740, "s": 5496, "text": "This is how our circuit looks right now. On one of the Qubits, we have added an X gate, shown by the X. A barrier is added to make the circuit more organized as we keep on adding gates and other things. The classical bits are still untouched. " }, { "code": null, "e": 5917, "s": 5740, "text": "Step 3: Creating entanglement between Q1 and Q2 by applying a Hadamard gate on Q1, and a CX gate on Q1 and Q2 in such a way that the behavior of Q1 affects the behavior of Q2. " }, { "code": null, "e": 6056, "s": 5917, "text": "Here, what we’ll do is that we will create entanglement so that the behavior of the first qubit affects the behavior of the second qubit. " }, { "code": null, "e": 6063, "s": 6056, "text": "Python" }, { "code": "# This is how we apply a Hadamard gate on Q1.circuit.h(1) # This is the CX gate, which takes two parameters,# one being the control qubit and the# other being the target qubit.circuit.cx(1, 2)circuit.draw(output='mpl')", "e": 6283, "s": 6063, "text": null }, { "code": null, "e": 6291, "s": 6283, "text": "Output:" }, { "code": null, "e": 6509, "s": 6291, "text": "Here we can see that after this step, this is how our circuit looks. We have a Hadamard gate applied to Q1, shown by the ‘H’ Symbol, and a Controlled NOT(CX) gate on Q1 and Q2. The classical bits are still untouched. " }, { "code": null, "e": 6949, "s": 6509, "text": "Creating entanglement between Q0 and Q1 by applying a Hadamard gate on Q0, and a CX gate on Q0 and Q1 in such a way that the behavior of Q1 affects the behavior of Q0. So essentially, we have a system where the behavior of either of the Qubits will affect the behavior of all the Qubits. Q1 can be considered as the portal we talked of, above. We will also now project the Qubits on the classical bits and measure the values of Q0 and Q1. " }, { "code": null, "e": 6956, "s": 6949, "text": "Python" }, { "code": "# The next step is to create a controlled# gate between qubit 0 and qubit 1.# Also we will be applying a Hadamard gate to q0.circuit.cx(0, 1)circuit.h(0) # Done for clarification of the circuit again.circuit.barrier() # the next step is to do the two measurements# on q0 and q1.circuit.measure([0, 1], [0, 1]) # circuit.measure can take any number of arguments,# and has the following parameters:# [qubit whos value is to be measured,# classical bit where the value is stored]circuit.draw(output='mpl')", "e": 7462, "s": 6956, "text": null }, { "code": null, "e": 7471, "s": 7462, "text": "Output: " }, { "code": null, "e": 7867, "s": 7471, "text": "Here we can see how our circuit looks. With the help of barriers, you can easily distinguish what was done in this step. We have a Hadamard gate applied to Q0, shown by the ‘H’ Symbol, and a Controlled NOT(CX) gate on Q0 and Q1. The classical bits are now put to use, with the black symbols showing that we have taken the value of Q0 and Q1 and stored it in classical bit 1 and classical bit 2. " }, { "code": null, "e": 8310, "s": 7867, "text": "The actual explanation will require an understanding of Quantum mechanics, so one can just understand that for a 00 measurement of the classical bits, we need to apply an I gate. For 01, an X gate needs to be applied, for 10, a Z gate needs to be applied and for 11, a ZX gate needs to be applied. Since we don’t know what the value will be stored in classical bits, we are applying the more generalized Control X gates and Control Z gates. " }, { "code": null, "e": 8507, "s": 8310, "text": "The last step is to add two more gates, a controlled x gate and a controlled z gate (We have talked about this step in the text above, which tells what gates to apply for different measurements). " }, { "code": null, "e": 8514, "s": 8507, "text": "Python" }, { "code": "circuit.barrier()circuit.cx(1, 2)circuit.cz(0, 2)circuit.draw(output='mpl')", "e": 8590, "s": 8514, "text": null }, { "code": null, "e": 8599, "s": 8590, "text": "Output: " }, { "code": null, "e": 8873, "s": 8599, "text": "This is the final required circuit for Quantum Teleportation. After the barrier, we can see that a Controlled X gate has been applied on Q1 and Q2, such that the behavior of Q2 affects the behavior of Q1. Also, a Control Z gate has been applied as shown between Q0 and Q2. " }, { "code": null, "e": 9380, "s": 8873, "text": "Now that our circuit has been made, all we need to do is to pass that circuit into a simulator so that we can get the results from the circuit back. Once we get the results back, we are plotting a histogram from the values of the classical bits that we have received. You can think of whatever we have done now as an Abstract Data Type created by us, and the code below is the main function where we will put it to use. Each step has been explained in complete detail for easy understanding of the reader. " }, { "code": null, "e": 9387, "s": 9380, "text": "Python" }, { "code": "# The first step is to call a simulator# which we will use to perform simulations.from qiskit.tools.visualization import plot_histogramsim = Aer.get_backend('qasm_simulator') # here, like before, we have given the# classical bit 2 the value of the Quantum bit 2.circuit.measure(2, 2) # Now, we run the execute function,# which takes our quantum circuit,# the backend which we are using and# the number of shots we want# (shots are to increase accuracy and# mitigate errors in Quantum Computing).# All of this is stored in a variable called result result = execute(circuit, backend=sim, shots=1000).result()counts = result.get_counts() # This counts variable shows that for each possible combination,# how many times the circuit gave a similar output# (for example, 111 came x times, 101 came y times etc.) # importing plot_histogram which will help us visualize the results.plot_histogram(counts)", "e": 10289, "s": 9387, "text": null }, { "code": null, "e": 10298, "s": 10289, "text": "Output: " }, { "code": null, "e": 10508, "s": 10298, "text": "Well, let’s see here. For 3 qubits, we can have states like 100, 101, 111, 001, and so on (8 of them to be precise, basic P&C stuff). Now, if I take one value from the x-axis, it is read in the following way: " }, { "code": null, "e": 10616, "s": 10508, "text": "[100] = [Value stored in classical bit 2, value stored in classical bit 1, value stored in classical bit 0]" }, { "code": null, "e": 10971, "s": 10616, "text": "We said that we will produce the same state on the first qubit on the second qubit. The state on the first qubit (the one which Sharanya had (Q0)) was 1, And look here, we have only received the permutations, where the value of the second classical bit is 1, which proves that the value on the second qubit (the one which Kartik had (Q2)) was 1 as well! " }, { "code": null, "e": 10986, "s": 10971, "text": "Blogathon-2021" }, { "code": null, "e": 11001, "s": 10986, "text": "python-utility" }, { "code": null, "e": 11011, "s": 11001, "text": "Blogathon" }, { "code": null, "e": 11018, "s": 11011, "text": "Python" }, { "code": null, "e": 11116, "s": 11018, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 11157, "s": 11116, "text": "How to Import JSON Data into SQL Server?" }, { "code": null, "e": 11195, "s": 11157, "text": "SQL Query to Convert Datetime to Date" }, { "code": null, "e": 11239, "s": 11195, "text": "Python program to convert XML to Dictionary" }, { "code": null, "e": 11299, "s": 11239, "text": "Scrape LinkedIn Using Selenium And Beautiful Soup in Python" }, { "code": null, "e": 11366, "s": 11299, "text": "How to toggle password visibility in forms using Bootstrap-icons ?" }, { "code": null, "e": 11394, "s": 11366, "text": "Read JSON file using Python" }, { "code": null, "e": 11416, "s": 11394, "text": "Python map() function" }, { "code": null, "e": 11466, "s": 11416, "text": "Adding new column to existing DataFrame in Pandas" }, { "code": null, "e": 11484, "s": 11466, "text": "Python Dictionary" } ]
JavaScript | Hoisting
25 May, 2022 In JavaScript, Hoisting is the default behavior of moving all the declarations at the top of the scope before code execution. Basically, it gives us an advantage that no matter where functions and variables are declared, they are moved to the top of their scope regardless of whether their scope is global or local. It allows us to call functions before even writing them in our code. Note: JavaScript only hoists declarations, not the initializations. JavaScript allocates memory for all variables and functions defined in the program before execution. Let us understand what exactly this is: The following is the sequence in which variable declaration and initialization occur. Declaration –> Initialisation/Assignment –> Usage // Variable lifecycle let a; // Declaration a = 100; // Assignment console.log(a); // Usage However, since JavaScript allows us to both declare and initialize our variables simultaneously, this is the most used pattern: let a = 100; Note: Always remember that in the background the Javascript is first declaring the variable and then initializing them. It is also good to know that variable declarations are processed before any code is executed. However, in javascript, undeclared variables do not exist until code assigning them is executed. Therefore, assigning a value to an undeclared variable implicitly creates it as a global variable when the assignment is executed. This means that all undeclared variables are global variables. Javascript // hoistingfunction codeHoist(){ a = 10; let b = 50;}codeHoist(); console.log(a); // 10console.log(b); // ReferenceError : b is not defined Output: Explanation: In the above code sample we created a function called codeHoist() and in there we have a variable which we didn’t declare using let/var/const and a let variable b. The undeclared variable is assigned the global scope by javascript hence we are able to print it outside the function, but in case of the variable b the scope is confined and it is not available outside and we get a ReferenceError. Note: There’s a difference between ReferenceError and undefined error. An undefined error occurs when we have a variable that is either not defined or explicitly defined as type undefined. ReferenceError is thrown when trying to access a previously undeclared variable. ES5 When we talk about ES5, the variable that comes into our minds is var. Hoisting with var is somewhat different as when compared to let/const. Let’s make use of var and see how hoisting works: Javascript // var code (global)console.log(name); // undefinedvar name = 'Mukul Latiyan'; Output: Explanation: In the above code we tried to console the variable name which was declared and assigned later than using it, the compiler gives us undefined which we didn’t expect as we should have got ReferenceError as we were trying to use name variable even before declaring it. But the interpreter sees this differently, the above code is seen like this: Javascript //how interpreter sees the above codevar name;console.log(name); // undefinedname = 'Mukul Latiyan'; Output: Function scoped variable Let’s look at how function scoped variables are hoisted. Javascript //function scopedfunction fun(){ console.log(name); var name = 'Mukul Latiyan';}fun(); // undefined Output: There is no difference here as when compared to the code where we declared the variable globally, we get undefined as the code seen by the interpreter is: Javascript //function scopedfunction fun(){ var name; console.log(name); name = 'Mukul Latiyan';}fun(); // undefined Output: In order to avoid this pitfall, we can make sure to declare and assign the variable at the same time, before using it. Something like this: Javascript //in order to avoid itfunction fun(){ var name = 'Mukul Latiyan'; console.log(name); // Mukul Latiyan}fun(); Output: ES6 Let We know that variables declared with let keywords are block scoped not function scoped and hence it is not any kind of problem when it comes to hoisting. Example: Javascript //let example(global)console.log(name);let name='Mukul Latiyan'; // ReferenceError: name is not defined Output: Like before, for the var keyword, we expect the output of the log to be undefined. However, since the es6 let doesn’t take kindly on us using undeclared variables, the interpreter explicitly spits out a Reference error. This ensures that we always declare our variable first. const behaves similar to let when it comes to hoisting. immukul Akanksha_Rai kbhattacharyya88 sweetyty surinderdawra388 javascript-basics JavaScript Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. File uploading in React.js Hide or show elements in HTML using display property How to Open URL in New Tab using JavaScript ? Node.js | fs.writeFileSync() Method How do you run JavaScript script through the Terminal? JavaScript | console.log() with Examples How to append HTML code to a div using JavaScript ? JavaScript String includes() Method Send unlimited Whatsapp messages using JavaScript Set the value of an input field in JavaScript
[ { "code": null, "e": 52, "s": 24, "text": "\n25 May, 2022" }, { "code": null, "e": 369, "s": 52, "text": "In JavaScript, Hoisting is the default behavior of moving all the declarations at the top of the scope before code execution. Basically, it gives us an advantage that no matter where functions and variables are declared, they are moved to the top of their scope regardless of whether their scope is global or local. " }, { "code": null, "e": 439, "s": 369, "text": "It allows us to call functions before even writing them in our code. " }, { "code": null, "e": 507, "s": 439, "text": "Note: JavaScript only hoists declarations, not the initializations." }, { "code": null, "e": 608, "s": 507, "text": "JavaScript allocates memory for all variables and functions defined in the program before execution." }, { "code": null, "e": 735, "s": 608, "text": "Let us understand what exactly this is: The following is the sequence in which variable declaration and initialization occur. " }, { "code": null, "e": 786, "s": 735, "text": "Declaration –> Initialisation/Assignment –> Usage " }, { "code": null, "e": 891, "s": 786, "text": "// Variable lifecycle\nlet a; // Declaration\na = 100; // Assignment\nconsole.log(a); // Usage" }, { "code": null, "e": 1021, "s": 891, "text": "However, since JavaScript allows us to both declare and initialize our variables simultaneously, this is the most used pattern: " }, { "code": null, "e": 1034, "s": 1021, "text": "let a = 100;" }, { "code": null, "e": 1249, "s": 1034, "text": "Note: Always remember that in the background the Javascript is first declaring the variable and then initializing them. It is also good to know that variable declarations are processed before any code is executed. " }, { "code": null, "e": 1540, "s": 1249, "text": "However, in javascript, undeclared variables do not exist until code assigning them is executed. Therefore, assigning a value to an undeclared variable implicitly creates it as a global variable when the assignment is executed. This means that all undeclared variables are global variables." }, { "code": null, "e": 1551, "s": 1540, "text": "Javascript" }, { "code": "// hoistingfunction codeHoist(){ a = 10; let b = 50;}codeHoist(); console.log(a); // 10console.log(b); // ReferenceError : b is not defined", "e": 1697, "s": 1551, "text": null }, { "code": null, "e": 1706, "s": 1697, "text": "Output: " }, { "code": null, "e": 2115, "s": 1706, "text": "Explanation: In the above code sample we created a function called codeHoist() and in there we have a variable which we didn’t declare using let/var/const and a let variable b. The undeclared variable is assigned the global scope by javascript hence we are able to print it outside the function, but in case of the variable b the scope is confined and it is not available outside and we get a ReferenceError." }, { "code": null, "e": 2386, "s": 2115, "text": "Note: There’s a difference between ReferenceError and undefined error. An undefined error occurs when we have a variable that is either not defined or explicitly defined as type undefined. ReferenceError is thrown when trying to access a previously undeclared variable. " }, { "code": null, "e": 2390, "s": 2386, "text": "ES5" }, { "code": null, "e": 2584, "s": 2390, "text": "When we talk about ES5, the variable that comes into our minds is var. Hoisting with var is somewhat different as when compared to let/const. Let’s make use of var and see how hoisting works: " }, { "code": null, "e": 2595, "s": 2584, "text": "Javascript" }, { "code": "// var code (global)console.log(name); // undefinedvar name = 'Mukul Latiyan';", "e": 2674, "s": 2595, "text": null }, { "code": null, "e": 2683, "s": 2674, "text": "Output: " }, { "code": null, "e": 2963, "s": 2683, "text": "Explanation: In the above code we tried to console the variable name which was declared and assigned later than using it, the compiler gives us undefined which we didn’t expect as we should have got ReferenceError as we were trying to use name variable even before declaring it. " }, { "code": null, "e": 3042, "s": 2963, "text": "But the interpreter sees this differently, the above code is seen like this: " }, { "code": null, "e": 3053, "s": 3042, "text": "Javascript" }, { "code": "//how interpreter sees the above codevar name;console.log(name); // undefinedname = 'Mukul Latiyan';", "e": 3154, "s": 3053, "text": null }, { "code": null, "e": 3163, "s": 3154, "text": "Output: " }, { "code": null, "e": 3188, "s": 3163, "text": "Function scoped variable" }, { "code": null, "e": 3247, "s": 3188, "text": "Let’s look at how function scoped variables are hoisted. " }, { "code": null, "e": 3258, "s": 3247, "text": "Javascript" }, { "code": "//function scopedfunction fun(){ console.log(name); var name = 'Mukul Latiyan';}fun(); // undefined", "e": 3364, "s": 3258, "text": null }, { "code": null, "e": 3373, "s": 3364, "text": "Output: " }, { "code": null, "e": 3529, "s": 3373, "text": "There is no difference here as when compared to the code where we declared the variable globally, we get undefined as the code seen by the interpreter is: " }, { "code": null, "e": 3540, "s": 3529, "text": "Javascript" }, { "code": "//function scopedfunction fun(){ var name; console.log(name); name = 'Mukul Latiyan';}fun(); // undefined", "e": 3655, "s": 3540, "text": null }, { "code": null, "e": 3664, "s": 3655, "text": "Output: " }, { "code": null, "e": 3806, "s": 3664, "text": "In order to avoid this pitfall, we can make sure to declare and assign the variable at the same time, before using it. Something like this: " }, { "code": null, "e": 3817, "s": 3806, "text": "Javascript" }, { "code": "//in order to avoid itfunction fun(){ var name = 'Mukul Latiyan'; console.log(name); // Mukul Latiyan}fun();", "e": 3932, "s": 3817, "text": null }, { "code": null, "e": 3941, "s": 3932, "text": "Output: " }, { "code": null, "e": 3945, "s": 3941, "text": "ES6" }, { "code": null, "e": 4104, "s": 3945, "text": "Let We know that variables declared with let keywords are block scoped not function scoped and hence it is not any kind of problem when it comes to hoisting. " }, { "code": null, "e": 4115, "s": 4104, "text": "Example: " }, { "code": null, "e": 4126, "s": 4115, "text": "Javascript" }, { "code": "//let example(global)console.log(name);let name='Mukul Latiyan'; // ReferenceError: name is not defined", "e": 4230, "s": 4126, "text": null }, { "code": null, "e": 4239, "s": 4230, "text": "Output: " }, { "code": null, "e": 4516, "s": 4239, "text": "Like before, for the var keyword, we expect the output of the log to be undefined. However, since the es6 let doesn’t take kindly on us using undeclared variables, the interpreter explicitly spits out a Reference error. This ensures that we always declare our variable first. " }, { "code": null, "e": 4573, "s": 4516, "text": "const behaves similar to let when it comes to hoisting. " }, { "code": null, "e": 4581, "s": 4573, "text": "immukul" }, { "code": null, "e": 4594, "s": 4581, "text": "Akanksha_Rai" }, { "code": null, "e": 4611, "s": 4594, "text": "kbhattacharyya88" }, { "code": null, "e": 4620, "s": 4611, "text": "sweetyty" }, { "code": null, "e": 4637, "s": 4620, "text": "surinderdawra388" }, { "code": null, "e": 4655, "s": 4637, "text": "javascript-basics" }, { "code": null, "e": 4666, "s": 4655, "text": "JavaScript" }, { "code": null, "e": 4764, "s": 4666, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 4791, "s": 4764, "text": "File uploading in React.js" }, { "code": null, "e": 4844, "s": 4791, "text": "Hide or show elements in HTML using display property" }, { "code": null, "e": 4890, "s": 4844, "text": "How to Open URL in New Tab using JavaScript ?" }, { "code": null, "e": 4926, "s": 4890, "text": "Node.js | fs.writeFileSync() Method" }, { "code": null, "e": 4981, "s": 4926, "text": "How do you run JavaScript script through the Terminal?" }, { "code": null, "e": 5022, "s": 4981, "text": "JavaScript | console.log() with Examples" }, { "code": null, "e": 5074, "s": 5022, "text": "How to append HTML code to a div using JavaScript ?" }, { "code": null, "e": 5110, "s": 5074, "text": "JavaScript String includes() Method" }, { "code": null, "e": 5160, "s": 5110, "text": "Send unlimited Whatsapp messages using JavaScript" } ]
Python | os.getpid() method
06 Nov, 2019 OS module in Python provides functions for interacting with the operating system. OS comes under Python’s standard utility modules. This module provides a portable way of using operating system dependent functionality. os.getpid() method in Python is used to get the process ID of the current process. Syntax: os.getpid() Parameter: Not required Return Type: This method returns a integer value denoting process ID of current process. The return type of this method is of class ‘int’. Code #1: use of os.getpid() method # Python program to explain os.getpid() method # importing os module import os # Get the process ID of# the current processpid = os.getpid() # Print the process ID of# the current processprint(pid) 2699 Akanksha_Rai python-os-module Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Iterate over a list in Python Rotate axis tick labels in Seaborn and Matplotlib Enumerate() in Python Deque in Python Stack in Python Python Dictionary sum() function in Python Print lists in Python (5 Different Ways) Different ways to create Pandas Dataframe Queue in Python
[ { "code": null, "e": 28, "s": 0, "text": "\n06 Nov, 2019" }, { "code": null, "e": 247, "s": 28, "text": "OS module in Python provides functions for interacting with the operating system. OS comes under Python’s standard utility modules. This module provides a portable way of using operating system dependent functionality." }, { "code": null, "e": 330, "s": 247, "text": "os.getpid() method in Python is used to get the process ID of the current process." }, { "code": null, "e": 350, "s": 330, "text": "Syntax: os.getpid()" }, { "code": null, "e": 374, "s": 350, "text": "Parameter: Not required" }, { "code": null, "e": 513, "s": 374, "text": "Return Type: This method returns a integer value denoting process ID of current process. The return type of this method is of class ‘int’." }, { "code": null, "e": 548, "s": 513, "text": "Code #1: use of os.getpid() method" }, { "code": "# Python program to explain os.getpid() method # importing os module import os # Get the process ID of# the current processpid = os.getpid() # Print the process ID of# the current processprint(pid) ", "e": 755, "s": 548, "text": null }, { "code": null, "e": 761, "s": 755, "text": "2699\n" }, { "code": null, "e": 774, "s": 761, "text": "Akanksha_Rai" }, { "code": null, "e": 791, "s": 774, "text": "python-os-module" }, { "code": null, "e": 798, "s": 791, "text": "Python" }, { "code": null, "e": 896, "s": 798, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 926, "s": 896, "text": "Iterate over a list in Python" }, { "code": null, "e": 976, "s": 926, "text": "Rotate axis tick labels in Seaborn and Matplotlib" }, { "code": null, "e": 998, "s": 976, "text": "Enumerate() in Python" }, { "code": null, "e": 1014, "s": 998, "text": "Deque in Python" }, { "code": null, "e": 1030, "s": 1014, "text": "Stack in Python" }, { "code": null, "e": 1048, "s": 1030, "text": "Python Dictionary" }, { "code": null, "e": 1073, "s": 1048, "text": "sum() function in Python" }, { "code": null, "e": 1114, "s": 1073, "text": "Print lists in Python (5 Different Ways)" }, { "code": null, "e": 1156, "s": 1114, "text": "Different ways to create Pandas Dataframe" } ]
How to Pass Additional Context into a Class Based View (Django)?
02 Nov, 2021 Passing context into your templates from class-based views is easy once you know what to look out for. There are two ways to do it – one involves get_context_data, the other is by modifying the extra_context variable. Let see how to use both the methods one by one. Explanation: Illustration of How to use get_context_data method and extra_context variable to pass context into your templates using an example. Consider a project named geeksforgeeks having an app named geeks. Refer to the following articles to check how to create a project and an app in django. How to Create Basic Project using MVT in Django? How to Create an App in Django ? Inside the models.py add the following code: Python3 from django.db import models # Create your models here.class YourModel(models.Model): first_name = models.CharField(max_length=30) last_name = models.CharField(max_length=30) def __str__(self): return self.first_name After creating this model, we need to run two commands in order to create database for the same. python manage.py makemigrations python manage.py migrate Create the folder named templates inside the app directory(geeks) , inside this folder add the file named Intro.html and add the following code: HTML <!-- Intro.html --><!DOCTYPE html><html lang="en" dir="ltr"> <head> <meta charset="utf-8"> <title>Intro</title> </head> <body> <h1>All users name </h1> {% for user in users %} {{user.first_name}} {% endfor %} </body></html> Inside the views.py file add the following code: Python3 from django.views.generic.base import TemplateViewfrom .models import YourModel class Intro(TemplateView): template_name = 'Intro.html' def get_context_data(self,*args, **kwargs): context = super(Intro, self).get_context_data(*args,**kwargs) context['users'] = YourModel.objects.all() return context Inside the urls.py file of project named geeksforgeeks add the following code: Python3 from django.contrib import adminfrom django.urls import pathfrom geeks.views import Intro urlpatterns = [ path('admin/', admin.site.urls), path('',Intro.as_view(),name="intro")] Rewrite the views.py flle by adding the following code: Python3 from django.views.generic.base import TemplateViewfrom .models import YourModel class Intro(TemplateView): template_name = 'Intro.html' extra_context={'users': YourModel.objects.all()} By both the methods you will see the same output. Let’s check what is there on http://localhost:8000/, before doing this don’t forget to add some data to your model. How to add data to your model Django ORM – Inserting, Updating & Deleting Data sumitgumber28 Django-views Python Django Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n02 Nov, 2021" }, { "code": null, "e": 294, "s": 28, "text": "Passing context into your templates from class-based views is easy once you know what to look out for. There are two ways to do it – one involves get_context_data, the other is by modifying the extra_context variable. Let see how to use both the methods one by one." }, { "code": null, "e": 307, "s": 294, "text": "Explanation:" }, { "code": null, "e": 505, "s": 307, "text": "Illustration of How to use get_context_data method and extra_context variable to pass context into your templates using an example. Consider a project named geeksforgeeks having an app named geeks." }, { "code": null, "e": 689, "s": 505, "text": "Refer to the following articles to check how to create a project and an app in django.\n\n How to Create Basic Project using MVT in Django?\n How to Create an App in Django ?" }, { "code": null, "e": 734, "s": 689, "text": "Inside the models.py add the following code:" }, { "code": null, "e": 742, "s": 734, "text": "Python3" }, { "code": "from django.db import models # Create your models here.class YourModel(models.Model): first_name = models.CharField(max_length=30) last_name = models.CharField(max_length=30) def __str__(self): return self.first_name", "e": 975, "s": 742, "text": null }, { "code": null, "e": 1072, "s": 975, "text": "After creating this model, we need to run two commands in order to create database for the same." }, { "code": null, "e": 1129, "s": 1072, "text": "python manage.py makemigrations\npython manage.py migrate" }, { "code": null, "e": 1274, "s": 1129, "text": "Create the folder named templates inside the app directory(geeks) , inside this folder add the file named Intro.html and add the following code:" }, { "code": null, "e": 1279, "s": 1274, "text": "HTML" }, { "code": "<!-- Intro.html --><!DOCTYPE html><html lang=\"en\" dir=\"ltr\"> <head> <meta charset=\"utf-8\"> <title>Intro</title> </head> <body> <h1>All users name </h1> {% for user in users %} {{user.first_name}} {% endfor %} </body></html>", "e": 1525, "s": 1279, "text": null }, { "code": null, "e": 1575, "s": 1525, "text": "Inside the views.py file add the following code:" }, { "code": null, "e": 1583, "s": 1575, "text": "Python3" }, { "code": "from django.views.generic.base import TemplateViewfrom .models import YourModel class Intro(TemplateView): template_name = 'Intro.html' def get_context_data(self,*args, **kwargs): context = super(Intro, self).get_context_data(*args,**kwargs) context['users'] = YourModel.objects.all() return context", "e": 1910, "s": 1583, "text": null }, { "code": null, "e": 1989, "s": 1910, "text": "Inside the urls.py file of project named geeksforgeeks add the following code:" }, { "code": null, "e": 1997, "s": 1989, "text": "Python3" }, { "code": "from django.contrib import adminfrom django.urls import pathfrom geeks.views import Intro urlpatterns = [ path('admin/', admin.site.urls), path('',Intro.as_view(),name=\"intro\")]", "e": 2181, "s": 1997, "text": null }, { "code": null, "e": 2237, "s": 2181, "text": "Rewrite the views.py flle by adding the following code:" }, { "code": null, "e": 2245, "s": 2237, "text": "Python3" }, { "code": "from django.views.generic.base import TemplateViewfrom .models import YourModel class Intro(TemplateView): template_name = 'Intro.html' extra_context={'users': YourModel.objects.all()}", "e": 2436, "s": 2245, "text": null }, { "code": null, "e": 2602, "s": 2436, "text": "By both the methods you will see the same output. Let’s check what is there on http://localhost:8000/, before doing this don’t forget to add some data to your model." }, { "code": null, "e": 2684, "s": 2602, "text": "How to add data to your model\n Django ORM – Inserting, Updating & Deleting Data" }, { "code": null, "e": 2698, "s": 2684, "text": "sumitgumber28" }, { "code": null, "e": 2711, "s": 2698, "text": "Django-views" }, { "code": null, "e": 2725, "s": 2711, "text": "Python Django" }, { "code": null, "e": 2732, "s": 2725, "text": "Python" } ]
Configuring Clusters in Cassandra
25 Jul, 2020 Prerequisite – Monitoring cluster in CassandraIn this article, we will discuss how we can configure clusters setting in cassandra.yaml file. Also, we will cover some basic parts of cassandra.yaml file in which we can change the by default setting as per our requirements. Cluster :In Cassandra, a cluster is a collection of a node. In a cluster, all nodes can communicate through gossip protocol and all nodes have a similar capability in a cluster. A node in the cluster contains keyspaces, tables, schema information, etc. Cluster Configuration : In Cassandra, cassandra.yaml is the main configuration file in which we can change the default setting as per requirements and after any changes in cassandra.yaml file you must remember to restart the node to take effect. The installation location of the cassandra.yaml file is<install_location>/resources/cassandra/conf. <install_location>/resources/cassandra/conf. Common properties for Cluster Configuration :The table below contains the common configurations like cluster name, listen_address, seeds, native transport address, etc. cluster_name :In this configuration, you can change the name of the cluster in cassandra.yaml file. To change the configuration setting follow steps – open cassandra.yaml file. use the command ctrl+f to search in a file. search for cluster_name. You will see the following property in a file cluster_name: ‘Test Cluster’. It is default setting for the cluster node. You can change the cluster name as per your requirements and then press ctrl+s to save the file. listen_address :It is the IP address that is used by other nodes in a cluster to find out this node. To change the configuration setting follow steps – open cassandra.yaml file. use the command ctrl+f to search in a file. Search for listen_address. You will see the following property in a file listen_address: localhost. It is default setting for the cluster node. You can change the IP listen_address as per your requirements and then press ctrl+s to save the file. native_transport_address :It is an IP address that is used by the client to connect with the node or the cluster. To change the configuration setting follow steps – open cassandra.yaml file. use the command ctrl+f to search in a file. Search for native_transport. You will see the following property in a file native_transport_address: localhost. It is default setting for the cluster node. You can change the IP native_transport as per your requirements and then press ctrl+s to save the file. seed address or seed addresses :It is used when a new node joined the cluster. In general, all nodes in a cluster have the same seed list. To change the configuration setting follow steps – open cassandra.yaml file. use the command ctrl+f to search in a file. Search for seeds. You will see the following property in file seeds: “127.0.0.1”. It is default setting for the cluster node. You can change the seeds IP address as per your requirements and then press ctrl+s to save the file. Output – seed_provider : # Addresses of hosts that are deemed contact points. # Cassandra nodes use this list of hosts to find each other and learn # the topology of the ring. You must change this if you are running # multiple nodes! class_name : org.apache.cassandra.locator.SimpleSeedProvider parameters : # seeds is actually a comma-delimited list of addresses. # Example - "<ip1>, <ip2>, <ip3>" seeds : "127.0.0.1" Example of Cluster Configuration : Apache DBMS DBMS Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Types of Functional dependencies in DBMS MySQL | Regular expressions (Regexp) OLAP Guidelines (Codd's Rule) Difference between OLAP and OLTP in DBMS What is Temporary Table in SQL? Difference between Where and Having Clause in SQL SQL | DDL, DML, TCL and DCL Introduction of Relational Algebra in DBMS Relational Model in DBMS KDD Process in Data Mining
[ { "code": null, "e": 28, "s": 0, "text": "\n25 Jul, 2020" }, { "code": null, "e": 300, "s": 28, "text": "Prerequisite – Monitoring cluster in CassandraIn this article, we will discuss how we can configure clusters setting in cassandra.yaml file. Also, we will cover some basic parts of cassandra.yaml file in which we can change the by default setting as per our requirements." }, { "code": null, "e": 553, "s": 300, "text": "Cluster :In Cassandra, a cluster is a collection of a node. In a cluster, all nodes can communicate through gossip protocol and all nodes have a similar capability in a cluster. A node in the cluster contains keyspaces, tables, schema information, etc." }, { "code": null, "e": 577, "s": 553, "text": "Cluster Configuration :" }, { "code": null, "e": 799, "s": 577, "text": "In Cassandra, cassandra.yaml is the main configuration file in which we can change the default setting as per requirements and after any changes in cassandra.yaml file you must remember to restart the node to take effect." }, { "code": null, "e": 899, "s": 799, "text": "The installation location of the cassandra.yaml file is<install_location>/resources/cassandra/conf." }, { "code": null, "e": 944, "s": 899, "text": "<install_location>/resources/cassandra/conf." }, { "code": null, "e": 1113, "s": 944, "text": "Common properties for Cluster Configuration :The table below contains the common configurations like cluster name, listen_address, seeds, native transport address, etc." }, { "code": null, "e": 1264, "s": 1113, "text": "cluster_name :In this configuration, you can change the name of the cluster in cassandra.yaml file. To change the configuration setting follow steps –" }, { "code": null, "e": 1290, "s": 1264, "text": "open cassandra.yaml file." }, { "code": null, "e": 1334, "s": 1290, "text": "use the command ctrl+f to search in a file." }, { "code": null, "e": 1359, "s": 1334, "text": "search for cluster_name." }, { "code": null, "e": 1479, "s": 1359, "text": "You will see the following property in a file cluster_name: ‘Test Cluster’. It is default setting for the cluster node." }, { "code": null, "e": 1576, "s": 1479, "text": "You can change the cluster name as per your requirements and then press ctrl+s to save the file." }, { "code": null, "e": 1728, "s": 1576, "text": "listen_address :It is the IP address that is used by other nodes in a cluster to find out this node. To change the configuration setting follow steps –" }, { "code": null, "e": 1754, "s": 1728, "text": "open cassandra.yaml file." }, { "code": null, "e": 1798, "s": 1754, "text": "use the command ctrl+f to search in a file." }, { "code": null, "e": 1825, "s": 1798, "text": "Search for listen_address." }, { "code": null, "e": 1942, "s": 1825, "text": "You will see the following property in a file listen_address: localhost. It is default setting for the cluster node." }, { "code": null, "e": 2044, "s": 1942, "text": "You can change the IP listen_address as per your requirements and then press ctrl+s to save the file." }, { "code": null, "e": 2209, "s": 2044, "text": "native_transport_address :It is an IP address that is used by the client to connect with the node or the cluster. To change the configuration setting follow steps –" }, { "code": null, "e": 2235, "s": 2209, "text": "open cassandra.yaml file." }, { "code": null, "e": 2279, "s": 2235, "text": "use the command ctrl+f to search in a file." }, { "code": null, "e": 2308, "s": 2279, "text": "Search for native_transport." }, { "code": null, "e": 2435, "s": 2308, "text": "You will see the following property in a file native_transport_address: localhost. It is default setting for the cluster node." }, { "code": null, "e": 2539, "s": 2435, "text": "You can change the IP native_transport as per your requirements and then press ctrl+s to save the file." }, { "code": null, "e": 2729, "s": 2539, "text": "seed address or seed addresses :It is used when a new node joined the cluster. In general, all nodes in a cluster have the same seed list. To change the configuration setting follow steps –" }, { "code": null, "e": 2755, "s": 2729, "text": "open cassandra.yaml file." }, { "code": null, "e": 2799, "s": 2755, "text": "use the command ctrl+f to search in a file." }, { "code": null, "e": 2817, "s": 2799, "text": "Search for seeds." }, { "code": null, "e": 2925, "s": 2817, "text": "You will see the following property in file seeds: “127.0.0.1”. It is default setting for the cluster node." }, { "code": null, "e": 3026, "s": 2925, "text": "You can change the seeds IP address as per your requirements and then press ctrl+s to save the file." }, { "code": null, "e": 3035, "s": 3026, "text": "Output –" }, { "code": null, "e": 3448, "s": 3035, "text": "seed_provider :\n# Addresses of hosts that are deemed contact points.\n# Cassandra nodes use this list of hosts to find each other and learn\n# the topology of the ring. You must change this if you are running\n# multiple nodes!\n\nclass_name : org.apache.cassandra.locator.SimpleSeedProvider\n\nparameters :\n# seeds is actually a comma-delimited list of addresses.\n# Example - \"<ip1>, <ip2>, <ip3>\"\n\nseeds : \"127.0.0.1\"" }, { "code": null, "e": 3483, "s": 3448, "text": "Example of Cluster Configuration :" }, { "code": null, "e": 3490, "s": 3483, "text": "Apache" }, { "code": null, "e": 3495, "s": 3490, "text": "DBMS" }, { "code": null, "e": 3500, "s": 3495, "text": "DBMS" }, { "code": null, "e": 3598, "s": 3500, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3639, "s": 3598, "text": "Types of Functional dependencies in DBMS" }, { "code": null, "e": 3676, "s": 3639, "text": "MySQL | Regular expressions (Regexp)" }, { "code": null, "e": 3706, "s": 3676, "text": "OLAP Guidelines (Codd's Rule)" }, { "code": null, "e": 3747, "s": 3706, "text": "Difference between OLAP and OLTP in DBMS" }, { "code": null, "e": 3779, "s": 3747, "text": "What is Temporary Table in SQL?" }, { "code": null, "e": 3829, "s": 3779, "text": "Difference between Where and Having Clause in SQL" }, { "code": null, "e": 3857, "s": 3829, "text": "SQL | DDL, DML, TCL and DCL" }, { "code": null, "e": 3900, "s": 3857, "text": "Introduction of Relational Algebra in DBMS" }, { "code": null, "e": 3925, "s": 3900, "text": "Relational Model in DBMS" } ]
Switch Statement in Go
22 Jul, 2019 A switch statement is a multiway branch statement. It provides an efficient way to transfer the execution to different parts of a code based on the value(also called case) of the expression. Go language supports two types of switch statements: Expression SwitchType Switch Expression Switch Type Switch Expression switch is similar to switch statement in C, C++, Java language. It provides an easy way to dispatch execution to different parts of code based on the value of the expression. Syntax: switch optstatement; optexpression{ case expression1: Statement.. case expression2: Statement.. ... default: Statement.. } Important Points: Both optstatement and optexpression in the expression switch are optional statements. If both optstatementand optexpression are present, then a semi-colon(;) is required in between them. If the switch does not contain any expression, then the compiler assume that the expression is true. The optional statement, i.e, optstatement contains simple statements like variable declarations, increment or assignment statements, or function calls, etc. If a variable present in the optional statement, then the scope of the variable is limited to that switch statement. In switch statement, the case and default statement does not contain any break statement. But you are allowed to use break and fallthrough statement if your program required. The default statement is optional in switch statement. If a case can contain multiple values and these values are separated by comma(,). If a case does not contain any expression, then the compiler assume that te expression is true. Example 1: // Go program to illustrate the // concept of Expression switch// statementpackage main import "fmt" func main() { // Switch statement with both // optional statement, i.e, day:=4 // and expression, i.e, day switch day:=4; day{ case 1: fmt.Println("Monday") case 2: fmt.Println("Tuesday") case 3: fmt.Println("Wednesday") case 4: fmt.Println("Thursday") case 5: fmt.Println("Friday") case 6: fmt.Println("Saturday") case 7: fmt.Println("Sunday") default: fmt.Println("Invalid") } } Output: Thursday Example 2: // Go program to illustrate the // concept of Expression switch// statementpackage main import "fmt" func main() { var value int = 2 // Switch statement without an // optional statement and // expression switch { case value == 1: fmt.Println("Hello") case value == 2: fmt.Println("Bonjour") case value == 3: fmt.Println("Namstay") default: fmt.Println("Invalid") } } Output: Bonjour Example 3: // Go program to illustrate the // concept of Expression switch// statementpackage main import "fmt" func main() { var value string = "five" // Switch statement without default statement // Multiple values in case statement switch value { case "one": fmt.Println("C#") case "two", "three": fmt.Println("Go") case "four", "five", "six": fmt.Println("Java") } } Output: Java Type switch is used when you want to compare types. In this switch, the case contains the type which is going to compare with the type present in the switch expression. Syntax: switch optstatement; typeswitchexpression{ case typelist 1: Statement.. case typelist 2: Statement.. ... default: Statement.. } Important Points: The optional statement, i.e., optstatement is similar as in the switch expression. If a case can contain multiple values and these values are separated by comma(,). In type switch statement, the case and default statement do not contain any break statement. But you are allowed to use break and fallthrough statement if your program required. The default statement is optional in type switch statement. The typeswitchexpression is an expression whose result is a type. If an expression is assigned in typeswitchexpression using := operator, then the type of that variable depends upon the type present in case clause. If the case clause contains two or more types, then the type of the variable is the type in which it is created in typeswitchexpression. Example: // Go program to illustrate the // concept of Type switch// statementpackage main import "fmt" func main() { var value interface{} switch q:= value.(type) { case bool: fmt.Println("value is of boolean type") case float64: fmt.Println("value is of float64 type") case int: fmt.Println("value is of int type") default: fmt.Printf("value is of type: %T", q) }} Output: value is of type: <nil> Go-Control-Flow Golang Go Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 53, "s": 25, "text": "\n22 Jul, 2019" }, { "code": null, "e": 297, "s": 53, "text": "A switch statement is a multiway branch statement. It provides an efficient way to transfer the execution to different parts of a code based on the value(also called case) of the expression. Go language supports two types of switch statements:" }, { "code": null, "e": 326, "s": 297, "text": "Expression SwitchType Switch" }, { "code": null, "e": 344, "s": 326, "text": "Expression Switch" }, { "code": null, "e": 356, "s": 344, "text": "Type Switch" }, { "code": null, "e": 542, "s": 356, "text": "Expression switch is similar to switch statement in C, C++, Java language. It provides an easy way to dispatch execution to different parts of code based on the value of the expression." }, { "code": null, "e": 550, "s": 542, "text": "Syntax:" }, { "code": null, "e": 674, "s": 550, "text": "switch optstatement; optexpression{\ncase expression1: Statement..\ncase expression2: Statement..\n...\ndefault: Statement..\n}\n" }, { "code": null, "e": 692, "s": 674, "text": "Important Points:" }, { "code": null, "e": 778, "s": 692, "text": "Both optstatement and optexpression in the expression switch are optional statements." }, { "code": null, "e": 879, "s": 778, "text": "If both optstatementand optexpression are present, then a semi-colon(;) is required in between them." }, { "code": null, "e": 980, "s": 879, "text": "If the switch does not contain any expression, then the compiler assume that the expression is true." }, { "code": null, "e": 1137, "s": 980, "text": "The optional statement, i.e, optstatement contains simple statements like variable declarations, increment or assignment statements, or function calls, etc." }, { "code": null, "e": 1254, "s": 1137, "text": "If a variable present in the optional statement, then the scope of the variable is limited to that switch statement." }, { "code": null, "e": 1429, "s": 1254, "text": "In switch statement, the case and default statement does not contain any break statement. But you are allowed to use break and fallthrough statement if your program required." }, { "code": null, "e": 1484, "s": 1429, "text": "The default statement is optional in switch statement." }, { "code": null, "e": 1566, "s": 1484, "text": "If a case can contain multiple values and these values are separated by comma(,)." }, { "code": null, "e": 1662, "s": 1566, "text": "If a case does not contain any expression, then the compiler assume that te expression is true." }, { "code": null, "e": 1673, "s": 1662, "text": "Example 1:" }, { "code": "// Go program to illustrate the // concept of Expression switch// statementpackage main import \"fmt\" func main() { // Switch statement with both // optional statement, i.e, day:=4 // and expression, i.e, day switch day:=4; day{ case 1: fmt.Println(\"Monday\") case 2: fmt.Println(\"Tuesday\") case 3: fmt.Println(\"Wednesday\") case 4: fmt.Println(\"Thursday\") case 5: fmt.Println(\"Friday\") case 6: fmt.Println(\"Saturday\") case 7: fmt.Println(\"Sunday\") default: fmt.Println(\"Invalid\") } }", "e": 2279, "s": 1673, "text": null }, { "code": null, "e": 2287, "s": 2279, "text": "Output:" }, { "code": null, "e": 2296, "s": 2287, "text": "Thursday" }, { "code": null, "e": 2307, "s": 2296, "text": "Example 2:" }, { "code": "// Go program to illustrate the // concept of Expression switch// statementpackage main import \"fmt\" func main() { var value int = 2 // Switch statement without an // optional statement and // expression switch { case value == 1: fmt.Println(\"Hello\") case value == 2: fmt.Println(\"Bonjour\") case value == 3: fmt.Println(\"Namstay\") default: fmt.Println(\"Invalid\") } }", "e": 2754, "s": 2307, "text": null }, { "code": null, "e": 2762, "s": 2754, "text": "Output:" }, { "code": null, "e": 2770, "s": 2762, "text": "Bonjour" }, { "code": null, "e": 2781, "s": 2770, "text": "Example 3:" }, { "code": "// Go program to illustrate the // concept of Expression switch// statementpackage main import \"fmt\" func main() { var value string = \"five\" // Switch statement without default statement // Multiple values in case statement switch value { case \"one\": fmt.Println(\"C#\") case \"two\", \"three\": fmt.Println(\"Go\") case \"four\", \"five\", \"six\": fmt.Println(\"Java\") } }", "e": 3199, "s": 2781, "text": null }, { "code": null, "e": 3207, "s": 3199, "text": "Output:" }, { "code": null, "e": 3212, "s": 3207, "text": "Java" }, { "code": null, "e": 3381, "s": 3212, "text": "Type switch is used when you want to compare types. In this switch, the case contains the type which is going to compare with the type present in the switch expression." }, { "code": null, "e": 3389, "s": 3381, "text": "Syntax:" }, { "code": null, "e": 3518, "s": 3389, "text": "switch optstatement; typeswitchexpression{\ncase typelist 1: Statement..\ncase typelist 2: Statement..\n...\ndefault: Statement..\n}\n" }, { "code": null, "e": 3536, "s": 3518, "text": "Important Points:" }, { "code": null, "e": 3619, "s": 3536, "text": "The optional statement, i.e., optstatement is similar as in the switch expression." }, { "code": null, "e": 3701, "s": 3619, "text": "If a case can contain multiple values and these values are separated by comma(,)." }, { "code": null, "e": 3879, "s": 3701, "text": "In type switch statement, the case and default statement do not contain any break statement. But you are allowed to use break and fallthrough statement if your program required." }, { "code": null, "e": 3939, "s": 3879, "text": "The default statement is optional in type switch statement." }, { "code": null, "e": 4005, "s": 3939, "text": "The typeswitchexpression is an expression whose result is a type." }, { "code": null, "e": 4291, "s": 4005, "text": "If an expression is assigned in typeswitchexpression using := operator, then the type of that variable depends upon the type present in case clause. If the case clause contains two or more types, then the type of the variable is the type in which it is created in typeswitchexpression." }, { "code": null, "e": 4300, "s": 4291, "text": "Example:" }, { "code": "// Go program to illustrate the // concept of Type switch// statementpackage main import \"fmt\" func main() { var value interface{} switch q:= value.(type) { case bool: fmt.Println(\"value is of boolean type\") case float64: fmt.Println(\"value is of float64 type\") case int: fmt.Println(\"value is of int type\") default: fmt.Printf(\"value is of type: %T\", q) }}", "e": 4725, "s": 4300, "text": null }, { "code": null, "e": 4733, "s": 4725, "text": "Output:" }, { "code": null, "e": 4757, "s": 4733, "text": "value is of type: <nil>" }, { "code": null, "e": 4773, "s": 4757, "text": "Go-Control-Flow" }, { "code": null, "e": 4780, "s": 4773, "text": "Golang" }, { "code": null, "e": 4792, "s": 4780, "text": "Go Language" } ]
Dirty read in SQL
29 Apr, 2020 Prerequisite – Types of Schedules, Transaction Isolation Levels in DBMSThere are mainly four types of common concurrency problems: dirty read, lost read, non-repeatable read and phantom reads. Dirty Reads –When a transaction is allowed to read a row that has been modified by an another transaction which is not committed yet that time Dirty Reads occurred. It is mainly occurred because of multiple transaction at a time which is not committed. Example – Table – Record Transaction –Transfer 10 from S Adam account to Zee Young account: Input: BEGIN TRY BEGIN TRANSACTION UPDATE Table SET Balance = Balance - 10 WHERE ID=1; UPDATE Table SET Balance = Balance + 10 WHERE ID='C'; COMMIT TRANSACTION PRINT 'Committed' END TRY BEGIN CATCH ROLLBACK TRANSACTION PRINT 'Not Committed' END CATCH Output: Not committed By executing the above query the output will be “Not committed” because there is an error, there is no ID=C. So at that time if we want to execute another transaction with that row that time Dirty Reads occurs. There is no partial commitment if both the UPDATE query succeed only then the output will be “Committed”. Before Execution: Table – Record After Execution: Input: BEGIN TRY BEGIN TRANSACTION UPDATE Table SET Balance = Balance - 10 WHERE ID=1; UPDATE Table SET Balance = Balance + 10 WHERE ID='C'; COMMIT TRANSACTION PRINT 'Committed' END TRY BEGIN CATCH ROLLBACK TRANSACTION PRINT 'Not Committed' END CATCH Output: (1row affected) (0row affected) Not Committed Note that if we put a valid ID first transaction result will come out as committed or 1 row effected but 2nd one will not be affected. Explanation –If we have a ticket booking system and One Customer is trying to book a ticket at that time available number of the ticket is 10, before completing the payment, the Second Customer wants to book a ticket that time this 2nd transaction will show the second customer that the number of the available tickets is 9. The twist is here if the first customer does not have sufficient fund in his debit card or in his wallet then the 1st transaction will Rollback, that time 9 seat available which is read by the 2nd transaction is Dirty Read. Example:Available ticket: For 1st customer 1st Step –Input: -- Transaction 1 Select *from Bus_ticket; Output:IDBus_NameAvailable_Seat1KA001710 Input: -- Transaction 1 Select *from Bus_ticket; Output: 2nd Step –Booking time for 1st customerInput: --Transaction 1 BEING Transaction UPDATE Bus_Ticket set Available_Seat=9 WHERE ID=1 --Payment for Transaction 1 Waitfor Delay '00.00.30' Rollback transaction Available ticket: For 2nd customer while 1st customer is paying for the ticket. Input: --Transaction 1 BEING Transaction UPDATE Bus_Ticket set Available_Seat=9 WHERE ID=1 --Payment for Transaction 1 Waitfor Delay '00.00.30' Rollback transaction Available ticket: For 2nd customer while 1st customer is paying for the ticket. 3rd Step –Input: -- Transaction 1 set transaction isolation level read uncommitted Select *from Bus_ticket where ID=1; Output:IDBus_NameAvailable_Seat1KA00179 Input: -- Transaction 1 set transaction isolation level read uncommitted Select *from Bus_ticket where ID=1; Output: Note that during the payment of 1st customer 2nd transaction read it 9 seat is available if some how 1st transaction Rollback then available seat 9 that is Dirty read data. After rollback of the 1st transaction available seat is 10 again. 2nd and 3rd step happening at the same time. Actually available seat after rollback of transaction 1: maerushee nidhi_biet samyboy280 Picked DBMS SQL DBMS SQL Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n29 Apr, 2020" }, { "code": null, "e": 245, "s": 52, "text": "Prerequisite – Types of Schedules, Transaction Isolation Levels in DBMSThere are mainly four types of common concurrency problems: dirty read, lost read, non-repeatable read and phantom reads." }, { "code": null, "e": 498, "s": 245, "text": "Dirty Reads –When a transaction is allowed to read a row that has been modified by an another transaction which is not committed yet that time Dirty Reads occurred. It is mainly occurred because of multiple transaction at a time which is not committed." }, { "code": null, "e": 508, "s": 498, "text": "Example –" }, { "code": null, "e": 523, "s": 508, "text": "Table – Record" }, { "code": null, "e": 590, "s": 523, "text": "Transaction –Transfer 10 from S Adam account to Zee Young account:" }, { "code": null, "e": 883, "s": 590, "text": "Input:\nBEGIN TRY\n BEGIN TRANSACTION\n UPDATE Table SET Balance = Balance - 10 WHERE ID=1;\n UPDATE Table SET Balance = Balance + 10 WHERE ID='C';\n COMMIT TRANSACTION\n PRINT 'Committed'\nEND TRY\nBEGIN CATCH\n ROLLBACK TRANSACTION\n PRINT 'Not Committed'\nEND CATCH\n\nOutput:\nNot committed " }, { "code": null, "e": 1200, "s": 883, "text": "By executing the above query the output will be “Not committed” because there is an error, there is no ID=C. So at that time if we want to execute another transaction with that row that time Dirty Reads occurs. There is no partial commitment if both the UPDATE query succeed only then the output will be “Committed”." }, { "code": null, "e": 1218, "s": 1200, "text": "Before Execution:" }, { "code": null, "e": 1233, "s": 1218, "text": "Table – Record" }, { "code": null, "e": 1250, "s": 1233, "text": "After Execution:" }, { "code": null, "e": 1687, "s": 1250, "text": "Input: \n BEGIN TRY\n BEGIN TRANSACTION\n UPDATE Table SET Balance = Balance - 10 WHERE ID=1;\n UPDATE Table SET Balance = Balance + 10 WHERE ID='C';\n COMMIT TRANSACTION\n PRINT 'Committed'\n END TRY\n BEGIN CATCH\n ROLLBACK TRANSACTION\n PRINT 'Not Committed'\n END CATCH\n\nOutput: \n (1row affected)\n (0row affected)\n Not Committed " }, { "code": null, "e": 1822, "s": 1687, "text": "Note that if we put a valid ID first transaction result will come out as committed or 1 row effected but 2nd one will not be affected." }, { "code": null, "e": 2371, "s": 1822, "text": "Explanation –If we have a ticket booking system and One Customer is trying to book a ticket at that time available number of the ticket is 10, before completing the payment, the Second Customer wants to book a ticket that time this 2nd transaction will show the second customer that the number of the available tickets is 9. The twist is here if the first customer does not have sufficient fund in his debit card or in his wallet then the 1st transaction will Rollback, that time 9 seat available which is read by the 2nd transaction is Dirty Read." }, { "code": null, "e": 2414, "s": 2371, "text": "Example:Available ticket: For 1st customer" }, { "code": null, "e": 2514, "s": 2414, "text": "1st Step –Input:\n-- Transaction 1\nSelect *from Bus_ticket; Output:IDBus_NameAvailable_Seat1KA001710" }, { "code": null, "e": 2564, "s": 2514, "text": "Input:\n-- Transaction 1\nSelect *from Bus_ticket; " }, { "code": null, "e": 2572, "s": 2564, "text": "Output:" }, { "code": null, "e": 2915, "s": 2572, "text": "2nd Step –Booking time for 1st customerInput: \n--Transaction 1\n BEING Transaction\n UPDATE Bus_Ticket set Available_Seat=9\n WHERE ID=1\n \n --Payment for Transaction 1\n Waitfor Delay '00.00.30'\n Rollback transaction Available ticket: For 2nd customer while 1st customer is paying for the ticket." }, { "code": null, "e": 3140, "s": 2915, "text": "Input: \n--Transaction 1\n BEING Transaction\n UPDATE Bus_Ticket set Available_Seat=9\n WHERE ID=1\n \n --Payment for Transaction 1\n Waitfor Delay '00.00.30'\n Rollback transaction " }, { "code": null, "e": 3220, "s": 3140, "text": "Available ticket: For 2nd customer while 1st customer is paying for the ticket." }, { "code": null, "e": 3382, "s": 3220, "text": "3rd Step –Input: \n-- Transaction 1\n\nset transaction isolation level read uncommitted\nSelect *from Bus_ticket where ID=1; Output:IDBus_NameAvailable_Seat1KA00179" }, { "code": null, "e": 3495, "s": 3382, "text": "Input: \n-- Transaction 1\n\nset transaction isolation level read uncommitted\nSelect *from Bus_ticket where ID=1; " }, { "code": null, "e": 3503, "s": 3495, "text": "Output:" }, { "code": null, "e": 3787, "s": 3503, "text": "Note that during the payment of 1st customer 2nd transaction read it 9 seat is available if some how 1st transaction Rollback then available seat 9 that is Dirty read data. After rollback of the 1st transaction available seat is 10 again. 2nd and 3rd step happening at the same time." }, { "code": null, "e": 3844, "s": 3787, "text": "Actually available seat after rollback of transaction 1:" }, { "code": null, "e": 3854, "s": 3844, "text": "maerushee" }, { "code": null, "e": 3865, "s": 3854, "text": "nidhi_biet" }, { "code": null, "e": 3876, "s": 3865, "text": "samyboy280" }, { "code": null, "e": 3883, "s": 3876, "text": "Picked" }, { "code": null, "e": 3888, "s": 3883, "text": "DBMS" }, { "code": null, "e": 3892, "s": 3888, "text": "SQL" }, { "code": null, "e": 3897, "s": 3892, "text": "DBMS" }, { "code": null, "e": 3901, "s": 3897, "text": "SQL" } ]
Node.js fs.openSync() Method
11 Oct, 2021 The fs.openSync() method is an inbuilt application programming interface of fs module which is used to return an integer value that represents the file descriptor. Syntax: fs.openSync( path, flags, mode ) Parameters: This method accepts three parameters as mentioned above and described below: path: It holds the path of the file. It is of type string, Buffer, or URL. flags: It holds either a string or a number value. Its default value of it is ‘r’. mode: It holds either a string or an integer value and its default value of it is 0o666. Return Value: It returns a number which represents the file descriptor. Below examples illustrate the use of fs.openSync() method in Node.js: Example 1: // Node.js program to demonstrate the // fs.openSync() method // Including fs modulevar fs = require('fs'); // Defining filenamevar filename = './myfile'; // Calling openSync method// with its parametersvar res = fs.openSync(filename, 'r'); // Prints outputconsole.log(res); Output: 23 Here, the flag ‘r’ indicates that the file is already created and it reads the created file. Example 2: // Node.js program to demonstrate the // fs.openSync() method // Including fs modulevar fs = require('fs'); // Defining pathvar path = require('path'); // Calling openSync method with// all its parametersvar fd = fs.openSync(path.join( process.cwd(), 'input.txt'), 'w', 0o666); // This will append the content// of file created abovefs.writeSync(fd, 'GeeksforGeeks'); // Setting timeoutsetTimeout(function () { // Its printed after the file is closed console.log('closing file now'); // closing file descriptor fs.closeSync(fd);}, 10000);console.log("Program done!"); Output: Program done! closing file now Here, the flag ‘w’ indicates that the file is created or overwritten. Reference: https://nodejs.org/api/fs.html#fs_fs_opensync_path_flags_mode Node.js-fs-module Picked Node.js Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to install the previous version of node.js and npm ? Difference between promise and async await in Node.js Mongoose | findByIdAndUpdate() Function JWT Authentication with Node.js Installation of Node.js on Windows Top 10 Projects For Beginners To Practice HTML and CSS Skills Difference between var, let and const keywords in JavaScript How to insert spaces/tabs in text using HTML/CSS? How to fetch data from an API in ReactJS ? Differences between Functional Components and Class Components in React
[ { "code": null, "e": 28, "s": 0, "text": "\n11 Oct, 2021" }, { "code": null, "e": 192, "s": 28, "text": "The fs.openSync() method is an inbuilt application programming interface of fs module which is used to return an integer value that represents the file descriptor." }, { "code": null, "e": 200, "s": 192, "text": "Syntax:" }, { "code": null, "e": 233, "s": 200, "text": "fs.openSync( path, flags, mode )" }, { "code": null, "e": 322, "s": 233, "text": "Parameters: This method accepts three parameters as mentioned above and described below:" }, { "code": null, "e": 397, "s": 322, "text": "path: It holds the path of the file. It is of type string, Buffer, or URL." }, { "code": null, "e": 480, "s": 397, "text": "flags: It holds either a string or a number value. Its default value of it is ‘r’." }, { "code": null, "e": 569, "s": 480, "text": "mode: It holds either a string or an integer value and its default value of it is 0o666." }, { "code": null, "e": 641, "s": 569, "text": "Return Value: It returns a number which represents the file descriptor." }, { "code": null, "e": 711, "s": 641, "text": "Below examples illustrate the use of fs.openSync() method in Node.js:" }, { "code": null, "e": 722, "s": 711, "text": "Example 1:" }, { "code": "// Node.js program to demonstrate the // fs.openSync() method // Including fs modulevar fs = require('fs'); // Defining filenamevar filename = './myfile'; // Calling openSync method// with its parametersvar res = fs.openSync(filename, 'r'); // Prints outputconsole.log(res);", "e": 1007, "s": 722, "text": null }, { "code": null, "e": 1015, "s": 1007, "text": "Output:" }, { "code": null, "e": 1019, "s": 1015, "text": "23\n" }, { "code": null, "e": 1112, "s": 1019, "text": "Here, the flag ‘r’ indicates that the file is already created and it reads the created file." }, { "code": null, "e": 1123, "s": 1112, "text": "Example 2:" }, { "code": "// Node.js program to demonstrate the // fs.openSync() method // Including fs modulevar fs = require('fs'); // Defining pathvar path = require('path'); // Calling openSync method with// all its parametersvar fd = fs.openSync(path.join( process.cwd(), 'input.txt'), 'w', 0o666); // This will append the content// of file created abovefs.writeSync(fd, 'GeeksforGeeks'); // Setting timeoutsetTimeout(function () { // Its printed after the file is closed console.log('closing file now'); // closing file descriptor fs.closeSync(fd);}, 10000);console.log(\"Program done!\");", "e": 1713, "s": 1123, "text": null }, { "code": null, "e": 1721, "s": 1713, "text": "Output:" }, { "code": null, "e": 1753, "s": 1721, "text": "Program done!\nclosing file now\n" }, { "code": null, "e": 1823, "s": 1753, "text": "Here, the flag ‘w’ indicates that the file is created or overwritten." }, { "code": null, "e": 1896, "s": 1823, "text": "Reference: https://nodejs.org/api/fs.html#fs_fs_opensync_path_flags_mode" }, { "code": null, "e": 1914, "s": 1896, "text": "Node.js-fs-module" }, { "code": null, "e": 1921, "s": 1914, "text": "Picked" }, { "code": null, "e": 1929, "s": 1921, "text": "Node.js" }, { "code": null, "e": 1946, "s": 1929, "text": "Web Technologies" }, { "code": null, "e": 2044, "s": 1946, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2101, "s": 2044, "text": "How to install the previous version of node.js and npm ?" }, { "code": null, "e": 2155, "s": 2101, "text": "Difference between promise and async await in Node.js" }, { "code": null, "e": 2195, "s": 2155, "text": "Mongoose | findByIdAndUpdate() Function" }, { "code": null, "e": 2227, "s": 2195, "text": "JWT Authentication with Node.js" }, { "code": null, "e": 2262, "s": 2227, "text": "Installation of Node.js on Windows" }, { "code": null, "e": 2324, "s": 2262, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 2385, "s": 2324, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 2435, "s": 2385, "text": "How to insert spaces/tabs in text using HTML/CSS?" }, { "code": null, "e": 2478, "s": 2435, "text": "How to fetch data from an API in ReactJS ?" } ]
C++ Program to Count pairs with given sum
30 Dec, 2021 Given an array of integers, and a number ‘sum’, find the number of pairs of integers in the array whose sum is equal to ‘sum’. Examples: Input : arr[] = {1, 5, 7, -1}, sum = 6 Output : 2 Pairs with sum 6 are (1, 5) and (7, -1) Input : arr[] = {1, 5, 7, -1, 5}, sum = 6 Output : 3 Pairs with sum 6 are (1, 5), (7, -1) & (1, 5) Input : arr[] = {1, 1, 1, 1}, sum = 2 Output : 6 There are 3! pairs with sum 2. Input : arr[] = {10, 12, 10, 15, -1, 7, 6, 5, 4, 2, 1, 1, 1}, sum = 11 Output : 9 Expected time complexity O(n) Naive Solution – A simple solution is to traverse each element and check if there’s another number in the array which can be added to it to give sum. C++ // C++ implementation of simple method to find count of// pairs with given sum.#include <bits/stdc++.h>using namespace std; // Returns number of pairs in arr[0..n-1] with sum equal// to 'sum'int getPairsCount(int arr[], int n, int sum){ int count = 0; // Initialize result // Consider all possible pairs and check their sums for (int i = 0; i < n; i++) for (int j = i + 1; j < n; j++) if (arr[i] + arr[j] == sum) count++; return count;} // Driver function to test the above functionint main(){ int arr[] = { 1, 5, 7, -1, 5 }; int n = sizeof(arr) / sizeof(arr[0]); int sum = 6; cout << "Count of pairs is " << getPairsCount(arr, n, sum); return 0;} Count of pairs is 3 Time Complexity: O(n2) Auxiliary Space: O(1) Efficient solution – A better solution is possible in O(n) time. Below is the Algorithm – Create a map to store frequency of each number in the array. (Single traversal is required)In the next traversal, for every element check if it can be combined with any other element (other than itself!) to give the desired sum. Increment the counter accordingly.After completion of second traversal, we’d have twice the required value stored in counter because every pair is counted two times. Hence divide count by 2 and return. Create a map to store frequency of each number in the array. (Single traversal is required) In the next traversal, for every element check if it can be combined with any other element (other than itself!) to give the desired sum. Increment the counter accordingly. After completion of second traversal, we’d have twice the required value stored in counter because every pair is counted two times. Hence divide count by 2 and return. Below is the implementation of above idea : C++ // C++ implementation of simple method to find count of// pairs with given sum.#include <bits/stdc++.h>using namespace std; // Returns number of pairs in arr[0..n-1] with sum equal// to 'sum'int getPairsCount(int arr[], int n, int sum){ unordered_map<int, int> m; // Store counts of all elements in map m for (int i = 0; i < n; i++) m[arr[i]]++; int twice_count = 0; // iterate through each element and increment the // count (Notice that every pair is counted twice) for (int i = 0; i < n; i++) { twice_count += m[sum - arr[i]]; // if (arr[i], arr[i]) pair satisfies the condition, // then we need to ensure that the count is // decreased by one such that the (arr[i], arr[i]) // pair is not considered if (sum - arr[i] == arr[i]) twice_count--; } // return the half of twice_count return twice_count / 2;} // Driver function to test the above functionint main(){ int arr[] = { 1, 5, 7, -1, 5 }; int n = sizeof(arr) / sizeof(arr[0]); int sum = 6; cout << "Count of pairs is " << getPairsCount(arr, n, sum); return 0;} Count of pairs is 3 Please refer complete article on Count pairs with given sum for more details! Accolite Amazon FactSet Hike Arrays C++ C++ Programs Hash Accolite Amazon FactSet Hike Arrays Hash CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Introduction to Data Structures Window Sliding Technique Search, insert and delete in an unsorted array What is Data Structure: Types, Classifications and Applications Chocolate Distribution Problem Vector in C++ STL Map in C++ Standard Template Library (STL) std::sort() in C++ STL Initialize a vector in C++ (7 different ways) Bitwise Operators in C/C++
[ { "code": null, "e": 28, "s": 0, "text": "\n30 Dec, 2021" }, { "code": null, "e": 155, "s": 28, "text": "Given an array of integers, and a number ‘sum’, find the number of pairs of integers in the array whose sum is equal to ‘sum’." }, { "code": null, "e": 167, "s": 155, "text": "Examples: " }, { "code": null, "e": 627, "s": 167, "text": "Input : arr[] = {1, 5, 7, -1}, \n sum = 6\nOutput : 2\nPairs with sum 6 are (1, 5) and (7, -1)\n\nInput : arr[] = {1, 5, 7, -1, 5}, \n sum = 6\nOutput : 3\nPairs with sum 6 are (1, 5), (7, -1) &\n (1, 5) \n\nInput : arr[] = {1, 1, 1, 1}, \n sum = 2\nOutput : 6\nThere are 3! pairs with sum 2.\n\nInput : arr[] = {10, 12, 10, 15, -1, 7, 6, \n 5, 4, 2, 1, 1, 1}, \n sum = 11\nOutput : 9" }, { "code": null, "e": 658, "s": 627, "text": "Expected time complexity O(n) " }, { "code": null, "e": 810, "s": 658, "text": "Naive Solution – A simple solution is to traverse each element and check if there’s another number in the array which can be added to it to give sum. " }, { "code": null, "e": 814, "s": 810, "text": "C++" }, { "code": "// C++ implementation of simple method to find count of// pairs with given sum.#include <bits/stdc++.h>using namespace std; // Returns number of pairs in arr[0..n-1] with sum equal// to 'sum'int getPairsCount(int arr[], int n, int sum){ int count = 0; // Initialize result // Consider all possible pairs and check their sums for (int i = 0; i < n; i++) for (int j = i + 1; j < n; j++) if (arr[i] + arr[j] == sum) count++; return count;} // Driver function to test the above functionint main(){ int arr[] = { 1, 5, 7, -1, 5 }; int n = sizeof(arr) / sizeof(arr[0]); int sum = 6; cout << \"Count of pairs is \" << getPairsCount(arr, n, sum); return 0;}", "e": 1536, "s": 814, "text": null }, { "code": null, "e": 1556, "s": 1536, "text": "Count of pairs is 3" }, { "code": null, "e": 1603, "s": 1556, "text": "Time Complexity: O(n2) Auxiliary Space: O(1) " }, { "code": null, "e": 1694, "s": 1603, "text": "Efficient solution – A better solution is possible in O(n) time. Below is the Algorithm – " }, { "code": null, "e": 2125, "s": 1694, "text": "Create a map to store frequency of each number in the array. (Single traversal is required)In the next traversal, for every element check if it can be combined with any other element (other than itself!) to give the desired sum. Increment the counter accordingly.After completion of second traversal, we’d have twice the required value stored in counter because every pair is counted two times. Hence divide count by 2 and return." }, { "code": null, "e": 2217, "s": 2125, "text": "Create a map to store frequency of each number in the array. (Single traversal is required)" }, { "code": null, "e": 2390, "s": 2217, "text": "In the next traversal, for every element check if it can be combined with any other element (other than itself!) to give the desired sum. Increment the counter accordingly." }, { "code": null, "e": 2558, "s": 2390, "text": "After completion of second traversal, we’d have twice the required value stored in counter because every pair is counted two times. Hence divide count by 2 and return." }, { "code": null, "e": 2604, "s": 2558, "text": "Below is the implementation of above idea : " }, { "code": null, "e": 2608, "s": 2604, "text": "C++" }, { "code": "// C++ implementation of simple method to find count of// pairs with given sum.#include <bits/stdc++.h>using namespace std; // Returns number of pairs in arr[0..n-1] with sum equal// to 'sum'int getPairsCount(int arr[], int n, int sum){ unordered_map<int, int> m; // Store counts of all elements in map m for (int i = 0; i < n; i++) m[arr[i]]++; int twice_count = 0; // iterate through each element and increment the // count (Notice that every pair is counted twice) for (int i = 0; i < n; i++) { twice_count += m[sum - arr[i]]; // if (arr[i], arr[i]) pair satisfies the condition, // then we need to ensure that the count is // decreased by one such that the (arr[i], arr[i]) // pair is not considered if (sum - arr[i] == arr[i]) twice_count--; } // return the half of twice_count return twice_count / 2;} // Driver function to test the above functionint main(){ int arr[] = { 1, 5, 7, -1, 5 }; int n = sizeof(arr) / sizeof(arr[0]); int sum = 6; cout << \"Count of pairs is \" << getPairsCount(arr, n, sum); return 0;}", "e": 3752, "s": 2608, "text": null }, { "code": null, "e": 3772, "s": 3752, "text": "Count of pairs is 3" }, { "code": null, "e": 3850, "s": 3772, "text": "Please refer complete article on Count pairs with given sum for more details!" }, { "code": null, "e": 3859, "s": 3850, "text": "Accolite" }, { "code": null, "e": 3866, "s": 3859, "text": "Amazon" }, { "code": null, "e": 3874, "s": 3866, "text": "FactSet" }, { "code": null, "e": 3879, "s": 3874, "text": "Hike" }, { "code": null, "e": 3886, "s": 3879, "text": "Arrays" }, { "code": null, "e": 3890, "s": 3886, "text": "C++" }, { "code": null, "e": 3903, "s": 3890, "text": "C++ Programs" }, { "code": null, "e": 3908, "s": 3903, "text": "Hash" }, { "code": null, "e": 3917, "s": 3908, "text": "Accolite" }, { "code": null, "e": 3924, "s": 3917, "text": "Amazon" }, { "code": null, "e": 3932, "s": 3924, "text": "FactSet" }, { "code": null, "e": 3937, "s": 3932, "text": "Hike" }, { "code": null, "e": 3944, "s": 3937, "text": "Arrays" }, { "code": null, "e": 3949, "s": 3944, "text": "Hash" }, { "code": null, "e": 3953, "s": 3949, "text": "CPP" }, { "code": null, "e": 4051, "s": 3953, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 4083, "s": 4051, "text": "Introduction to Data Structures" }, { "code": null, "e": 4108, "s": 4083, "text": "Window Sliding Technique" }, { "code": null, "e": 4155, "s": 4108, "text": "Search, insert and delete in an unsorted array" }, { "code": null, "e": 4219, "s": 4155, "text": "What is Data Structure: Types, Classifications and Applications" }, { "code": null, "e": 4250, "s": 4219, "text": "Chocolate Distribution Problem" }, { "code": null, "e": 4268, "s": 4250, "text": "Vector in C++ STL" }, { "code": null, "e": 4311, "s": 4268, "text": "Map in C++ Standard Template Library (STL)" }, { "code": null, "e": 4334, "s": 4311, "text": "std::sort() in C++ STL" }, { "code": null, "e": 4380, "s": 4334, "text": "Initialize a vector in C++ (7 different ways)" } ]
Python String rfind() Method
19 Aug, 2021 Python String rfind() method returns the highest index of the substring if found in the given string. If not found then it returns -1. Syntax: str.rfind(sub, start, end) Parameters: sub: It’s the substring that needs to be searched in the given string. start: Starting position where the sub needs to be checked within the string. end: Ending position where suffix needs to be checked within the string. Note: If start and end indexes are not provided then, by default it takes 0 and length-1 as starting and ending indexes where ending indexes are not included in our search. Return: Returns the highest index of the substring if it is found in the given string; if not found, then it returns -1. Exception: ValueError: This error is raised in the case when the argument string is not found in the target string. Python3 # Python program to demonstrate working of rfind()# in whole stringword = 'geeks for geeks' # Returns highest index of the substringresult = word.rfind('geeks')print ("Substring 'geeks' found at index :", result ) result = word.rfind('for')print ("Substring 'for' found at index :", result ) word = 'CatBatSatMatGate' # Returns highest index of the substringresult = word.rfind('ate')print("Substring 'ate' found at index :", result) Output: Substring 'geeks' found at index : 10 Substring 'for' found at index : 6 Substring 'ate' found at index : 13 Python3 # Python program to demonstrate working of rfind()# in a sub-stringword = 'geeks for geeks' # Substring is searched in 'eeks for geeks'print(word.rfind('ge', 2)) # Substring is searched in 'eeks for geeks' print(word.rfind('geeks', 2)) # Substring is searched in 'eeks for geeks' print(word.rfind('geeks ', 2)) # Substring is searched in 's for g'print(word.rfind('for ', 4, 11)) Output: 10 10 -1 6 Useful in string checking. To check if the given substring is present in some string or not. Python3 # Python program to demonstrate working of rfind()# to search a stringword = 'CatBatSatMatGate' if (word.rfind('Ate') != -1): print ("Contains given substring ")else: print ("Doesn't contains given substring") Output: Doesn't contains given substring AmiyaRanjanRout Python-Built-in-functions python-string 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 Different ways to create Pandas Dataframe Taking input in Python Enumerate() in Python Read a file line by line in Python How to Install PIP on Windows ?
[ { "code": null, "e": 28, "s": 0, "text": "\n19 Aug, 2021" }, { "code": null, "e": 163, "s": 28, "text": "Python String rfind() method returns the highest index of the substring if found in the given string. If not found then it returns -1." }, { "code": null, "e": 172, "s": 163, "text": "Syntax: " }, { "code": null, "e": 199, "s": 172, "text": "str.rfind(sub, start, end)" }, { "code": null, "e": 212, "s": 199, "text": "Parameters: " }, { "code": null, "e": 284, "s": 212, "text": "sub: It’s the substring that needs to be searched in the given string. " }, { "code": null, "e": 363, "s": 284, "text": "start: Starting position where the sub needs to be checked within the string. " }, { "code": null, "e": 437, "s": 363, "text": "end: Ending position where suffix needs to be checked within the string. " }, { "code": null, "e": 610, "s": 437, "text": "Note: If start and end indexes are not provided then, by default it takes 0 and length-1 as starting and ending indexes where ending indexes are not included in our search." }, { "code": null, "e": 619, "s": 610, "text": "Return: " }, { "code": null, "e": 732, "s": 619, "text": "Returns the highest index of the substring if it is found in the given string; if not found, then it returns -1." }, { "code": null, "e": 744, "s": 732, "text": "Exception: " }, { "code": null, "e": 849, "s": 744, "text": "ValueError: This error is raised in the case when the argument string is not found in the target string." }, { "code": null, "e": 857, "s": 849, "text": "Python3" }, { "code": "# Python program to demonstrate working of rfind()# in whole stringword = 'geeks for geeks' # Returns highest index of the substringresult = word.rfind('geeks')print (\"Substring 'geeks' found at index :\", result ) result = word.rfind('for')print (\"Substring 'for' found at index :\", result ) word = 'CatBatSatMatGate' # Returns highest index of the substringresult = word.rfind('ate')print(\"Substring 'ate' found at index :\", result)", "e": 1295, "s": 857, "text": null }, { "code": null, "e": 1304, "s": 1295, "text": "Output: " }, { "code": null, "e": 1413, "s": 1304, "text": "Substring 'geeks' found at index : 10\nSubstring 'for' found at index : 6\nSubstring 'ate' found at index : 13" }, { "code": null, "e": 1421, "s": 1413, "text": "Python3" }, { "code": "# Python program to demonstrate working of rfind()# in a sub-stringword = 'geeks for geeks' # Substring is searched in 'eeks for geeks'print(word.rfind('ge', 2)) # Substring is searched in 'eeks for geeks' print(word.rfind('geeks', 2)) # Substring is searched in 'eeks for geeks' print(word.rfind('geeks ', 2)) # Substring is searched in 's for g'print(word.rfind('for ', 4, 11))", "e": 1805, "s": 1421, "text": null }, { "code": null, "e": 1814, "s": 1805, "text": "Output: " }, { "code": null, "e": 1825, "s": 1814, "text": "10\n10\n-1\n6" }, { "code": null, "e": 1919, "s": 1825, "text": "Useful in string checking. To check if the given substring is present in some string or not. " }, { "code": null, "e": 1927, "s": 1919, "text": "Python3" }, { "code": "# Python program to demonstrate working of rfind()# to search a stringword = 'CatBatSatMatGate' if (word.rfind('Ate') != -1): print (\"Contains given substring \")else: print (\"Doesn't contains given substring\")", "e": 2144, "s": 1927, "text": null }, { "code": null, "e": 2153, "s": 2144, "text": "Output: " }, { "code": null, "e": 2186, "s": 2153, "text": "Doesn't contains given substring" }, { "code": null, "e": 2202, "s": 2186, "text": "AmiyaRanjanRout" }, { "code": null, "e": 2228, "s": 2202, "text": "Python-Built-in-functions" }, { "code": null, "e": 2242, "s": 2228, "text": "python-string" }, { "code": null, "e": 2249, "s": 2242, "text": "Python" }, { "code": null, "e": 2347, "s": 2249, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2375, "s": 2347, "text": "Read JSON file using Python" }, { "code": null, "e": 2425, "s": 2375, "text": "Adding new column to existing DataFrame in Pandas" }, { "code": null, "e": 2447, "s": 2425, "text": "Python map() function" }, { "code": null, "e": 2491, "s": 2447, "text": "How to get column names in Pandas dataframe" }, { "code": null, "e": 2509, "s": 2491, "text": "Python Dictionary" }, { "code": null, "e": 2551, "s": 2509, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 2574, "s": 2551, "text": "Taking input in Python" }, { "code": null, "e": 2596, "s": 2574, "text": "Enumerate() in Python" }, { "code": null, "e": 2631, "s": 2596, "text": "Read a file line by line in Python" } ]
JavaScript | Output
28 Mar, 2019 JavaScript Output defines the ways to display the output of a given code. The output can be display by using four different ways which are listed below: innerHTML: It is used to access an element. It defines the HTML content.Syntax:document.getElementById(id)Example: This example uses innerHTML to display the data.<!DOCTYPE html><html> <head> <title> JavaScript Output using innerHTML </title></head> <body> <h1>GeeksforGeeks</h1> <h2> JavaScript Display Possibilities Using innerHTML </h2> <p id="GFG"></p> <!-- Script to uses innerHTML --> <script> document.getElementById("GFG").innerHTML = 10 * 2; </script></body> </html> Output: Syntax: document.getElementById(id) Example: This example uses innerHTML to display the data. <!DOCTYPE html><html> <head> <title> JavaScript Output using innerHTML </title></head> <body> <h1>GeeksforGeeks</h1> <h2> JavaScript Display Possibilities Using innerHTML </h2> <p id="GFG"></p> <!-- Script to uses innerHTML --> <script> document.getElementById("GFG").innerHTML = 10 * 2; </script></body> </html> Output: document.write(): It is used for testing purpose.Syntax:document.write()Example: This example uses document.write() property to display data.<!DOCTYPE html><html> <head> <title> JavaScript Output using document.write() </title></head> <body> <h1>GeeksforGeeks</h1> <h2> JavaScript Display Possibilities Using document.write() </h2> <p id="GFG"></p> <!-- Script to uses document.write() --> <script> document.write(10 * 2); </script></body> </html> Output: Syntax: document.write() Example: This example uses document.write() property to display data. <!DOCTYPE html><html> <head> <title> JavaScript Output using document.write() </title></head> <body> <h1>GeeksforGeeks</h1> <h2> JavaScript Display Possibilities Using document.write() </h2> <p id="GFG"></p> <!-- Script to uses document.write() --> <script> document.write(10 * 2); </script></body> </html> Output: window.alert():It displays the content using an alert box.Syntax:window.alert()Example: This example uses window.alert() property to display data.<!DOCTYPE html><html> <head> <title> JavaScript Output using window.alert() </title></head> <body> <h1>GeeksforGeeks</h1> <h2> JavaScript Display Possibilities Using window.alert() </h2> <p id="GFG"></p> <!-- Script to use window.alert() --> <script> window.alert(10 * 2); </script></body> </html> Output: Syntax: window.alert() Example: This example uses window.alert() property to display data. <!DOCTYPE html><html> <head> <title> JavaScript Output using window.alert() </title></head> <body> <h1>GeeksforGeeks</h1> <h2> JavaScript Display Possibilities Using window.alert() </h2> <p id="GFG"></p> <!-- Script to use window.alert() --> <script> window.alert(10 * 2); </script></body> </html> Output: console.log(): It is used for debugging purposes.Syntax:console.log()Example: This example uses console.log() property to display data.<!DOCTYPE html><html> <head> <title> JavaScript Output using innerHTML </title></head> <body> <h1>GeeksforGeeks</h1> <h2> JavaScript Display Possibilities Using console.log() </h2> <p id="GFG"></p> <!-- Script to use console.log() --> <script> console.log(10*2); </script></body> </html> Output: Syntax: console.log() Example: This example uses console.log() property to display data. <!DOCTYPE html><html> <head> <title> JavaScript Output using innerHTML </title></head> <body> <h1>GeeksforGeeks</h1> <h2> JavaScript Display Possibilities Using console.log() </h2> <p id="GFG"></p> <!-- Script to use console.log() --> <script> console.log(10*2); </script></body> </html> Output: javascript-basics Picked JavaScript 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": "\n28 Mar, 2019" }, { "code": null, "e": 206, "s": 53, "text": "JavaScript Output defines the ways to display the output of a given code. The output can be display by using four different ways which are listed below:" }, { "code": null, "e": 796, "s": 206, "text": "innerHTML: It is used to access an element. It defines the HTML content.Syntax:document.getElementById(id)Example: This example uses innerHTML to display the data.<!DOCTYPE html><html> <head> <title> JavaScript Output using innerHTML </title></head> <body> <h1>GeeksforGeeks</h1> <h2> JavaScript Display Possibilities Using innerHTML </h2> <p id=\"GFG\"></p> <!-- Script to uses innerHTML --> <script> document.getElementById(\"GFG\").innerHTML = 10 * 2; </script></body> </html> Output:" }, { "code": null, "e": 804, "s": 796, "text": "Syntax:" }, { "code": null, "e": 832, "s": 804, "text": "document.getElementById(id)" }, { "code": null, "e": 890, "s": 832, "text": "Example: This example uses innerHTML to display the data." }, { "code": "<!DOCTYPE html><html> <head> <title> JavaScript Output using innerHTML </title></head> <body> <h1>GeeksforGeeks</h1> <h2> JavaScript Display Possibilities Using innerHTML </h2> <p id=\"GFG\"></p> <!-- Script to uses innerHTML --> <script> document.getElementById(\"GFG\").innerHTML = 10 * 2; </script></body> </html> ", "e": 1310, "s": 890, "text": null }, { "code": null, "e": 1318, "s": 1310, "text": "Output:" }, { "code": null, "e": 1865, "s": 1318, "text": "document.write(): It is used for testing purpose.Syntax:document.write()Example: This example uses document.write() property to display data.<!DOCTYPE html><html> <head> <title> JavaScript Output using document.write() </title></head> <body> <h1>GeeksforGeeks</h1> <h2> JavaScript Display Possibilities Using document.write() </h2> <p id=\"GFG\"></p> <!-- Script to uses document.write() --> <script> document.write(10 * 2); </script></body> </html> Output:" }, { "code": null, "e": 1873, "s": 1865, "text": "Syntax:" }, { "code": null, "e": 1890, "s": 1873, "text": "document.write()" }, { "code": null, "e": 1960, "s": 1890, "text": "Example: This example uses document.write() property to display data." }, { "code": "<!DOCTYPE html><html> <head> <title> JavaScript Output using document.write() </title></head> <body> <h1>GeeksforGeeks</h1> <h2> JavaScript Display Possibilities Using document.write() </h2> <p id=\"GFG\"></p> <!-- Script to uses document.write() --> <script> document.write(10 * 2); </script></body> </html> ", "e": 2359, "s": 1960, "text": null }, { "code": null, "e": 2367, "s": 2359, "text": "Output:" }, { "code": null, "e": 2906, "s": 2367, "text": "window.alert():It displays the content using an alert box.Syntax:window.alert()Example: This example uses window.alert() property to display data.<!DOCTYPE html><html> <head> <title> JavaScript Output using window.alert() </title></head> <body> <h1>GeeksforGeeks</h1> <h2> JavaScript Display Possibilities Using window.alert() </h2> <p id=\"GFG\"></p> <!-- Script to use window.alert() --> <script> window.alert(10 * 2); </script></body> </html> Output:" }, { "code": null, "e": 2914, "s": 2906, "text": "Syntax:" }, { "code": null, "e": 2929, "s": 2914, "text": "window.alert()" }, { "code": null, "e": 2997, "s": 2929, "text": "Example: This example uses window.alert() property to display data." }, { "code": "<!DOCTYPE html><html> <head> <title> JavaScript Output using window.alert() </title></head> <body> <h1>GeeksforGeeks</h1> <h2> JavaScript Display Possibilities Using window.alert() </h2> <p id=\"GFG\"></p> <!-- Script to use window.alert() --> <script> window.alert(10 * 2); </script></body> </html> ", "e": 3383, "s": 2997, "text": null }, { "code": null, "e": 3391, "s": 3383, "text": "Output:" }, { "code": null, "e": 3913, "s": 3391, "text": "console.log(): It is used for debugging purposes.Syntax:console.log()Example: This example uses console.log() property to display data.<!DOCTYPE html><html> <head> <title> JavaScript Output using innerHTML </title></head> <body> <h1>GeeksforGeeks</h1> <h2> JavaScript Display Possibilities Using console.log() </h2> <p id=\"GFG\"></p> <!-- Script to use console.log() --> <script> console.log(10*2); </script></body> </html> Output:" }, { "code": null, "e": 3921, "s": 3913, "text": "Syntax:" }, { "code": null, "e": 3935, "s": 3921, "text": "console.log()" }, { "code": null, "e": 4002, "s": 3935, "text": "Example: This example uses console.log() property to display data." }, { "code": "<!DOCTYPE html><html> <head> <title> JavaScript Output using innerHTML </title></head> <body> <h1>GeeksforGeeks</h1> <h2> JavaScript Display Possibilities Using console.log() </h2> <p id=\"GFG\"></p> <!-- Script to use console.log() --> <script> console.log(10*2); </script></body> </html> ", "e": 4382, "s": 4002, "text": null }, { "code": null, "e": 4390, "s": 4382, "text": "Output:" }, { "code": null, "e": 4408, "s": 4390, "text": "javascript-basics" }, { "code": null, "e": 4415, "s": 4408, "text": "Picked" }, { "code": null, "e": 4426, "s": 4415, "text": "JavaScript" }, { "code": null, "e": 4443, "s": 4426, "text": "Web Technologies" } ]
Sparse Matrix Multiplication in C++
Suppose we have two matrices A and B, we have to find the result of AB. We may assume that A's column number is equal to B's row number. So, if the input is like [[1,0,0],[-1,0,3]] [[7,0,0],[0,0,0],[0,0,1]], then the output will be [[7,0,0],[-7,0,3]] To solve this, we will follow these steps − r1 := size of A, r2 := size of B r1 := size of A, r2 := size of B c1 := size of A[0], c2 := size of B[0] c1 := size of A[0], c2 := size of B[0] Define one 2D array ret of order r1 x c2 Define one 2D array ret of order r1 x c2 Define an array sparseA[r1] of pairs Define an array sparseA[r1] of pairs for initialize i := 0, when i < r1, update (increase i by 1), do −for initialize j := 0, when j < c1, update (increase j by 1), do −if A[i, j] is not equal to 0, then −insert { j, A[i, j] } at the end of sparseA[i] for initialize i := 0, when i < r1, update (increase i by 1), do − for initialize j := 0, when j < c1, update (increase j by 1), do −if A[i, j] is not equal to 0, then −insert { j, A[i, j] } at the end of sparseA[i] for initialize j := 0, when j < c1, update (increase j by 1), do − if A[i, j] is not equal to 0, then −insert { j, A[i, j] } at the end of sparseA[i] if A[i, j] is not equal to 0, then − insert { j, A[i, j] } at the end of sparseA[i] insert { j, A[i, j] } at the end of sparseA[i] for initialize i := 0, when i < r1, update (increase i by 1), do −for initialize j := 0, when j < size of sparseA[i], update (increase j by 1), do −for initialize k := 0, when k < c2, update (increase k by 1), do −x := first element of sparseA[i, j]if B[x, k] is not equal to 0, then −ret[i, k] := ret[i, k] + second element of sparseA[i, j] * B[x, k] for initialize i := 0, when i < r1, update (increase i by 1), do − for initialize j := 0, when j < size of sparseA[i], update (increase j by 1), do −for initialize k := 0, when k < c2, update (increase k by 1), do −x := first element of sparseA[i, j]if B[x, k] is not equal to 0, then −ret[i, k] := ret[i, k] + second element of sparseA[i, j] * B[x, k] for initialize j := 0, when j < size of sparseA[i], update (increase j by 1), do − for initialize k := 0, when k < c2, update (increase k by 1), do −x := first element of sparseA[i, j]if B[x, k] is not equal to 0, then −ret[i, k] := ret[i, k] + second element of sparseA[i, j] * B[x, k] for initialize k := 0, when k < c2, update (increase k by 1), do − x := first element of sparseA[i, j] x := first element of sparseA[i, j] if B[x, k] is not equal to 0, then −ret[i, k] := ret[i, k] + second element of sparseA[i, j] * B[x, k] if B[x, k] is not equal to 0, then − ret[i, k] := ret[i, k] + second element of sparseA[i, j] * B[x, k] ret[i, k] := ret[i, k] + second element of sparseA[i, j] * B[x, k] return ret return ret Let us see the following implementation to get better understanding − class Solution { public: vector<vector<int<> multiply(vector<vector<int<>& A, vector<vector<int<>& B) { int r1 = A.size(); int r2 = B.size(); int c1 = A[0].size(); int c2 = B[0].size(); vector < vector <int< > ret(r1, vector <int< (c2)); vector < pair <int, int> > sparseA[r1]; for(int i = 0; i < r1; i++){ for(int j = 0; j < c1; j++){ if(A[i][j] != 0)sparseA[i].push_back({j, A[i][j]}); } } for(int i = 0; i < r1; i++){ for(int j = 0; j < sparseA[i].size(); j++){ for(int k = 0; k < c2; k++){ int x = sparseA[i][j].first; if(B[x][k] != 0){ ret[i][k] += sparseA[i][j].second * B[x][k]; } } } } return ret; } }; {{1,0,0},{-1,0,3}},{{7,0,0},{0,0,0},{0,0,1}} [[7, 0, 0, ],[-7, 0, 3, ],]
[ { "code": null, "e": 1324, "s": 1187, "text": "Suppose we have two matrices A and B, we have to find the result of AB. We may assume that A's column number is equal to B's row number." }, { "code": null, "e": 1395, "s": 1324, "text": "So, if the input is like [[1,0,0],[-1,0,3]] [[7,0,0],[0,0,0],[0,0,1]]," }, { "code": null, "e": 1438, "s": 1395, "text": "then the output will be [[7,0,0],[-7,0,3]]" }, { "code": null, "e": 1482, "s": 1438, "text": "To solve this, we will follow these steps −" }, { "code": null, "e": 1515, "s": 1482, "text": "r1 := size of A, r2 := size of B" }, { "code": null, "e": 1548, "s": 1515, "text": "r1 := size of A, r2 := size of B" }, { "code": null, "e": 1587, "s": 1548, "text": "c1 := size of A[0], c2 := size of B[0]" }, { "code": null, "e": 1626, "s": 1587, "text": "c1 := size of A[0], c2 := size of B[0]" }, { "code": null, "e": 1667, "s": 1626, "text": "Define one 2D array ret of order r1 x c2" }, { "code": null, "e": 1708, "s": 1667, "text": "Define one 2D array ret of order r1 x c2" }, { "code": null, "e": 1745, "s": 1708, "text": "Define an array sparseA[r1] of pairs" }, { "code": null, "e": 1782, "s": 1745, "text": "Define an array sparseA[r1] of pairs" }, { "code": null, "e": 1997, "s": 1782, "text": "for initialize i := 0, when i < r1, update (increase i by 1), do −for initialize j := 0, when j < c1, update (increase j by 1), do −if A[i, j] is not equal to 0, then −insert { j, A[i, j] } at the end of sparseA[i]" }, { "code": null, "e": 2064, "s": 1997, "text": "for initialize i := 0, when i < r1, update (increase i by 1), do −" }, { "code": null, "e": 2213, "s": 2064, "text": "for initialize j := 0, when j < c1, update (increase j by 1), do −if A[i, j] is not equal to 0, then −insert { j, A[i, j] } at the end of sparseA[i]" }, { "code": null, "e": 2280, "s": 2213, "text": "for initialize j := 0, when j < c1, update (increase j by 1), do −" }, { "code": null, "e": 2363, "s": 2280, "text": "if A[i, j] is not equal to 0, then −insert { j, A[i, j] } at the end of sparseA[i]" }, { "code": null, "e": 2400, "s": 2363, "text": "if A[i, j] is not equal to 0, then −" }, { "code": null, "e": 2447, "s": 2400, "text": "insert { j, A[i, j] } at the end of sparseA[i]" }, { "code": null, "e": 2494, "s": 2447, "text": "insert { j, A[i, j] } at the end of sparseA[i]" }, { "code": null, "e": 2846, "s": 2494, "text": "for initialize i := 0, when i < r1, update (increase i by 1), do −for initialize j := 0, when j < size of sparseA[i], update (increase j by 1), do −for initialize k := 0, when k < c2, update (increase k by 1), do −x := first element of sparseA[i, j]if B[x, k] is not equal to 0, then −ret[i, k] := ret[i, k] + second element of sparseA[i, j] * B[x, k]" }, { "code": null, "e": 2913, "s": 2846, "text": "for initialize i := 0, when i < r1, update (increase i by 1), do −" }, { "code": null, "e": 3199, "s": 2913, "text": "for initialize j := 0, when j < size of sparseA[i], update (increase j by 1), do −for initialize k := 0, when k < c2, update (increase k by 1), do −x := first element of sparseA[i, j]if B[x, k] is not equal to 0, then −ret[i, k] := ret[i, k] + second element of sparseA[i, j] * B[x, k]" }, { "code": null, "e": 3282, "s": 3199, "text": "for initialize j := 0, when j < size of sparseA[i], update (increase j by 1), do −" }, { "code": null, "e": 3486, "s": 3282, "text": "for initialize k := 0, when k < c2, update (increase k by 1), do −x := first element of sparseA[i, j]if B[x, k] is not equal to 0, then −ret[i, k] := ret[i, k] + second element of sparseA[i, j] * B[x, k]" }, { "code": null, "e": 3553, "s": 3486, "text": "for initialize k := 0, when k < c2, update (increase k by 1), do −" }, { "code": null, "e": 3589, "s": 3553, "text": "x := first element of sparseA[i, j]" }, { "code": null, "e": 3625, "s": 3589, "text": "x := first element of sparseA[i, j]" }, { "code": null, "e": 3728, "s": 3625, "text": "if B[x, k] is not equal to 0, then −ret[i, k] := ret[i, k] + second element of sparseA[i, j] * B[x, k]" }, { "code": null, "e": 3765, "s": 3728, "text": "if B[x, k] is not equal to 0, then −" }, { "code": null, "e": 3832, "s": 3765, "text": "ret[i, k] := ret[i, k] + second element of sparseA[i, j] * B[x, k]" }, { "code": null, "e": 3899, "s": 3832, "text": "ret[i, k] := ret[i, k] + second element of sparseA[i, j] * B[x, k]" }, { "code": null, "e": 3910, "s": 3899, "text": "return ret" }, { "code": null, "e": 3921, "s": 3910, "text": "return ret" }, { "code": null, "e": 3991, "s": 3921, "text": "Let us see the following implementation to get better understanding −" }, { "code": null, "e": 4809, "s": 3991, "text": "class Solution {\npublic:\n vector<vector<int<> multiply(vector<vector<int<>& A, vector<vector<int<>& B) {\n int r1 = A.size();\n int r2 = B.size();\n int c1 = A[0].size();\n int c2 = B[0].size();\n vector < vector <int< > ret(r1, vector <int< (c2));\n vector < pair <int, int> > sparseA[r1];\n for(int i = 0; i < r1; i++){\n for(int j = 0; j < c1; j++){\n if(A[i][j] != 0)sparseA[i].push_back({j, A[i][j]});\n }\n }\n for(int i = 0; i < r1; i++){\n for(int j = 0; j < sparseA[i].size(); j++){\n for(int k = 0; k < c2; k++){\n int x = sparseA[i][j].first;\n if(B[x][k] != 0){\n ret[i][k] += sparseA[i][j].second * B[x][k];\n }\n }\n }\n }\n return ret;\n }\n};" }, { "code": null, "e": 4854, "s": 4809, "text": "{{1,0,0},{-1,0,3}},{{7,0,0},{0,0,0},{0,0,1}}" }, { "code": null, "e": 4882, "s": 4854, "text": "[[7, 0, 0, ],[-7, 0, 3, ],]" } ]
How to find the difference between two dataframes in R ?
21 Apr, 2021 In this article, we will discuss how to find the difference between two data frames or compare two dataframes or data sets in R Programming Language. Intersect function in R helps to get the common elements in the two datasets. Syntax: intersect(names(data_short), names(data_long)) Example: R first <- data.frame( "1" = c('0.44','0.554','0.67','0.64'), "2" = c('0.124','0.22','0.82','0.994'), "3" = c('0.82','1.22','0.73','1.23') ) second <- data.frame( "1" = runif(4), "2" = runif(4), "3" = runif(4), "d" = runif(4), "e" = runif(4) ) second[intersect(names(first), names(second))] Output: 1 2 3 1 0.562627228 0.9391250 0.6437934 2 0.003867576 0.7131200 0.9313777 3 0.129852760 0.2657934 0.9291285 4 0.325867139 0.2367633 0.1211350 This function unlike intersect helps to view the columns that are the missing in first dataframe. Syntax: setdiff( dataframe2, dataframe 1) Example: R first <- data.frame( "1" = c('0.44','0.554','0.67','0.64'), "2" = c('0.124','0.22','0.82','0.994'), "3" = c('0.82','1.22','0.73','1.23') ) second <- data.frame( "1" = runif(4), "2" = runif(4), "3" = runif(4), "d" = runif(4), "e" = runif(4) ) second[setdiff(names(second), names(first))] Output: d e 1 0.7899783 0.04363003 2 0.9167861 0.39865991 3 0.3314494 0.13963663 4 0.7005957 0.73401069 We will select from dplyr to get the columns of the dataframe on which some operations will be performed to get the desired difference between the two dataframes. Example: R library("dplyr") first <- data.frame( "1" = c('0.44','0.554','0.67','0.64'), "2" = c('0.124','0.22','0.82','0.994'), "3" = c('0.82','1.22','0.73','1.23') ) second <- data.frame( "1" = runif(4), "2" = runif(4), "3" = runif(4), "d" = runif(4), "e" = runif(4) ) second%>%select(which(!(colnames(second) %in% colnames(first)))) Output: d e 1 0.7899783 0.04363003 2 0.9167861 0.39865991 3 0.3314494 0.13963663 4 0.7005957 0.73401069 Picked R DataFrame-Programs R-DataFrame R Language R Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Change Color of Bars in Barchart using ggplot2 in R How to Split Column Into Multiple Columns in R DataFrame? Group by function in R using Dplyr How to Change Axis Scales in R Plots? How to filter R DataFrame by values in a column? How to Split Column Into Multiple Columns in R DataFrame? How to filter R DataFrame by values in a column? Replace Specific Characters in String in R Merge DataFrames by Column Names in R How to Sort a DataFrame in R ?
[ { "code": null, "e": 28, "s": 0, "text": "\n21 Apr, 2021" }, { "code": null, "e": 179, "s": 28, "text": "In this article, we will discuss how to find the difference between two data frames or compare two dataframes or data sets in R Programming Language. " }, { "code": null, "e": 257, "s": 179, "text": "Intersect function in R helps to get the common elements in the two datasets." }, { "code": null, "e": 265, "s": 257, "text": "Syntax:" }, { "code": null, "e": 312, "s": 265, "text": "intersect(names(data_short), names(data_long))" }, { "code": null, "e": 321, "s": 312, "text": "Example:" }, { "code": null, "e": 323, "s": 321, "text": "R" }, { "code": "first <- data.frame( \"1\" = c('0.44','0.554','0.67','0.64'), \"2\" = c('0.124','0.22','0.82','0.994'), \"3\" = c('0.82','1.22','0.73','1.23') ) second <- data.frame( \"1\" = runif(4), \"2\" = runif(4), \"3\" = runif(4), \"d\" = runif(4), \"e\" = runif(4) ) second[intersect(names(first), names(second))]", "e": 735, "s": 323, "text": null }, { "code": null, "e": 743, "s": 735, "text": "Output:" }, { "code": null, "e": 786, "s": 743, "text": " 1 2 3" }, { "code": null, "e": 820, "s": 786, "text": "1 0.562627228 0.9391250 0.6437934" }, { "code": null, "e": 854, "s": 820, "text": "2 0.003867576 0.7131200 0.9313777" }, { "code": null, "e": 888, "s": 854, "text": "3 0.129852760 0.2657934 0.9291285" }, { "code": null, "e": 922, "s": 888, "text": "4 0.325867139 0.2367633 0.1211350" }, { "code": null, "e": 1021, "s": 922, "text": "This function unlike intersect helps to view the columns that are the missing in first dataframe. " }, { "code": null, "e": 1029, "s": 1021, "text": "Syntax:" }, { "code": null, "e": 1063, "s": 1029, "text": "setdiff( dataframe2, dataframe 1)" }, { "code": null, "e": 1072, "s": 1063, "text": "Example:" }, { "code": null, "e": 1074, "s": 1072, "text": "R" }, { "code": "first <- data.frame( \"1\" = c('0.44','0.554','0.67','0.64'), \"2\" = c('0.124','0.22','0.82','0.994'), \"3\" = c('0.82','1.22','0.73','1.23') ) second <- data.frame( \"1\" = runif(4), \"2\" = runif(4), \"3\" = runif(4), \"d\" = runif(4), \"e\" = runif(4) ) second[setdiff(names(second), names(first))]", "e": 1484, "s": 1074, "text": null }, { "code": null, "e": 1492, "s": 1484, "text": "Output:" }, { "code": null, "e": 1514, "s": 1492, "text": " d e" }, { "code": null, "e": 1537, "s": 1514, "text": "1 0.7899783 0.04363003" }, { "code": null, "e": 1560, "s": 1537, "text": "2 0.9167861 0.39865991" }, { "code": null, "e": 1583, "s": 1560, "text": "3 0.3314494 0.13963663" }, { "code": null, "e": 1606, "s": 1583, "text": "4 0.7005957 0.73401069" }, { "code": null, "e": 1770, "s": 1606, "text": "We will select from dplyr to get the columns of the dataframe on which some operations will be performed to get the desired difference between the two dataframes. " }, { "code": null, "e": 1779, "s": 1770, "text": "Example:" }, { "code": null, "e": 1781, "s": 1779, "text": "R" }, { "code": "library(\"dplyr\") first <- data.frame( \"1\" = c('0.44','0.554','0.67','0.64'), \"2\" = c('0.124','0.22','0.82','0.994'), \"3\" = c('0.82','1.22','0.73','1.23') ) second <- data.frame( \"1\" = runif(4), \"2\" = runif(4), \"3\" = runif(4), \"d\" = runif(4), \"e\" = runif(4) ) second%>%select(which(!(colnames(second) %in% colnames(first))))", "e": 2229, "s": 1781, "text": null }, { "code": null, "e": 2237, "s": 2229, "text": "Output:" }, { "code": null, "e": 2260, "s": 2237, "text": " d e" }, { "code": null, "e": 2283, "s": 2260, "text": "1 0.7899783 0.04363003" }, { "code": null, "e": 2306, "s": 2283, "text": "2 0.9167861 0.39865991" }, { "code": null, "e": 2329, "s": 2306, "text": "3 0.3314494 0.13963663" }, { "code": null, "e": 2352, "s": 2329, "text": "4 0.7005957 0.73401069" }, { "code": null, "e": 2359, "s": 2352, "text": "Picked" }, { "code": null, "e": 2380, "s": 2359, "text": "R DataFrame-Programs" }, { "code": null, "e": 2392, "s": 2380, "text": "R-DataFrame" }, { "code": null, "e": 2403, "s": 2392, "text": "R Language" }, { "code": null, "e": 2414, "s": 2403, "text": "R Programs" }, { "code": null, "e": 2512, "s": 2414, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2564, "s": 2512, "text": "Change Color of Bars in Barchart using ggplot2 in R" }, { "code": null, "e": 2622, "s": 2564, "text": "How to Split Column Into Multiple Columns in R DataFrame?" }, { "code": null, "e": 2657, "s": 2622, "text": "Group by function in R using Dplyr" }, { "code": null, "e": 2695, "s": 2657, "text": "How to Change Axis Scales in R Plots?" }, { "code": null, "e": 2744, "s": 2695, "text": "How to filter R DataFrame by values in a column?" }, { "code": null, "e": 2802, "s": 2744, "text": "How to Split Column Into Multiple Columns in R DataFrame?" }, { "code": null, "e": 2851, "s": 2802, "text": "How to filter R DataFrame by values in a column?" }, { "code": null, "e": 2894, "s": 2851, "text": "Replace Specific Characters in String in R" }, { "code": null, "e": 2932, "s": 2894, "text": "Merge DataFrames by Column Names in R" } ]
PostgreSQL – ILIKE operator
28 Aug, 2020 The PostgreSQL ILIKE operator is used query data using pattern matching techniques. Its result include strings that are case-insensitive and follow the mentioned pattern.It is important to know that PostgreSQL provides with 2 special wildcard characters for the purpose of patterns matching as below: Percent ( %) for matching any sequence of characters. Underscore ( _) for matching any single character. Syntax: string ILIKE pattern; For the sake of this article we will be using the sample DVD rental database, which is explained here and can be downloaded by clicking on this link in our examples. Now, let’s look into a few examples. Example 1:Here we will make a query to find the customer in the “customer” table by looking at the “first_name” column to see if there is any value that begins with “ke” using the ILIKE operator in our sample database. SELECT first_name, last_name FROM customer WHERE first_name ILIKE 'Ke%'; Output: Notice few things in the above example, the WHERE clause contains a special expression: the first_name, the LIKE operator, and a string that contains a percent (%) character, which is referred to as a pattern. Example 2:Here we will query for customers whose first name begins with any single character, is followed by the literal string “aR”, and ends with any number of characters using the ILIKE operator in our sample database. SELECT first_name, last_name FROM customer WHERE first_name ILIKE '_aR%'; Output: postgreSQL-operators Misc Misc Misc Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n28 Aug, 2020" }, { "code": null, "e": 329, "s": 28, "text": "The PostgreSQL ILIKE operator is used query data using pattern matching techniques. Its result include strings that are case-insensitive and follow the mentioned pattern.It is important to know that PostgreSQL provides with 2 special wildcard characters for the purpose of patterns matching as below:" }, { "code": null, "e": 383, "s": 329, "text": "Percent ( %) for matching any sequence of characters." }, { "code": null, "e": 434, "s": 383, "text": "Underscore ( _) for matching any single character." }, { "code": null, "e": 464, "s": 434, "text": "Syntax: string ILIKE pattern;" }, { "code": null, "e": 630, "s": 464, "text": "For the sake of this article we will be using the sample DVD rental database, which is explained here and can be downloaded by clicking on this link in our examples." }, { "code": null, "e": 667, "s": 630, "text": "Now, let’s look into a few examples." }, { "code": null, "e": 886, "s": 667, "text": "Example 1:Here we will make a query to find the customer in the “customer” table by looking at the “first_name” column to see if there is any value that begins with “ke” using the ILIKE operator in our sample database." }, { "code": null, "e": 979, "s": 886, "text": "SELECT\n first_name,\n last_name\nFROM\n customer\nWHERE\n first_name ILIKE 'Ke%';" }, { "code": null, "e": 987, "s": 979, "text": "Output:" }, { "code": null, "e": 1197, "s": 987, "text": "Notice few things in the above example, the WHERE clause contains a special expression: the first_name, the LIKE operator, and a string that contains a percent (%) character, which is referred to as a pattern." }, { "code": null, "e": 1419, "s": 1197, "text": "Example 2:Here we will query for customers whose first name begins with any single character, is followed by the literal string “aR”, and ends with any number of characters using the ILIKE operator in our sample database." }, { "code": null, "e": 1509, "s": 1419, "text": "SELECT\n first_name,\n last_name\nFROM\n customer\nWHERE\n first_name ILIKE '_aR%';" }, { "code": null, "e": 1517, "s": 1509, "text": "Output:" }, { "code": null, "e": 1538, "s": 1517, "text": "postgreSQL-operators" }, { "code": null, "e": 1543, "s": 1538, "text": "Misc" }, { "code": null, "e": 1548, "s": 1543, "text": "Misc" }, { "code": null, "e": 1553, "s": 1548, "text": "Misc" } ]
Python | Find Maximum difference pair - GeeksforGeeks
29 Apr, 2019 Sometimes, we need to find the specific problem of getting the pair which yields the maximum difference, this can be solved by sorting and getting the first and last elements of the list. But in some case, we don’t with to change the ordering of list and perform some operation in a similar list without using extra space. Let’s discuss certain ways in which this can be performed. Method #1 : Using list comprehension + max() + combination() + lambda This particular task can be performed using the combination of above functions in which we use list comprehension to bind all the functionalities and max function to get the maximum difference, combination function finds all differences internally and lambda function is used to compute the difference. # Python3 code to demonstrate# maximum difference pair# using list comprehension + max() + combinations() + lambdafrom itertools import combinations # initializing listtest_list = [3, 4, 1, 7, 9, 1] # printing original listprint("The original list : " + str(test_list)) # using list comprehension + max() + combinations() + lambda# maximum difference pairres = max(combinations(test_list, 2), key = lambda sub: abs(sub[0]-sub[1])) # print resultprint("The maximum difference pair is : " + str(res)) The original list : [3, 4, 1, 7, 9, 1] The maximum difference pair is : (1, 9) Method #2 : Using list comprehension + nlargest() + combination() + lambda This method has potential of not only finding a single maximum but also k maximum difference pairs if required and uses nlargest function instead of max function to achieve this functionality. # Python3 code to demonstrate# maximum difference pair# using list comprehension + nlargest() + combinations() + lambdafrom itertools import combinationsfrom heapq import nlargest # initializing listtest_list = [3, 4, 1, 7, 9, 8] # printing original listprint("The original list : " + str(test_list)) # using list comprehension + max() + combinations() + lambda# maximum difference pair# computes 2 maximum pair differencesres = nlargest(2, combinations(test_list, 2), key = lambda sub: abs(sub[0]-sub[1])) # print resultprint("The maximum difference pair is : " + str(res)) The original list : [3, 4, 1, 7, 9, 8] The maximum difference pair is : [(1, 9), (1, 8)] Python list-programs Python Python Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Python Dictionary Read a file line by line in Python Enumerate() in Python How to Install PIP on Windows ? Iterate over a list in Python Python program to convert a list to string 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
[ { "code": null, "e": 24731, "s": 24703, "text": "\n29 Apr, 2019" }, { "code": null, "e": 25113, "s": 24731, "text": "Sometimes, we need to find the specific problem of getting the pair which yields the maximum difference, this can be solved by sorting and getting the first and last elements of the list. But in some case, we don’t with to change the ordering of list and perform some operation in a similar list without using extra space. Let’s discuss certain ways in which this can be performed." }, { "code": null, "e": 25183, "s": 25113, "text": "Method #1 : Using list comprehension + max() + combination() + lambda" }, { "code": null, "e": 25486, "s": 25183, "text": "This particular task can be performed using the combination of above functions in which we use list comprehension to bind all the functionalities and max function to get the maximum difference, combination function finds all differences internally and lambda function is used to compute the difference." }, { "code": "# Python3 code to demonstrate# maximum difference pair# using list comprehension + max() + combinations() + lambdafrom itertools import combinations # initializing listtest_list = [3, 4, 1, 7, 9, 1] # printing original listprint(\"The original list : \" + str(test_list)) # using list comprehension + max() + combinations() + lambda# maximum difference pairres = max(combinations(test_list, 2), key = lambda sub: abs(sub[0]-sub[1])) # print resultprint(\"The maximum difference pair is : \" + str(res))", "e": 25989, "s": 25486, "text": null }, { "code": null, "e": 26069, "s": 25989, "text": "The original list : [3, 4, 1, 7, 9, 1]\nThe maximum difference pair is : (1, 9)\n" }, { "code": null, "e": 26146, "s": 26071, "text": "Method #2 : Using list comprehension + nlargest() + combination() + lambda" }, { "code": null, "e": 26339, "s": 26146, "text": "This method has potential of not only finding a single maximum but also k maximum difference pairs if required and uses nlargest function instead of max function to achieve this functionality." }, { "code": "# Python3 code to demonstrate# maximum difference pair# using list comprehension + nlargest() + combinations() + lambdafrom itertools import combinationsfrom heapq import nlargest # initializing listtest_list = [3, 4, 1, 7, 9, 8] # printing original listprint(\"The original list : \" + str(test_list)) # using list comprehension + max() + combinations() + lambda# maximum difference pair# computes 2 maximum pair differencesres = nlargest(2, combinations(test_list, 2), key = lambda sub: abs(sub[0]-sub[1])) # print resultprint(\"The maximum difference pair is : \" + str(res))", "e": 26927, "s": 26339, "text": null }, { "code": null, "e": 27017, "s": 26927, "text": "The original list : [3, 4, 1, 7, 9, 8]\nThe maximum difference pair is : [(1, 9), (1, 8)]\n" }, { "code": null, "e": 27038, "s": 27017, "text": "Python list-programs" }, { "code": null, "e": 27045, "s": 27038, "text": "Python" }, { "code": null, "e": 27061, "s": 27045, "text": "Python Programs" }, { "code": null, "e": 27159, "s": 27061, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27168, "s": 27159, "text": "Comments" }, { "code": null, "e": 27181, "s": 27168, "text": "Old Comments" }, { "code": null, "e": 27199, "s": 27181, "text": "Python Dictionary" }, { "code": null, "e": 27234, "s": 27199, "text": "Read a file line by line in Python" }, { "code": null, "e": 27256, "s": 27234, "text": "Enumerate() in Python" }, { "code": null, "e": 27288, "s": 27256, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 27318, "s": 27288, "text": "Iterate over a list in Python" }, { "code": null, "e": 27361, "s": 27318, "text": "Python program to convert a list to string" }, { "code": null, "e": 27383, "s": 27361, "text": "Defaultdict in Python" }, { "code": null, "e": 27422, "s": 27383, "text": "Python | Get dictionary keys as a list" }, { "code": null, "e": 27468, "s": 27422, "text": "Python | Split string into list of characters" } ]
XML - Declaration
This chapter covers XML declaration in detail. XML declaration contains details that prepare an XML processor to parse the XML document. It is optional, but when used, it must appear in the first line of the XML document. Following syntax shows XML declaration − <?xml version = "version_number" encoding = "encoding_declaration" standalone = "standalone_status" ?> Each parameter consists of a parameter name, an equals sign (=), and parameter value inside a quote. Following table shows the above syntax in detail − An XML declaration should abide with the following rules − If the XML declaration is present in the XML, it must be placed as the first line in the XML document. If the XML declaration is present in the XML, it must be placed as the first line in the XML document. If the XML declaration is included, it must contain version number attribute. If the XML declaration is included, it must contain version number attribute. The Parameter names and values are case-sensitive. The Parameter names and values are case-sensitive. The names are always in lower case. The names are always in lower case. The order of placing the parameters is important. The correct order is: version, encoding and standalone. The order of placing the parameters is important. The correct order is: version, encoding and standalone. Either single or double quotes may be used. Either single or double quotes may be used. The XML declaration has no closing tag i.e. </?xml> The XML declaration has no closing tag i.e. </?xml> Following are few examples of XML declarations − XML declaration with no parameters − <?xml > XML declaration with version definition − <?xml version = "1.0"> XML declaration with all parameters defined − <?xml version = "1.0" encoding = "UTF-8" standalone = "no" ?> XML declaration with all parameters defined in single quotes − <?xml version = '1.0' encoding = 'iso-8859-1' standalone = 'no' ?> 84 Lectures 6 hours Frahaan Hussain 29 Lectures 2 hours YouAccel 27 Lectures 1 hours Jordan Stanchev 16 Lectures 2 hours Simon Sez IT Print Add Notes Bookmark this page
[ { "code": null, "e": 2183, "s": 1961, "text": "This chapter covers XML declaration in detail. XML declaration contains details that prepare an XML processor to parse the XML document. It is optional, but when used, it must appear in the first line of the XML document." }, { "code": null, "e": 2224, "s": 2183, "text": "Following syntax shows XML declaration −" }, { "code": null, "e": 2336, "s": 2224, "text": "<?xml\n version = \"version_number\"\n encoding = \"encoding_declaration\"\n standalone = \"standalone_status\"\n?>" }, { "code": null, "e": 2488, "s": 2336, "text": "Each parameter consists of a parameter name, an equals sign (=), and parameter value inside a quote. Following table shows the above syntax in detail −" }, { "code": null, "e": 2547, "s": 2488, "text": "An XML declaration should abide with the following rules −" }, { "code": null, "e": 2650, "s": 2547, "text": "If the XML declaration is present in the XML, it must be placed as the first line in the XML document." }, { "code": null, "e": 2753, "s": 2650, "text": "If the XML declaration is present in the XML, it must be placed as the first line in the XML document." }, { "code": null, "e": 2831, "s": 2753, "text": "If the XML declaration is included, it must contain version number attribute." }, { "code": null, "e": 2909, "s": 2831, "text": "If the XML declaration is included, it must contain version number attribute." }, { "code": null, "e": 2960, "s": 2909, "text": "The Parameter names and values are case-sensitive." }, { "code": null, "e": 3011, "s": 2960, "text": "The Parameter names and values are case-sensitive." }, { "code": null, "e": 3047, "s": 3011, "text": "The names are always in lower case." }, { "code": null, "e": 3083, "s": 3047, "text": "The names are always in lower case." }, { "code": null, "e": 3189, "s": 3083, "text": "The order of placing the parameters is important. The correct order is: version, encoding and standalone." }, { "code": null, "e": 3295, "s": 3189, "text": "The order of placing the parameters is important. The correct order is: version, encoding and standalone." }, { "code": null, "e": 3339, "s": 3295, "text": "Either single or double quotes may be used." }, { "code": null, "e": 3383, "s": 3339, "text": "Either single or double quotes may be used." }, { "code": null, "e": 3435, "s": 3383, "text": "The XML declaration has no closing tag i.e. </?xml>" }, { "code": null, "e": 3487, "s": 3435, "text": "The XML declaration has no closing tag i.e. </?xml>" }, { "code": null, "e": 3536, "s": 3487, "text": "Following are few examples of XML declarations −" }, { "code": null, "e": 3573, "s": 3536, "text": "XML declaration with no parameters −" }, { "code": null, "e": 3582, "s": 3573, "text": "<?xml >\n" }, { "code": null, "e": 3624, "s": 3582, "text": "XML declaration with version definition −" }, { "code": null, "e": 3648, "s": 3624, "text": "<?xml version = \"1.0\">\n" }, { "code": null, "e": 3694, "s": 3648, "text": "XML declaration with all parameters defined −" }, { "code": null, "e": 3757, "s": 3694, "text": "<?xml version = \"1.0\" encoding = \"UTF-8\" standalone = \"no\" ?>\n" }, { "code": null, "e": 3820, "s": 3757, "text": "XML declaration with all parameters defined in single quotes −" }, { "code": null, "e": 3888, "s": 3820, "text": "<?xml version = '1.0' encoding = 'iso-8859-1' standalone = 'no' ?>\n" }, { "code": null, "e": 3921, "s": 3888, "text": "\n 84 Lectures \n 6 hours \n" }, { "code": null, "e": 3938, "s": 3921, "text": " Frahaan Hussain" }, { "code": null, "e": 3971, "s": 3938, "text": "\n 29 Lectures \n 2 hours \n" }, { "code": null, "e": 3981, "s": 3971, "text": " YouAccel" }, { "code": null, "e": 4014, "s": 3981, "text": "\n 27 Lectures \n 1 hours \n" }, { "code": null, "e": 4031, "s": 4014, "text": " Jordan Stanchev" }, { "code": null, "e": 4064, "s": 4031, "text": "\n 16 Lectures \n 2 hours \n" }, { "code": null, "e": 4078, "s": 4064, "text": " Simon Sez IT" }, { "code": null, "e": 4085, "s": 4078, "text": " Print" }, { "code": null, "e": 4096, "s": 4085, "text": " Add Notes" } ]
A Better mAP for Object Detection | by Ivan Ralašić | Towards Data Science
TL;DR: Your object detection model sucks and you want to improve it by leveraging better evaluation metrics... skip the introduction, and find out how or go directly to the Google Colab notebook for the code or here for the ClearML experiment log! Object detection is easy. All you need to do is get a training dataset, download a pre-trained model from one of the open-source libraries like Tensorflow Object Detection API, Detectron2, and mmdetection, and (re)train it. In reality, after training your model for hours, you evaluate it, check the metrics... and you end up completely disappointed with the performance as it’s miles away from what you’ve expected! Now you’re in trouble... there are no good tutorials, recipes, or StackOverflow topics on how to debug the performance of the model and how to optimize it to achieve better performance. At Forsight, we use TIDE to achieve accurate object detection. This blog is all about sharing tips & tricks that will prove invaluable for improving the accuracy of your object detection model. There are two key aspects that make up the object detection model performance: speed and accuracy. There’s always a tradeoff between the two as can be seen in the table below. In this blog, we’ll focus exclusively on analyzing the model accuracy. In a nutshell, object detectors predict the location of objects of a given class in an image with a certain confidence score. Locations of the objects are defined by placing bounding boxes around the objects to identify their position. Therefore, a detection is represented by a set of three attributes: object class (i.e. person)corresponding bounding box (i.e. [63, 52, 150, 50])confidence score (i.e. 0.583 or 58.3%) object class (i.e. person) corresponding bounding box (i.e. [63, 52, 150, 50]) confidence score (i.e. 0.583 or 58.3%) Similarly, the performance evaluation of the object detection model is done based on: a set of ground-truth bounding boxes representing the rectangular areas of an image containing objects of the class to be detected, a set of detections predicted by a model, each one consisting of a bounding box, a class, and a confidence value. Consider an object of interest (person) represented by a ground-truth bounding box (green color) and the detected area represented by a predicted bounding box (red color) in the image below. Without taking into account the confidence score, a perfect match occurs when the area and location of the predicted and ground-truth boxes are the same, i.e. perfectly bounding the person. These two conditions are assessed by the intersection over union (IoU), a measurement based on the Jaccard index, a coefficient of similarity for two sets of data. In the object detection scope, the IoU is equal to the area of the overlap (intersection) between the predicted bounding box (red) and the ground-truth bounding box (green) divided by the area of their union. A few examples of different IoU scores can be seen in the image below. By setting an IoU threshold, a metric can be more or less restrictive on considering detections as correct or incorrect. An IoU threshold closer to 1 is more restrictive as it requires almost perfect detections, while an IoU threshold closer to, but different than 0 is more flexible, considering even small overlaps as valid detections. The confidence score reflects how likely the box contains an object of interest and how confident the classifier is about it. If no object exists in that box, the confidence score should ideally be zero. In general, the confidence score tends to be higher for tighter bounding boxes (strict IoU). Precision (Pr) is the ability of a model to identify only relevant objects and is calculated as the percentage of correct positive predictions. Recall (Rc) is the ability of a model to find all relevant cases (all ground-truth bounding boxes). It is the percentage of correct positive predictions among all given ground truths. To calculate the precision and recall values, each detected bounding box must first be classified as: True-positive (TP) — a correct detection of a ground-truth bounding box; False-positive (FP) — incorrect detection of a non-existing object or a misplaced detection of an existing object; False-negative (FN) — an undetected ground-truth bounding box; True Negative (TN) — does not apply to object detection because there are infinitely many instances that should not be detected as objects. To recap, the output of an object detector is characterized by a bounding box, a class, and a confidence score. The confidence score can be taken into account in the precision and recall calculations by considering as positive detections only those whose confidence is larger than a confidence threshold τ. The detections whose confidence level is smaller than τ are considered as negatives. Both TP(τ) and FP(τ) are decreasing functions of τ, as a larger τ reduces the number of positive detections. Conversely, FN(τ) is an increasing function of τ, since less positive detections imply a larger number of negative detections. The precision-recall (PR) curve is a plot of precision as a function of recall. It shows the trade-off between the two metrics for varying confidence values for the model detections. AP@α is the Area Under the precision-recall curve (AUC-PR). Mathematically, AP is defined as: Notation: AP@α means Average Precision(AP) at the IoU threshold of α. Therefore [email protected] and [email protected] mean AP at IoU threshold of 50% and 75% respectively. A high AUC-PR implies high precision and high recall. Naturally, the PR curve has a zig-zag behavior (not monotonically decreasing). Before calculating the AP, we make the PR curve to be monotonically decreasing using the following interpolation formula: After we calculate the AP for each individual class, we calculate the mean AP as an average of all AP for all classes: For an example of precision-recall curve calculation with a numerical example, please check a great blog post by Harshit Kumar. In the image below, we can see three different PR curves and they differ by the IoU threshold used in the precision/recall calculation. Since the AP corresponds to the area under the curve, it is obvious that a loose IoU threshold results in a higher AP score than a strict IoU threshold. For more details about the specifics of the COCO mAP metric visit: https://cocodataset.org/#detection-eval! As shown in the previous sections, object detection, and instance segmentation tasks usually only use one metric to benchmark model performance: mean Average Precision (mAP). While mAP succinctly summarizes the performance of a model in one number, disentangling errors in object detection and instance segmentation from mAP is difficult: a false positive can be a duplicate detection, misclassification, mislocalization, confusion with background, or even both misclassification and mislocalization. TIDE (Toolkit for Identifying Detection and segmentation Errors) was introduced to solve the aforementioned challenge. It segments the object detection errors into six types and introduces a technique for measuring the contribution of each error in a way that isolates its effect on overall performance. TIDE is basically COCO mAP on steroids! If your object detection model has a low mAP after training it on a custom dataset, you’ll for sure want to know where we can improve it additionally. This is where TIDE shines in all its glory. TIDE will help you pinpoint the exact type of error you should focus on improving in order to make your model run better. In the paper, there’s a detailed explanation of the error types and how they are defined. In order to create a meaningful distribution of errors that captures the components of mAP, we bin all false positives and false negatives in the model into one of 6 types as depicted in the figure below. Note that for some error types (classification and localization), a false positive can be paired with a false negative. We will use IoUmax to denote a false positive’s maximum IoU overlap with a ground truth of the given category. The foreground IoU threshold is denoted as tf and the background threshold is denoted as tb, which are set to 0.5 and 0.1 unless otherwise noted. 1. Classification Error: IoUmax ≥ tf for GT of the incorrect class (i.e., localized correctly but classified incorrectly). 2. Localization Error: tb ≤ IoUmax ≤ tf for GT of the correct class (i.e., classified correctly but localized incorrectly). 3. Both Cls and Loc Error: tb ≤ IoUmax ≤ tf for GT of the incorrect class (i.e., classified incorrectly and localized incorrectly). 4. Duplicate Detection Error: IoUmax ≥ tf for GT of the correct class but another higher-scoring detection already matched that GT (i.e., would be correct if not for a higher scoring detection). 5. Background Error: IoUmax ≤ tb for all GT (i.e., detected background as foreground). 6. Missed GT Error: All undetected ground truth (false negatives) not already covered by classification or localization error. TIDE is meant as a drop-in replacement for the COCO Evaluation toolkit, and getting started is pretty easy: from tidecv import TIDE, datasetstide = TIDE()tide.evaluate(datasets.COCO(), datasets.COCOResult('path/to/your/results/file'), mode=TIDE.BOX)tide.summarize() # Summarize the results as tables in the consoletide.plot() # Show a summary figure We’ve prepared a Google Colab notebook with a code sample that shows how to use TIDE with Tensorflow Object Detection API. If you don’t want to run the notebook and wait for the eval to finish, you can check the results on the Allegro ClearML dashboard which we use for experiment management. By using ClearML, we can persistently store all the experiment data in an organized way which enables us to easily perform comparisons and upload custom artifacts such as ground-truth and detection metadata in COCO format, as well as custom plots to the experiment. By comparing COCO evaluation results for EfficientDet-D0 and EfficientDet-D7 models, we see that EfficientDet-D7 has a higher mAP by ~15%. This is due to the larger capacity of the model — there are ~13x more parameters in EfficientDet-D7 compared to EfficentDet-D0. Note: There are some known discrepancies between mAP calculation in TIDE and pycocotools. That is the reason why the COCO mAP and TIDE mAP aren’t equal in certain cases. When comparing the TIDE evaluation results, we can see that the classification and duplicate detection errors are similar for both of the models, while the localization error is 2% lower for the D7 model. Error in detecting background as the foreground is higher 2% for the D7 model, while the missed GT error is 3.5% smaller for the D7 model compared to the D0. This can be explained by the fact that the D7 model has a higher recall rate which lowers the missed GT error, but at the same time, it increases the background classification error. The interesting part of the comparison is the mAP for false positives and false negatives. We can see that the false positive rate is very similar between the two models. This can be a sign that there is some unlabeled data in the dataset and that the model is detecting it with high confidence. On the other hand, the false-negative rate is significantly lower for the D7 model. It is obvious that the larger model can detect object instances which the smaller capacity model struggles with. In this comparison, we’ve compared the same model architecture (EfficientDet) with a different number of parameters (D0 vs D7). TIDE model evaluation is even more useful when we want to compare different model architectures, so feel free to try it yourself. TIDE paper [1] contains additional analysis on different object detection and segmentation models. TIDE plots for the previous analysis are available below. Recently, AI pioneer Andrew Ng launched a campaign for data-centric AI where his main goal is to shift the focus of AI practitioners from model/algorithm development to the quality of the data they use to train the models. While high-quality data indeed is the key to achieving the high-performance of the models, the models also play a key role: models and data cannot be completely decoupled. Only the focus can be switched from one to the other during the development process, depending on the bottlenecks identified by in-depth analysis. At Forsight, we found that understanding the performance of object detection models must go beyond vanilla frames-per-second (FPS) and mAP-based accuracy metrics. It is incredibly important not just to naively benchmark the models, but to understand what you should do to further improve their performance. Using more insightful metrics like those provided by TIDE makes it much easier to identify specific problems in your dataset such as unlabeled images, loose bounding boxes, etc. It also helps you identify situations where your model capacity just isn’t large enough for the specific task at hand. Solving these problems one by one will eventually lead you to significantly better machine algorithms, and help you create production-ready models for real-world applications! We hope that you found this blog post useful, please take a look at some other blogs written by our team at Forsight, and feel free to reach out to us at [email protected] if you have any questions! towardsdatascience.com medium.com towardsdatascience.com Daniel Bolya, Sean Foley, James Hays, and Judy Hoffman; TIDE: A General Toolbox for Identifying Object Detection Errors, ECCV 2020.Padilla, Rafael, Passos, Wesley L., Dias, Thadeu L. B., Netto, Sergio L. and da Silva, Eduardo A. B.; A Comparative Analysis of Object Detection Metrics with a Companion Open-Source Toolkit, Electronics 2021., https://doi.org/10.3390/electronics10030279Tushar Kolhe; How to boost object detection accuracy by understanding data, https://blog.gofynd.com/boost-object-detection-model-accuracy-552586d698cAdam Kelly; Create COCO Annotations From Scratch, https://www.immersivelimit.com/tutorials/create-coco-annotations-from-scratchKiprono Elijah Koech; Object Detection Metrics With Worked Example https://towardsdatascience.com/on-object-detection-metrics-with-worked-example-216f173ed31eHarshit Kumar; Evaluation metrics for object detection and segmentation - mAP, https://kharshit.github.io/blog/2019/09/20/evaluation-metrics-for-object-detection-and-segmentation Daniel Bolya, Sean Foley, James Hays, and Judy Hoffman; TIDE: A General Toolbox for Identifying Object Detection Errors, ECCV 2020. Padilla, Rafael, Passos, Wesley L., Dias, Thadeu L. B., Netto, Sergio L. and da Silva, Eduardo A. B.; A Comparative Analysis of Object Detection Metrics with a Companion Open-Source Toolkit, Electronics 2021., https://doi.org/10.3390/electronics10030279 Tushar Kolhe; How to boost object detection accuracy by understanding data, https://blog.gofynd.com/boost-object-detection-model-accuracy-552586d698c Adam Kelly; Create COCO Annotations From Scratch, https://www.immersivelimit.com/tutorials/create-coco-annotations-from-scratch Kiprono Elijah Koech; Object Detection Metrics With Worked Example https://towardsdatascience.com/on-object-detection-metrics-with-worked-example-216f173ed31e Harshit Kumar; Evaluation metrics for object detection and segmentation - mAP, https://kharshit.github.io/blog/2019/09/20/evaluation-metrics-for-object-detection-and-segmentation
[ { "code": null, "e": 420, "s": 172, "text": "TL;DR: Your object detection model sucks and you want to improve it by leveraging better evaluation metrics... skip the introduction, and find out how or go directly to the Google Colab notebook for the code or here for the ClearML experiment log!" }, { "code": null, "e": 644, "s": 420, "text": "Object detection is easy. All you need to do is get a training dataset, download a pre-trained model from one of the open-source libraries like Tensorflow Object Detection API, Detectron2, and mmdetection, and (re)train it." }, { "code": null, "e": 837, "s": 644, "text": "In reality, after training your model for hours, you evaluate it, check the metrics... and you end up completely disappointed with the performance as it’s miles away from what you’ve expected!" }, { "code": null, "e": 1217, "s": 837, "text": "Now you’re in trouble... there are no good tutorials, recipes, or StackOverflow topics on how to debug the performance of the model and how to optimize it to achieve better performance. At Forsight, we use TIDE to achieve accurate object detection. This blog is all about sharing tips & tricks that will prove invaluable for improving the accuracy of your object detection model." }, { "code": null, "e": 1464, "s": 1217, "text": "There are two key aspects that make up the object detection model performance: speed and accuracy. There’s always a tradeoff between the two as can be seen in the table below. In this blog, we’ll focus exclusively on analyzing the model accuracy." }, { "code": null, "e": 1700, "s": 1464, "text": "In a nutshell, object detectors predict the location of objects of a given class in an image with a certain confidence score. Locations of the objects are defined by placing bounding boxes around the objects to identify their position." }, { "code": null, "e": 1768, "s": 1700, "text": "Therefore, a detection is represented by a set of three attributes:" }, { "code": null, "e": 1884, "s": 1768, "text": "object class (i.e. person)corresponding bounding box (i.e. [63, 52, 150, 50])confidence score (i.e. 0.583 or 58.3%)" }, { "code": null, "e": 1911, "s": 1884, "text": "object class (i.e. person)" }, { "code": null, "e": 1963, "s": 1911, "text": "corresponding bounding box (i.e. [63, 52, 150, 50])" }, { "code": null, "e": 2002, "s": 1963, "text": "confidence score (i.e. 0.583 or 58.3%)" }, { "code": null, "e": 2088, "s": 2002, "text": "Similarly, the performance evaluation of the object detection model is done based on:" }, { "code": null, "e": 2220, "s": 2088, "text": "a set of ground-truth bounding boxes representing the rectangular areas of an image containing objects of the class to be detected," }, { "code": null, "e": 2334, "s": 2220, "text": "a set of detections predicted by a model, each one consisting of a bounding box, a class, and a confidence value." }, { "code": null, "e": 2715, "s": 2334, "text": "Consider an object of interest (person) represented by a ground-truth bounding box (green color) and the detected area represented by a predicted bounding box (red color) in the image below. Without taking into account the confidence score, a perfect match occurs when the area and location of the predicted and ground-truth boxes are the same, i.e. perfectly bounding the person." }, { "code": null, "e": 3088, "s": 2715, "text": "These two conditions are assessed by the intersection over union (IoU), a measurement based on the Jaccard index, a coefficient of similarity for two sets of data. In the object detection scope, the IoU is equal to the area of the overlap (intersection) between the predicted bounding box (red) and the ground-truth bounding box (green) divided by the area of their union." }, { "code": null, "e": 3497, "s": 3088, "text": "A few examples of different IoU scores can be seen in the image below. By setting an IoU threshold, a metric can be more or less restrictive on considering detections as correct or incorrect. An IoU threshold closer to 1 is more restrictive as it requires almost perfect detections, while an IoU threshold closer to, but different than 0 is more flexible, considering even small overlaps as valid detections." }, { "code": null, "e": 3794, "s": 3497, "text": "The confidence score reflects how likely the box contains an object of interest and how confident the classifier is about it. If no object exists in that box, the confidence score should ideally be zero. In general, the confidence score tends to be higher for tighter bounding boxes (strict IoU)." }, { "code": null, "e": 3938, "s": 3794, "text": "Precision (Pr) is the ability of a model to identify only relevant objects and is calculated as the percentage of correct positive predictions." }, { "code": null, "e": 4122, "s": 3938, "text": "Recall (Rc) is the ability of a model to find all relevant cases (all ground-truth bounding boxes). It is the percentage of correct positive predictions among all given ground truths." }, { "code": null, "e": 4224, "s": 4122, "text": "To calculate the precision and recall values, each detected bounding box must first be classified as:" }, { "code": null, "e": 4297, "s": 4224, "text": "True-positive (TP) — a correct detection of a ground-truth bounding box;" }, { "code": null, "e": 4412, "s": 4297, "text": "False-positive (FP) — incorrect detection of a non-existing object or a misplaced detection of an existing object;" }, { "code": null, "e": 4475, "s": 4412, "text": "False-negative (FN) — an undetected ground-truth bounding box;" }, { "code": null, "e": 4615, "s": 4475, "text": "True Negative (TN) — does not apply to object detection because there are infinitely many instances that should not be detected as objects." }, { "code": null, "e": 5007, "s": 4615, "text": "To recap, the output of an object detector is characterized by a bounding box, a class, and a confidence score. The confidence score can be taken into account in the precision and recall calculations by considering as positive detections only those whose confidence is larger than a confidence threshold τ. The detections whose confidence level is smaller than τ are considered as negatives." }, { "code": null, "e": 5243, "s": 5007, "text": "Both TP(τ) and FP(τ) are decreasing functions of τ, as a larger τ reduces the number of positive detections. Conversely, FN(τ) is an increasing function of τ, since less positive detections imply a larger number of negative detections." }, { "code": null, "e": 5520, "s": 5243, "text": "The precision-recall (PR) curve is a plot of precision as a function of recall. It shows the trade-off between the two metrics for varying confidence values for the model detections. AP@α is the Area Under the precision-recall curve (AUC-PR). Mathematically, AP is defined as:" }, { "code": null, "e": 5674, "s": 5520, "text": "Notation: AP@α means Average Precision(AP) at the IoU threshold of α. Therefore [email protected] and [email protected] mean AP at IoU threshold of 50% and 75% respectively." }, { "code": null, "e": 5929, "s": 5674, "text": "A high AUC-PR implies high precision and high recall. Naturally, the PR curve has a zig-zag behavior (not monotonically decreasing). Before calculating the AP, we make the PR curve to be monotonically decreasing using the following interpolation formula:" }, { "code": null, "e": 6048, "s": 5929, "text": "After we calculate the AP for each individual class, we calculate the mean AP as an average of all AP for all classes:" }, { "code": null, "e": 6176, "s": 6048, "text": "For an example of precision-recall curve calculation with a numerical example, please check a great blog post by Harshit Kumar." }, { "code": null, "e": 6465, "s": 6176, "text": "In the image below, we can see three different PR curves and they differ by the IoU threshold used in the precision/recall calculation. Since the AP corresponds to the area under the curve, it is obvious that a loose IoU threshold results in a higher AP score than a strict IoU threshold." }, { "code": null, "e": 6573, "s": 6465, "text": "For more details about the specifics of the COCO mAP metric visit: https://cocodataset.org/#detection-eval!" }, { "code": null, "e": 7074, "s": 6573, "text": "As shown in the previous sections, object detection, and instance segmentation tasks usually only use one metric to benchmark model performance: mean Average Precision (mAP). While mAP succinctly summarizes the performance of a model in one number, disentangling errors in object detection and instance segmentation from mAP is difficult: a false positive can be a duplicate detection, misclassification, mislocalization, confusion with background, or even both misclassification and mislocalization." }, { "code": null, "e": 7418, "s": 7074, "text": "TIDE (Toolkit for Identifying Detection and segmentation Errors) was introduced to solve the aforementioned challenge. It segments the object detection errors into six types and introduces a technique for measuring the contribution of each error in a way that isolates its effect on overall performance. TIDE is basically COCO mAP on steroids!" }, { "code": null, "e": 7735, "s": 7418, "text": "If your object detection model has a low mAP after training it on a custom dataset, you’ll for sure want to know where we can improve it additionally. This is where TIDE shines in all its glory. TIDE will help you pinpoint the exact type of error you should focus on improving in order to make your model run better." }, { "code": null, "e": 7825, "s": 7735, "text": "In the paper, there’s a detailed explanation of the error types and how they are defined." }, { "code": null, "e": 8261, "s": 7825, "text": "In order to create a meaningful distribution of errors that captures the components of mAP, we bin all false positives and false negatives in the model into one of 6 types as depicted in the figure below. Note that for some error types (classification and localization), a false positive can be paired with a false negative. We will use IoUmax to denote a false positive’s maximum IoU overlap with a ground truth of the given category." }, { "code": null, "e": 8407, "s": 8261, "text": "The foreground IoU threshold is denoted as tf and the background threshold is denoted as tb, which are set to 0.5 and 0.1 unless otherwise noted." }, { "code": null, "e": 8530, "s": 8407, "text": "1. Classification Error: IoUmax ≥ tf for GT of the incorrect class (i.e., localized correctly but classified incorrectly)." }, { "code": null, "e": 8654, "s": 8530, "text": "2. Localization Error: tb ≤ IoUmax ≤ tf for GT of the correct class (i.e., classified correctly but localized incorrectly)." }, { "code": null, "e": 8786, "s": 8654, "text": "3. Both Cls and Loc Error: tb ≤ IoUmax ≤ tf for GT of the incorrect class (i.e., classified incorrectly and localized incorrectly)." }, { "code": null, "e": 8981, "s": 8786, "text": "4. Duplicate Detection Error: IoUmax ≥ tf for GT of the correct class but another higher-scoring detection already matched that GT (i.e., would be correct if not for a higher scoring detection)." }, { "code": null, "e": 9068, "s": 8981, "text": "5. Background Error: IoUmax ≤ tb for all GT (i.e., detected background as foreground)." }, { "code": null, "e": 9195, "s": 9068, "text": "6. Missed GT Error: All undetected ground truth (false negatives) not already covered by classification or localization error." }, { "code": null, "e": 9303, "s": 9195, "text": "TIDE is meant as a drop-in replacement for the COCO Evaluation toolkit, and getting started is pretty easy:" }, { "code": null, "e": 9552, "s": 9303, "text": "from tidecv import TIDE, datasetstide = TIDE()tide.evaluate(datasets.COCO(), datasets.COCOResult('path/to/your/results/file'), mode=TIDE.BOX)tide.summarize() # Summarize the results as tables in the consoletide.plot() # Show a summary figure" }, { "code": null, "e": 9675, "s": 9552, "text": "We’ve prepared a Google Colab notebook with a code sample that shows how to use TIDE with Tensorflow Object Detection API." }, { "code": null, "e": 10111, "s": 9675, "text": "If you don’t want to run the notebook and wait for the eval to finish, you can check the results on the Allegro ClearML dashboard which we use for experiment management. By using ClearML, we can persistently store all the experiment data in an organized way which enables us to easily perform comparisons and upload custom artifacts such as ground-truth and detection metadata in COCO format, as well as custom plots to the experiment." }, { "code": null, "e": 10378, "s": 10111, "text": "By comparing COCO evaluation results for EfficientDet-D0 and EfficientDet-D7 models, we see that EfficientDet-D7 has a higher mAP by ~15%. This is due to the larger capacity of the model — there are ~13x more parameters in EfficientDet-D7 compared to EfficentDet-D0." }, { "code": null, "e": 10548, "s": 10378, "text": "Note: There are some known discrepancies between mAP calculation in TIDE and pycocotools. That is the reason why the COCO mAP and TIDE mAP aren’t equal in certain cases." }, { "code": null, "e": 10753, "s": 10548, "text": "When comparing the TIDE evaluation results, we can see that the classification and duplicate detection errors are similar for both of the models, while the localization error is 2% lower for the D7 model." }, { "code": null, "e": 11094, "s": 10753, "text": "Error in detecting background as the foreground is higher 2% for the D7 model, while the missed GT error is 3.5% smaller for the D7 model compared to the D0. This can be explained by the fact that the D7 model has a higher recall rate which lowers the missed GT error, but at the same time, it increases the background classification error." }, { "code": null, "e": 11587, "s": 11094, "text": "The interesting part of the comparison is the mAP for false positives and false negatives. We can see that the false positive rate is very similar between the two models. This can be a sign that there is some unlabeled data in the dataset and that the model is detecting it with high confidence. On the other hand, the false-negative rate is significantly lower for the D7 model. It is obvious that the larger model can detect object instances which the smaller capacity model struggles with." }, { "code": null, "e": 11944, "s": 11587, "text": "In this comparison, we’ve compared the same model architecture (EfficientDet) with a different number of parameters (D0 vs D7). TIDE model evaluation is even more useful when we want to compare different model architectures, so feel free to try it yourself. TIDE paper [1] contains additional analysis on different object detection and segmentation models." }, { "code": null, "e": 12002, "s": 11944, "text": "TIDE plots for the previous analysis are available below." }, { "code": null, "e": 12544, "s": 12002, "text": "Recently, AI pioneer Andrew Ng launched a campaign for data-centric AI where his main goal is to shift the focus of AI practitioners from model/algorithm development to the quality of the data they use to train the models. While high-quality data indeed is the key to achieving the high-performance of the models, the models also play a key role: models and data cannot be completely decoupled. Only the focus can be switched from one to the other during the development process, depending on the bottlenecks identified by in-depth analysis." }, { "code": null, "e": 12851, "s": 12544, "text": "At Forsight, we found that understanding the performance of object detection models must go beyond vanilla frames-per-second (FPS) and mAP-based accuracy metrics. It is incredibly important not just to naively benchmark the models, but to understand what you should do to further improve their performance." }, { "code": null, "e": 13324, "s": 12851, "text": "Using more insightful metrics like those provided by TIDE makes it much easier to identify specific problems in your dataset such as unlabeled images, loose bounding boxes, etc. It also helps you identify situations where your model capacity just isn’t large enough for the specific task at hand. Solving these problems one by one will eventually lead you to significantly better machine algorithms, and help you create production-ready models for real-world applications!" }, { "code": null, "e": 13522, "s": 13324, "text": "We hope that you found this blog post useful, please take a look at some other blogs written by our team at Forsight, and feel free to reach out to us at [email protected] if you have any questions!" }, { "code": null, "e": 13545, "s": 13522, "text": "towardsdatascience.com" }, { "code": null, "e": 13556, "s": 13545, "text": "medium.com" }, { "code": null, "e": 13579, "s": 13556, "text": "towardsdatascience.com" }, { "code": null, "e": 14576, "s": 13579, "text": "Daniel Bolya, Sean Foley, James Hays, and Judy Hoffman; TIDE: A General Toolbox for Identifying Object Detection Errors, ECCV 2020.Padilla, Rafael, Passos, Wesley L., Dias, Thadeu L. B., Netto, Sergio L. and da Silva, Eduardo A. B.; A Comparative Analysis of Object Detection Metrics with a Companion Open-Source Toolkit, Electronics 2021., https://doi.org/10.3390/electronics10030279Tushar Kolhe; How to boost object detection accuracy by understanding data, https://blog.gofynd.com/boost-object-detection-model-accuracy-552586d698cAdam Kelly; Create COCO Annotations From Scratch, https://www.immersivelimit.com/tutorials/create-coco-annotations-from-scratchKiprono Elijah Koech; Object Detection Metrics With Worked Example https://towardsdatascience.com/on-object-detection-metrics-with-worked-example-216f173ed31eHarshit Kumar; Evaluation metrics for object detection and segmentation - mAP, https://kharshit.github.io/blog/2019/09/20/evaluation-metrics-for-object-detection-and-segmentation" }, { "code": null, "e": 14708, "s": 14576, "text": "Daniel Bolya, Sean Foley, James Hays, and Judy Hoffman; TIDE: A General Toolbox for Identifying Object Detection Errors, ECCV 2020." }, { "code": null, "e": 14962, "s": 14708, "text": "Padilla, Rafael, Passos, Wesley L., Dias, Thadeu L. B., Netto, Sergio L. and da Silva, Eduardo A. B.; A Comparative Analysis of Object Detection Metrics with a Companion Open-Source Toolkit, Electronics 2021., https://doi.org/10.3390/electronics10030279" }, { "code": null, "e": 15112, "s": 14962, "text": "Tushar Kolhe; How to boost object detection accuracy by understanding data, https://blog.gofynd.com/boost-object-detection-model-accuracy-552586d698c" }, { "code": null, "e": 15240, "s": 15112, "text": "Adam Kelly; Create COCO Annotations From Scratch, https://www.immersivelimit.com/tutorials/create-coco-annotations-from-scratch" }, { "code": null, "e": 15399, "s": 15240, "text": "Kiprono Elijah Koech; Object Detection Metrics With Worked Example https://towardsdatascience.com/on-object-detection-metrics-with-worked-example-216f173ed31e" } ]
How do we copy objects in java?
In Java you can copy an object in several ways, among them, copy constructor and the clone method are the mostly used. Generally, the copy constructor is a constructor which creates an object by initializing it with an object of the same class, which has been created previously. Java does support for copy constructors but you need to define them yourself. In the following Java example, we a have a class with two instance variables name and age and a parameterized constructor initializing these variables. Then, we have another constructor which accepts an object of the current class and initializes the instance variables with the variables of this object. If you instantiate this class using the second constructor by passing an object to it, this results an object which is the copy of the one which you passed as an argument. Live Demo import java.util.Scanner; public class Student { private String name; private int age; public Student(String name, int age){ this.name = name; this.age = age; } public Student(Student std){ this.name = std.name; this.age = std.age; } public void displayData(){ System.out.println("Name : "+this.name); System.out.println("Age : "+this.age); } public static void main(String[] args) { Scanner sc =new Scanner(System.in); System.out.println("Enter your name "); String name = sc.next(); System.out.println("Enter your age "); int age = sc.nextInt(); Student std = new Student(name, age); System.out.println("Contents of the original object"); std.displayData(); System.out.println("Contents of the copied object"); Student copyOfStd = new Student(std); copyOfStd.displayData(); } } Enter your name Krishna Enter your age 20 Contents of the original object Name : Krishna Age : 20 Contents of the copied object Name : Krishna Age : 20 The clone() method of the class java.lang.Object accepts an object as a parameter, creates and returns a copy of it. In the following Java example, we a have a class with two instance variables name and age and a parameterized constructor initializing these variables. From the main method we are creating an object of this class and generating a copy of it using the clone() method. Live Demo import java.util.Scanner; public class CloneExample implements Cloneable { private String name; private int age; public CloneExample(String name, int age){ this.name = name; this.age = age; } public void displayData(){ System.out.println("Name : "+this.name); System.out.println("Age : "+this.age); } public static void main(String[] args) throws CloneNotSupportedException { Scanner sc =new Scanner(System.in); System.out.println("Enter your name "); String name = sc.next(); System.out.println("Enter your age "); int age = sc.nextInt(); CloneExample std = new CloneExample(name, age); System.out.println("Contents of the original object"); std.displayData(); System.out.println("Contents of the copied object"); CloneExample copiedStd = (CloneExample) std.clone(); copiedStd.displayData(); } } Enter your name Krishna Enter your age 20 Contents of the original object Name : Krishna Age : 20 Contents of the copied object Name : Krishna Age : 20
[ { "code": null, "e": 1181, "s": 1062, "text": "In Java you can copy an object in several ways, among them, copy constructor and the clone method are the mostly used." }, { "code": null, "e": 1420, "s": 1181, "text": "Generally, the copy constructor is a constructor which creates an object by initializing it with an object of the same class, which has been created previously. Java does support for copy constructors but you need to define them yourself." }, { "code": null, "e": 1572, "s": 1420, "text": "In the following Java example, we a have a class with two instance variables name and age and a parameterized constructor initializing these variables." }, { "code": null, "e": 1725, "s": 1572, "text": "Then, we have another constructor which accepts an object of the current class and initializes the instance variables with the variables of this object." }, { "code": null, "e": 1897, "s": 1725, "text": "If you instantiate this class using the second constructor by passing an object to it, this results an object which is the copy of the one which you passed as an argument." }, { "code": null, "e": 1908, "s": 1897, "text": " Live Demo" }, { "code": null, "e": 2820, "s": 1908, "text": "import java.util.Scanner;\npublic class Student {\n private String name;\n private int age;\n public Student(String name, int age){\n this.name = name;\n this.age = age;\n }\n public Student(Student std){\n this.name = std.name;\n this.age = std.age;\n }\n public void displayData(){\n System.out.println(\"Name : \"+this.name);\n System.out.println(\"Age : \"+this.age);\n }\n public static void main(String[] args) {\n Scanner sc =new Scanner(System.in);\n System.out.println(\"Enter your name \");\n String name = sc.next();\n System.out.println(\"Enter your age \");\n int age = sc.nextInt();\n Student std = new Student(name, age);\n System.out.println(\"Contents of the original object\");\n std.displayData();\n System.out.println(\"Contents of the copied object\");\n Student copyOfStd = new Student(std);\n copyOfStd.displayData();\n }\n}" }, { "code": null, "e": 2972, "s": 2820, "text": "Enter your name\nKrishna\nEnter your age\n20\nContents of the original object\nName : Krishna\nAge : 20\nContents of the copied object\nName : Krishna\nAge : 20" }, { "code": null, "e": 3089, "s": 2972, "text": "The clone() method of the class java.lang.Object accepts an object as a parameter, creates and returns a copy of it." }, { "code": null, "e": 3241, "s": 3089, "text": "In the following Java example, we a have a class with two instance variables name and age and a parameterized constructor initializing these variables." }, { "code": null, "e": 3356, "s": 3241, "text": "From the main method we are creating an object of this class and generating a copy of it using the clone() method." }, { "code": null, "e": 3367, "s": 3356, "text": " Live Demo" }, { "code": null, "e": 4278, "s": 3367, "text": "import java.util.Scanner;\npublic class CloneExample implements Cloneable {\n private String name;\n private int age;\n public CloneExample(String name, int age){\n this.name = name;\n this.age = age;\n }\n public void displayData(){\n System.out.println(\"Name : \"+this.name);\n System.out.println(\"Age : \"+this.age);\n }\n public static void main(String[] args) throws CloneNotSupportedException {\n Scanner sc =new Scanner(System.in);\n System.out.println(\"Enter your name \");\n String name = sc.next();\n System.out.println(\"Enter your age \");\n int age = sc.nextInt();\n CloneExample std = new CloneExample(name, age);\n System.out.println(\"Contents of the original object\");\n std.displayData();\n System.out.println(\"Contents of the copied object\");\n CloneExample copiedStd = (CloneExample) std.clone();\n copiedStd.displayData();\n }\n}" }, { "code": null, "e": 4430, "s": 4278, "text": "Enter your name\nKrishna\nEnter your age\n20\nContents of the original object\nName : Krishna\nAge : 20\nContents of the copied object\nName : Krishna\nAge : 20" } ]
How to raise an exception in Python?
We can force raise an exception using the raise keyword. Here is the syntax for calling the “raise” method. raise [Exception [, args [, traceback]]] where, the Exception is the name of the exception; the optional “args” represents the value of the exception argument. The also optional argument, traceback, is the traceback object used for the exception. #raise_error.py try: i = int ( input ( "Enter a positive integer value: " ) ) if i <= 0: raise ValueError ( "This is not a positive number!!" ) except ValueError as e: print(e) If we execute the above script at terminal as follows $python raise_error.py Enter a positive integer: –6 Following is displayed since we have entered a negative number: This is not a positive number!! Alternate example code # Here there is no variable or argument passed with the raised exception import sys try: i = int ( input("Enter a positive integer value: ")) if i <= 0: raise ValueError#("This is not a positive number!!") except ValueError as e: print sys.exc_info() output Enter a positive integer value: -9 (<type 'exceptions.ValueError'>, ValueError(), <traceback object at 0x0000000003584EC8>)
[ { "code": null, "e": 1170, "s": 1062, "text": "We can force raise an exception using the raise keyword. Here is the syntax for calling the “raise” method." }, { "code": null, "e": 1211, "s": 1170, "text": "raise [Exception [, args [, traceback]]]" }, { "code": null, "e": 1330, "s": 1211, "text": "where, the Exception is the name of the exception; the optional “args” represents the value of the exception argument." }, { "code": null, "e": 1417, "s": 1330, "text": "The also optional argument, traceback, is the traceback object used for the exception." }, { "code": null, "e": 1594, "s": 1417, "text": "#raise_error.py\ntry:\ni = int ( input ( \"Enter a positive integer value: \" ) )\nif i <= 0:\nraise ValueError ( \"This is not a positive number!!\" )\nexcept ValueError as e:\nprint(e)" }, { "code": null, "e": 1648, "s": 1594, "text": "If we execute the above script at terminal as follows" }, { "code": null, "e": 1700, "s": 1648, "text": "$python raise_error.py\nEnter a positive integer: –6" }, { "code": null, "e": 1764, "s": 1700, "text": "Following is displayed since we have entered a negative number:" }, { "code": null, "e": 1796, "s": 1764, "text": "This is not a positive number!!" }, { "code": null, "e": 1819, "s": 1796, "text": "Alternate example code" }, { "code": null, "e": 2070, "s": 1819, "text": "# Here there is no variable or argument passed with the raised exception\nimport sys\ntry:\ni = int ( input(\"Enter a positive integer value: \"))\nif i <= 0:\nraise ValueError#(\"This is not a positive number!!\")\nexcept ValueError as e:\nprint sys.exc_info()" }, { "code": null, "e": 2077, "s": 2070, "text": "output" }, { "code": null, "e": 2202, "s": 2077, "text": "Enter a positive integer value: -9\n(<type 'exceptions.ValueError'>, ValueError(), <traceback object at\n 0x0000000003584EC8>)" } ]
Count duplicates in a given linked list - GeeksforGeeks
21 Jun, 2021 Given a linked list. The task is to count the number of duplicate nodes in the linked list. Examples: Input: 5 -> 7 -> 5 -> 1 -> 7 -> NULL Output: 2Input: 5 -> 7 -> 8 -> 7 -> 1 -> NULL Output: 1 Simple Approach: We traverse the whole linked list. For each node we check in the remaining list whether the duplicate node exists or not. If it does then we increment the count.Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ implementation of the approach#include <iostream>#include <unordered_set>using namespace std; // Representation of nodestruct Node { int data; Node* next;}; // Function to insert a node at the beginningvoid insert(Node** head, int item){ Node* temp = new Node(); temp->data = item; temp->next = *head; *head = temp;} // Function to count the number of// duplicate nodes in the linked listint countNode(Node* head){ int count = 0; while (head->next != NULL) { // Starting from the next node Node *ptr = head->next; while (ptr != NULL) { // If some duplicate node is found if (head->data == ptr->data) { count++; break; } ptr = ptr->next; } head = head->next; } // Return the count of duplicate nodes return count;} // Driver codeint main(){ Node* head = NULL; insert(&head, 5); insert(&head, 7); insert(&head, 5); insert(&head, 1); insert(&head, 7); cout << countNode(head); return 0;} // Java implementation of the approachclass GFG{ // Representation of nodestatic class Node{ int data; Node next;}; // Function to insert a node at the beginningstatic Node insert(Node head, int item){ Node temp = new Node(); temp.data = item; temp.next = head; head = temp; return head;} // Function to count the number of// duplicate nodes in the linked liststatic int countNode(Node head){ int count = 0; while (head.next != null) { // Starting from the next node Node ptr = head.next; while (ptr != null) { // If some duplicate node is found if (head.data == ptr.data) { count++; break; } ptr = ptr.next; } head = head.next; } // Return the count of duplicate nodes return count;} // Driver codepublic static void main(String args[]){ Node head = null; head = insert(head, 5); head = insert(head, 7); head = insert(head, 5); head = insert(head, 1); head = insert(head, 7); System.out.println( countNode(head));}} // This code is contributed by Arnab Kundu # Python3 implementation of the approachimport math # Representation of nodeclass Node: def __init__(self, data): self.data = data self.next = None # Function to push a node at the beginningdef push(head, item): temp = Node(item); temp.data = item; temp.next = head; head = temp; return head; # Function to count the number of# duplicate nodes in the linked listdef countNode(head): count = 0 while (head.next != None): # print(1) # Starting from the next node ptr = head.next while (ptr != None): # print(2) # If some duplicate node is found if (head.data == ptr.data): count = count + 1 break ptr = ptr.next head = head.next # Return the count of duplicate nodes return count # Driver codeif __name__=='__main__': head = None; head = push(head, 5) head = push(head, 7) head = push(head, 5) head = push(head, 1) head = push(head, 7) print(countNode(head)) # This code is contributed by Srathore // C# implementation of the approachusing System; class GFG{ // Representation of nodepublic class Node{ public int data; public Node next;}; // Function to insert a node at the beginningstatic Node insert(Node head, int item){ Node temp = new Node(); temp.data = item; temp.next = head; head = temp; return head;} // Function to count the number of// duplicate nodes in the linked liststatic int countNode(Node head){ int count = 0; while (head.next != null) { // Starting from the next node Node ptr = head.next; while (ptr != null) { // If some duplicate node is found if (head.data == ptr.data) { count++; break; } ptr = ptr.next; } head = head.next; } // Return the count of duplicate nodes return count;} // Driver codepublic static void Main(String []args){ Node head = null; head = insert(head, 5); head = insert(head, 7); head = insert(head, 5); head = insert(head, 1); head = insert(head, 7); Console.WriteLine( countNode(head));}} // This code is contributed by Rajput-Ji <script> // Javascript implementation of the approach // Representation of a nodeclass Node { constructor() { var data; var next; } } // Function to insert a node at the beginningfunction insert( head, item){ var temp = new Node(); temp.data = item; temp.next = head; head = temp; return head;} // Function to count the number of// duplicate nodes in the linked listfunction countNode( head){ let count = 0; while (head.next != null) { // Starting from the next node let ptr = head.next; while (ptr != null) { // If some duplicate node is found if (head.data == ptr.data) { count++; break; } ptr = ptr.next; } head = head.next; } // Return the count of duplicate nodes return count;} // Driver Code var head = null; head = insert(head, 5); head = insert(head, 7); head = insert(head, 5); head = insert(head, 1); head = insert(head, 7); document.write( countNode(head)); // This code is contribute by jana_ayantan.</script> 2 Time Complexity: O(n*n)Efficient Approach: The idea is to use hashing C++ Java Python C# Javascript // C++ implementation of the approach#include <iostream>#include <unordered_set>using namespace std; // Representation of nodestruct Node { int data; Node* next;}; // Function to insert a node at the beginningvoid insert(Node** head, int item){ Node* temp = new Node(); temp->data = item; temp->next = *head; *head = temp;} // Function to count the number of// duplicate nodes in the linked listint countNode(Node* head){ if (head == NULL) return 0;; // Create a hash table insert head unordered_set<int> s; s.insert(head->data); // Traverse through remaining nodes int count = 0; for (Node *curr=head->next; curr != NULL; curr=curr->next) { if (s.find(curr->data) != s.end()) count++; s.insert(curr->data); } // Return the count of duplicate nodes return count;} // Driver codeint main(){ Node* head = NULL; insert(&head, 5); insert(&head, 7); insert(&head, 5); insert(&head, 1); insert(&head, 7); cout << countNode(head); return 0;} // Java implementation of the approachimport java.util.HashSet; class GFG{ // Representation of nodestatic class Node{ int data; Node next;};static Node head; // Function to insert a node at the beginningstatic void insert(Node ref_head, int item){ Node temp = new Node(); temp.data = item; temp.next = ref_head; head = temp; } // Function to count the number of// duplicate nodes in the linked liststatic int countNode(Node head){ if (head == null) return 0;; // Create a hash table insert head HashSet<Integer>s = new HashSet<>(); s.add(head.data); // Traverse through remaining nodes int count = 0; for (Node curr=head.next; curr != null; curr=curr.next) { if (s.contains(curr.data)) count++; s.add(curr.data); } // Return the count of duplicate nodes return count;} // Driver codepublic static void main(String[] args){ insert(head, 5); insert(head, 7); insert(head, 5); insert(head, 1); insert(head, 7); System.out.println(countNode(head));}} // This code is contributed by Princi Singh # Python3 implementation of the approach # Node of a linked listclass Node: def __init__(self, data = None, next = None): self.next = next self.data = data head = None # Function to insert a node at the beginningdef insert(ref_head, item): global head temp = Node() temp.data = item temp.next = ref_head head = temp # Function to count the number of# duplicate nodes in the linked listdef countNode(head): if (head == None): return 0 # Create a hash table insert head s = set() s.add(head.data) # Traverse through remaining nodes count = 0 curr = head.next while ( curr != None ) : if (curr.data in s): count = count + 1 s.add(curr.data) curr = curr.next # Return the count of duplicate nodes return count # Driver codeinsert(head, 5)insert(head, 7)insert(head, 5)insert(head, 1)insert(head, 7) print(countNode(head)) # This code is contributed by Arnab Kundu // C# implementation of the approachusing System;using System.Collections.Generic; class GFG{ // Representation of nodepublic class Node{ public int data; public Node next;};static Node head; // Function to insert a node at the beginningstatic void insert(Node ref_head, int item){ Node temp = new Node(); temp.data = item; temp.next = ref_head; head = temp; } // Function to count the number of// duplicate nodes in the linked liststatic int countNode(Node head){ if (head == null) return 0;; // Create a hash table insert head HashSet<int>s = new HashSet<int>(); s.Add(head.data); // Traverse through remaining nodes int count = 0; for (Node curr=head.next; curr != null; curr=curr.next) { if (s.Contains(curr.data)) count++; s.Add(curr.data); } // Return the count of duplicate nodes return count;} // Driver codepublic static void Main(String[] args){ insert(head, 5); insert(head, 7); insert(head, 5); insert(head, 1); insert(head, 7); Console.WriteLine(countNode(head));}} // This code is contributed by 29AjayKumar <script> // JavaScript implementation of the approach // Representation of nodeclass Node { constructor() { this.data = 0; this.next = null; }}; // Function to insert a node at the beginningfunction insert(head, item){ var temp = new Node(); temp.data = item; temp.next = head; head = temp; return head;} // Function to count the number of// duplicate nodes in the linked listfunction countNode(head){ if (head == null) return 0;; // Create a hash table insert head var s = new Set(); s.add(head.data); // Traverse through remaining nodes var count = 0; for (var curr=head.next; curr != null; curr=curr.next) { if (s.has(curr.data)) count++; s.add(curr.data); } // Return the count of duplicate nodes return count;} // Driver codevar head = null;head = insert(head, 5);head = insert(head, 7);head = insert(head, 5);head = insert(head, 1);head = insert(head, 7);document.write( countNode(head)); </script> 2 Time Complexity : O(n) andrew1234 Rajput-Ji princi singh 29AjayKumar sapnasingh4991 jana_sayantan itsok Traversal Hash Linked List Searching Linked List Searching Hash Traversal Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Quadratic Probing in Hashing Double Hashing Hashing | Set 2 (Separate Chaining) Implementing our Own Hash Table with Separate Chaining in Java Load Factor and Rehashing 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
[ { "code": null, "e": 24789, "s": 24761, "text": "\n21 Jun, 2021" }, { "code": null, "e": 24893, "s": 24789, "text": "Given a linked list. The task is to count the number of duplicate nodes in the linked list. Examples: " }, { "code": null, "e": 24988, "s": 24893, "text": "Input: 5 -> 7 -> 5 -> 1 -> 7 -> NULL Output: 2Input: 5 -> 7 -> 8 -> 7 -> 1 -> NULL Output: 1 " }, { "code": null, "e": 25221, "s": 24990, "text": "Simple Approach: We traverse the whole linked list. For each node we check in the remaining list whether the duplicate node exists or not. If it does then we increment the count.Below is the implementation of the above approach: " }, { "code": null, "e": 25225, "s": 25221, "text": "C++" }, { "code": null, "e": 25230, "s": 25225, "text": "Java" }, { "code": null, "e": 25238, "s": 25230, "text": "Python3" }, { "code": null, "e": 25241, "s": 25238, "text": "C#" }, { "code": null, "e": 25252, "s": 25241, "text": "Javascript" }, { "code": "// C++ implementation of the approach#include <iostream>#include <unordered_set>using namespace std; // Representation of nodestruct Node { int data; Node* next;}; // Function to insert a node at the beginningvoid insert(Node** head, int item){ Node* temp = new Node(); temp->data = item; temp->next = *head; *head = temp;} // Function to count the number of// duplicate nodes in the linked listint countNode(Node* head){ int count = 0; while (head->next != NULL) { // Starting from the next node Node *ptr = head->next; while (ptr != NULL) { // If some duplicate node is found if (head->data == ptr->data) { count++; break; } ptr = ptr->next; } head = head->next; } // Return the count of duplicate nodes return count;} // Driver codeint main(){ Node* head = NULL; insert(&head, 5); insert(&head, 7); insert(&head, 5); insert(&head, 1); insert(&head, 7); cout << countNode(head); return 0;}", "e": 26318, "s": 25252, "text": null }, { "code": "// Java implementation of the approachclass GFG{ // Representation of nodestatic class Node{ int data; Node next;}; // Function to insert a node at the beginningstatic Node insert(Node head, int item){ Node temp = new Node(); temp.data = item; temp.next = head; head = temp; return head;} // Function to count the number of// duplicate nodes in the linked liststatic int countNode(Node head){ int count = 0; while (head.next != null) { // Starting from the next node Node ptr = head.next; while (ptr != null) { // If some duplicate node is found if (head.data == ptr.data) { count++; break; } ptr = ptr.next; } head = head.next; } // Return the count of duplicate nodes return count;} // Driver codepublic static void main(String args[]){ Node head = null; head = insert(head, 5); head = insert(head, 7); head = insert(head, 5); head = insert(head, 1); head = insert(head, 7); System.out.println( countNode(head));}} // This code is contributed by Arnab Kundu", "e": 27476, "s": 26318, "text": null }, { "code": "# Python3 implementation of the approachimport math # Representation of nodeclass Node: def __init__(self, data): self.data = data self.next = None # Function to push a node at the beginningdef push(head, item): temp = Node(item); temp.data = item; temp.next = head; head = temp; return head; # Function to count the number of# duplicate nodes in the linked listdef countNode(head): count = 0 while (head.next != None): # print(1) # Starting from the next node ptr = head.next while (ptr != None): # print(2) # If some duplicate node is found if (head.data == ptr.data): count = count + 1 break ptr = ptr.next head = head.next # Return the count of duplicate nodes return count # Driver codeif __name__=='__main__': head = None; head = push(head, 5) head = push(head, 7) head = push(head, 5) head = push(head, 1) head = push(head, 7) print(countNode(head)) # This code is contributed by Srathore", "e": 28586, "s": 27476, "text": null }, { "code": "// C# implementation of the approachusing System; class GFG{ // Representation of nodepublic class Node{ public int data; public Node next;}; // Function to insert a node at the beginningstatic Node insert(Node head, int item){ Node temp = new Node(); temp.data = item; temp.next = head; head = temp; return head;} // Function to count the number of// duplicate nodes in the linked liststatic int countNode(Node head){ int count = 0; while (head.next != null) { // Starting from the next node Node ptr = head.next; while (ptr != null) { // If some duplicate node is found if (head.data == ptr.data) { count++; break; } ptr = ptr.next; } head = head.next; } // Return the count of duplicate nodes return count;} // Driver codepublic static void Main(String []args){ Node head = null; head = insert(head, 5); head = insert(head, 7); head = insert(head, 5); head = insert(head, 1); head = insert(head, 7); Console.WriteLine( countNode(head));}} // This code is contributed by Rajput-Ji", "e": 29771, "s": 28586, "text": null }, { "code": "<script> // Javascript implementation of the approach // Representation of a nodeclass Node { constructor() { var data; var next; } } // Function to insert a node at the beginningfunction insert( head, item){ var temp = new Node(); temp.data = item; temp.next = head; head = temp; return head;} // Function to count the number of// duplicate nodes in the linked listfunction countNode( head){ let count = 0; while (head.next != null) { // Starting from the next node let ptr = head.next; while (ptr != null) { // If some duplicate node is found if (head.data == ptr.data) { count++; break; } ptr = ptr.next; } head = head.next; } // Return the count of duplicate nodes return count;} // Driver Code var head = null; head = insert(head, 5); head = insert(head, 7); head = insert(head, 5); head = insert(head, 1); head = insert(head, 7); document.write( countNode(head)); // This code is contribute by jana_ayantan.</script>", "e": 30949, "s": 29771, "text": null }, { "code": null, "e": 30951, "s": 30949, "text": "2" }, { "code": null, "e": 31025, "s": 30953, "text": "Time Complexity: O(n*n)Efficient Approach: The idea is to use hashing " }, { "code": null, "e": 31029, "s": 31025, "text": "C++" }, { "code": null, "e": 31034, "s": 31029, "text": "Java" }, { "code": null, "e": 31041, "s": 31034, "text": "Python" }, { "code": null, "e": 31044, "s": 31041, "text": "C#" }, { "code": null, "e": 31055, "s": 31044, "text": "Javascript" }, { "code": "// C++ implementation of the approach#include <iostream>#include <unordered_set>using namespace std; // Representation of nodestruct Node { int data; Node* next;}; // Function to insert a node at the beginningvoid insert(Node** head, int item){ Node* temp = new Node(); temp->data = item; temp->next = *head; *head = temp;} // Function to count the number of// duplicate nodes in the linked listint countNode(Node* head){ if (head == NULL) return 0;; // Create a hash table insert head unordered_set<int> s; s.insert(head->data); // Traverse through remaining nodes int count = 0; for (Node *curr=head->next; curr != NULL; curr=curr->next) { if (s.find(curr->data) != s.end()) count++; s.insert(curr->data); } // Return the count of duplicate nodes return count;} // Driver codeint main(){ Node* head = NULL; insert(&head, 5); insert(&head, 7); insert(&head, 5); insert(&head, 1); insert(&head, 7); cout << countNode(head); return 0;}", "e": 32103, "s": 31055, "text": null }, { "code": "// Java implementation of the approachimport java.util.HashSet; class GFG{ // Representation of nodestatic class Node{ int data; Node next;};static Node head; // Function to insert a node at the beginningstatic void insert(Node ref_head, int item){ Node temp = new Node(); temp.data = item; temp.next = ref_head; head = temp; } // Function to count the number of// duplicate nodes in the linked liststatic int countNode(Node head){ if (head == null) return 0;; // Create a hash table insert head HashSet<Integer>s = new HashSet<>(); s.add(head.data); // Traverse through remaining nodes int count = 0; for (Node curr=head.next; curr != null; curr=curr.next) { if (s.contains(curr.data)) count++; s.add(curr.data); } // Return the count of duplicate nodes return count;} // Driver codepublic static void main(String[] args){ insert(head, 5); insert(head, 7); insert(head, 5); insert(head, 1); insert(head, 7); System.out.println(countNode(head));}} // This code is contributed by Princi Singh", "e": 33202, "s": 32103, "text": null }, { "code": "# Python3 implementation of the approach # Node of a linked listclass Node: def __init__(self, data = None, next = None): self.next = next self.data = data head = None # Function to insert a node at the beginningdef insert(ref_head, item): global head temp = Node() temp.data = item temp.next = ref_head head = temp # Function to count the number of# duplicate nodes in the linked listdef countNode(head): if (head == None): return 0 # Create a hash table insert head s = set() s.add(head.data) # Traverse through remaining nodes count = 0 curr = head.next while ( curr != None ) : if (curr.data in s): count = count + 1 s.add(curr.data) curr = curr.next # Return the count of duplicate nodes return count # Driver codeinsert(head, 5)insert(head, 7)insert(head, 5)insert(head, 1)insert(head, 7) print(countNode(head)) # This code is contributed by Arnab Kundu", "e": 34172, "s": 33202, "text": null }, { "code": "// C# implementation of the approachusing System;using System.Collections.Generic; class GFG{ // Representation of nodepublic class Node{ public int data; public Node next;};static Node head; // Function to insert a node at the beginningstatic void insert(Node ref_head, int item){ Node temp = new Node(); temp.data = item; temp.next = ref_head; head = temp; } // Function to count the number of// duplicate nodes in the linked liststatic int countNode(Node head){ if (head == null) return 0;; // Create a hash table insert head HashSet<int>s = new HashSet<int>(); s.Add(head.data); // Traverse through remaining nodes int count = 0; for (Node curr=head.next; curr != null; curr=curr.next) { if (s.Contains(curr.data)) count++; s.Add(curr.data); } // Return the count of duplicate nodes return count;} // Driver codepublic static void Main(String[] args){ insert(head, 5); insert(head, 7); insert(head, 5); insert(head, 1); insert(head, 7); Console.WriteLine(countNode(head));}} // This code is contributed by 29AjayKumar", "e": 35305, "s": 34172, "text": null }, { "code": "<script> // JavaScript implementation of the approach // Representation of nodeclass Node { constructor() { this.data = 0; this.next = null; }}; // Function to insert a node at the beginningfunction insert(head, item){ var temp = new Node(); temp.data = item; temp.next = head; head = temp; return head;} // Function to count the number of// duplicate nodes in the linked listfunction countNode(head){ if (head == null) return 0;; // Create a hash table insert head var s = new Set(); s.add(head.data); // Traverse through remaining nodes var count = 0; for (var curr=head.next; curr != null; curr=curr.next) { if (s.has(curr.data)) count++; s.add(curr.data); } // Return the count of duplicate nodes return count;} // Driver codevar head = null;head = insert(head, 5);head = insert(head, 7);head = insert(head, 5);head = insert(head, 1);head = insert(head, 7);document.write( countNode(head)); </script>", "e": 36319, "s": 35305, "text": null }, { "code": null, "e": 36321, "s": 36319, "text": "2" }, { "code": null, "e": 36347, "s": 36323, "text": "Time Complexity : O(n) " }, { "code": null, "e": 36358, "s": 36347, "text": "andrew1234" }, { "code": null, "e": 36368, "s": 36358, "text": "Rajput-Ji" }, { "code": null, "e": 36381, "s": 36368, "text": "princi singh" }, { "code": null, "e": 36393, "s": 36381, "text": "29AjayKumar" }, { "code": null, "e": 36408, "s": 36393, "text": "sapnasingh4991" }, { "code": null, "e": 36422, "s": 36408, "text": "jana_sayantan" }, { "code": null, "e": 36428, "s": 36422, "text": "itsok" }, { "code": null, "e": 36438, "s": 36428, "text": "Traversal" }, { "code": null, "e": 36443, "s": 36438, "text": "Hash" }, { "code": null, "e": 36455, "s": 36443, "text": "Linked List" }, { "code": null, "e": 36465, "s": 36455, "text": "Searching" }, { "code": null, "e": 36477, "s": 36465, "text": "Linked List" }, { "code": null, "e": 36487, "s": 36477, "text": "Searching" }, { "code": null, "e": 36492, "s": 36487, "text": "Hash" }, { "code": null, "e": 36502, "s": 36492, "text": "Traversal" }, { "code": null, "e": 36600, "s": 36502, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 36609, "s": 36600, "text": "Comments" }, { "code": null, "e": 36622, "s": 36609, "text": "Old Comments" }, { "code": null, "e": 36651, "s": 36622, "text": "Quadratic Probing in Hashing" }, { "code": null, "e": 36666, "s": 36651, "text": "Double Hashing" }, { "code": null, "e": 36702, "s": 36666, "text": "Hashing | Set 2 (Separate Chaining)" }, { "code": null, "e": 36765, "s": 36702, "text": "Implementing our Own Hash Table with Separate Chaining in Java" }, { "code": null, "e": 36791, "s": 36765, "text": "Load Factor and Rehashing" }, { "code": null, "e": 36826, "s": 36791, "text": "Linked List | Set 1 (Introduction)" }, { "code": null, "e": 36865, "s": 36826, "text": "Linked List | Set 2 (Inserting a node)" }, { "code": null, "e": 36913, "s": 36865, "text": "Stack Data Structure (Introduction and Program)" }, { "code": null, "e": 36951, "s": 36913, "text": "Linked List | Set 3 (Deleting a node)" } ]
Selenium - Quick Guide
Selenium is an open-source and a portable automated software testing tool for testing web applications. It has capabilities to operate across different browsers and operating systems. Selenium is not just a single tool but a set of tools that helps testers to automate web-based applications more efficiently. Let us now understand each one of the tools available in the Selenium suite and their usage. Selenium IDE Selenium Integrated Development Environment (IDE) is a Firefox plugin that lets testers to record their actions as they follow the workflow that they need to test. Selenium RC Selenium Remote Control (RC) was the flagship testing framework that allowed more than simple browser actions and linear execution. It makes use of the full power of programming languages such as Java, C#, PHP, Python, Ruby and PERL to create more complex tests. Selenium WebDriver Selenium WebDriver is the successor to Selenium RC which sends commands directly to the browser and retrieves results. Selenium Grid Selenium Grid is a tool used to run parallel tests across different machines and different browsers simultaneously which results in minimized execution time. QTP and Selenium are the most used tools in the market for software automation testing. Hence it makes sense to compare the pros of Selenium over QTP. Let us now discuss the pitfalls of Selenium over QTP. The Selenium-IDE (Integrated Development Environment) is an easy-to-use Firefox plug-in to develop Selenium test cases. It provides a Graphical User Interface for recording user actions using Firefox which is used to learn and use Selenium, but it can only be used with Firefox browser as other browsers are not supported. However, the recorded scripts can be converted into various programming languages supported by Selenium and the scripts can be executed on other browsers as well. The following table lists the sections that we are going to cover in this chapter. This section deals with how to download and configure Selenium IDE. This section deals with the features available in Selenium IDE. This section deals with how to create IDE tests using recording feature. This section deals with debugging the Selenium IDE script. This section describes how to insert verification points in Selenium IDE. This section deals with how to work with regular expressions using IDE. The Java script that allows users to customize or add new functionality. This section deals with how to execute Selenium IDE scripts on different browsers. In order to develop Selenium RC or WebDriver scripts, users have to ensure that they have the initial configuration done. Setting up the environment involves the following steps. Download and Install Java Download and Configure Eclipse Configure FireBug and FirePath Configure Selenium RC Configure Selenium WebDriver We need to have JDK (Java Development Kit) installed in order to work with Selenium WebDriver/Selenium. Let us see how to download and install Java. Step 1 − Navigate to the UR. https://www.oracle.com/technetwork/java/javase/downloads/index.html Step 2 − Go to "Downloads" section and select "JDK Download". Step 3 − Select "Accept License Agreement" radio button. Step 4 − Select the appropriate installation. In this case, it is 'Windows 7-64' bit. Click the appropriate link and save the .exe file to your disk. Step 5 − Run the downloaded exe file to launch the Installer wizard. Click 'Next' to continue. Step 6 − Select the features and click 'Next'. Step 7 − The installer is extracted and its progress is shown in the wizard. Step 8 − The user can choose the install location and click 'Next'. Step 9 − The installer installs the JDK and new files are copied across. Step 10 − The Installer installs successfully and displays the same to the user. Step 11 − To verify if the installation was successful, go to the command prompt and just type 'java' as a command. The output of the command is shown below. If the Java installation is unsuccessful or if it had NOT been installed, it would throw an "unknown command" error. Step 1 − Navigate to the URL: https://www.eclipse.org/downloads/ and download the appropriate file based on your OS architecture. Step 2 − Click the 'Download' button. Step 3 − The download would be in a Zipped format. Unzip the contents. Step 4 − Locate Eclipse.exe and double click on the file. Step 5 − To configure the workspace, select the location where the development has to take place. Step 6 − The Eclipse window opens as shown below. To work with Selenium RC or WebDriver, we need to locate elements based on their XPath or ID or name, etc. In order to locate an element, we need tools/plugins. Step 1 − Navigate to the URL : https://addons.mozilla.org/en-US/firefox/addon/firebug/ and download plugin. Step 2 − The add-on installer is shown to the user and it is installed upon clicking the 'Install' button. Step 3 − After installing, we can launch the plugin by navigating to "Web Developer" >> "Firebug". Step 4 − FirePath, a plugin that works within Firebug, helps users to grab the 'XPath' of an element. Install FirePath by navigating to "https://addons.mozilla.org/en-US/firefox/addon/firepath/" Step 5 − The add-on installer is shown to the user and it is installed upon clicking the 'Install' button. Step 6 − Now launch "Firebug" by navigating to "Tools" >> "Webdeveloper" >> "Firebug". Now let us understand how to use FireBug and FirePath with an example. For demonstration, we will use www.google.com and capture the properties of the text box of "google.com". Step 1 − First click on the arrow icon as highlighted in the following screenshot and drag it to the object for which we would like to capture the properties. The HTML/DOM of the object would be displayed as shown below. We are able to capture the 'ID' of the input text box with which we can interact. Step 2 − To fetch the XPath of the object, go to 'firepath' tab and perform the following steps. Click the Spy icon. Select the Control for which we would like to capture the XPath. XPath of the selected control would be generated. Now let us look at how to configure Selenium Remote control. We will understand how to develop scripts with Selenium RC in later chapters, however for now, we will understand just the configuration part of it. Step 1 − Navigate to the Selenium downloads section http://www.seleniumhq.org/download/ and download Selenium Server by clicking on its version number as shown below. Step 2 − After downloading, we need to start the Selenium Server. To do so, open command prompt and navigate to the folder where the downloaded JAR file is kept as shown below. Step 3 − To start the server, use the command 'java -jar <<downloaded jar name >> and if java JDK is installed properly, you would get a success message as shown below. Now we can start writing Selenium RC scripts. Now let us look at how to configure Selenium WebDriver. We will understand how to develop scripts with Selenium WebDriver in later chapters, however for now, we will understand just the configuration part of it. Step 1 − Navigate to the selenium downloads section http://www.seleniumhq.org/download/ and download Selenium WebDriver by clicking on its version number as shown below. Step 2 − The downloaded file is in Zipped format and one has to unzip the contents to map it to the project folder. Step 3 − The Unzipped contents would be displayed as shown below. How to map it to the project folder and how to start scripting would be dealt in the webDriver chapter. Selenium Remote Control (RC) was the main Selenium project that sustained for a long time before Selenium WebDriver(Selenium 2.0) came into existence. Now Selenium RC is hardly in use, as WebDriver offers more powerful features, however users can still continue to develop scripts using RC. It allows us to write automated web application UI tests with the help of full power of programming languages such as Java, C#, Perl, Python and PHP to create more complex tests such as reading and writing files, querying a database, and emailing test results. Selenium RC works in such a way that the client libraries can communicate with the Selenium RC Server passing each Selenium command for execution. Then the server passes the Selenium command to the browser using Selenium-Core JavaScript commands. The browser executes the Selenium command using its JavaScript interpreter. Selenium RC comes in two parts. The Selenium Server launches and kills browsers. In addition to that, it interprets and executes the Selenese commands. It also acts as an HTTP proxy by intercepting and verifying HTTP messages passed between the browser and the application under test. The Selenium Server launches and kills browsers. In addition to that, it interprets and executes the Selenese commands. It also acts as an HTTP proxy by intercepting and verifying HTTP messages passed between the browser and the application under test. Client libraries that provide an interface between each one of the programming languages (Java, C#, Perl, Python and PHP) and the Selenium-RC Server. Client libraries that provide an interface between each one of the programming languages (Java, C#, Perl, Python and PHP) and the Selenium-RC Server. Now let us write a sample script using Selenium Remote Control. Let us use http://www.calculator.net/ for understanding Selenium RC. We will perform a Percent calculation using 'Percent Calculator' that is present under the 'Math Calculators' module. Step 1 − Start Selenium Remote Control (with the help of command prompt). Step 2 − After launching Selenium RC, open Eclipse and create a "New Project" as shown below. Step 3 − Enter the project name and click 'Next' button. Step 4 − Verify the Source, Projects, Libraries, and Output folder and click 'Finish'. Step 5 − Right click on 'project' container and choose 'Configure Build Path'. Step 6 − Properties for 'selrcdemo' opens up. Navigate to 'Libraries' tab and select 'Add External JARs'. Choose the Selenium RC jar file that we have downloaded and it would appear as shown below. Step 7 − The referenced Libraries are shown as displayed below. Step 8 − Create a new class file by performing a right click on 'src' folder and select 'New' >> 'class'. Step 9 − Enter a name of the class file and enable 'public static void main' as shown below. Step 10 − The Created Class is created under the folder structure as shown below. Step 11 − Now it is time for coding. The following code has comments embedded in it to make the readers understand what has been put forth. package selrcdemo; import com.thoughtworks.selenium.DefaultSelenium; import com.thoughtworks.selenium.Selenium; public class rcdemo { public static void main(String[] args) throws InterruptedException { // Instatiate the RC Server Selenium selenium = new DefaultSelenium("localhost", 4444 , "firefox", "http://www.calculator.net"); selenium.start(); // Start selenium.open("/"); // Open the URL selenium.windowMaximize(); // Click on Link Math Calculator selenium.click("xpath = .//*[@id = 'menu']/div[3]/a"); Thread.sleep(2500); // Wait for page load // Click on Link Percent Calculator selenium.click("xpath = .//*[@id = 'menu']/div[4]/div[3]/a"); Thread.sleep(4000); // Wait for page load // Focus on text Box selenium.focus("name = cpar1"); // enter a value in Text box 1 selenium.type("css=input[name = \"cpar1\"]", "10"); // enter a value in Text box 2 selenium.focus("name = cpar2"); selenium.type("css = input[name = \"cpar2\"]", "50"); // Click Calculate button selenium.click("xpath = .//*[@id = 'content']/table/tbody/tr/td[2]/input"); // verify if the result is 5 String result = selenium.getText(".//*[@id = 'content']/p[2]"); if (result == "5") { System.out.println("Pass"); } else { System.out.println("Fail"); } } } Step 12 − Now, let us execute the script by clicking 'Run' Button. Step 13 − The script would start executing and user would be able to see the command history under 'Command History' Tab. Step 14 − The final state of the application is shown as below. The percentage is calculated and it displayed the result on screen as shown below. Step 15 − The output of the test is printed on the Eclipse console as shown below as we have printed the output to the console. In real time the output is written to an HTML file or in a simple Text file. A command refers to what Selenium has to do and commands in selenium are of three types. Click on each one of them to know more about the commands. Actions Actions Accessors Accessors Assertions Assertions Element Locators help Selenium to identify the HTML element the command refers to. All these locators can be identified with the help of FirePath and FireBug plugin of Mozilla. Please refer the Environment Setup chapter for details. identifier = id Select the element with the specified "id" attribute and if there is no match, select the first element whose @name attribute is id. identifier = id Select the element with the specified "id" attribute and if there is no match, select the first element whose @name attribute is id. id = id Select the element with the specified "id" attribute. id = id Select the element with the specified "id" attribute. name = name Select the first element with the specified "name" attribute name = name Select the first element with the specified "name" attribute dom = javascriptExpression Selenium finds an element by evaluating the specified string that allows us to traverse through the HTML Document Object Model using JavaScript. Users cannot return a value but can evaluate as an expression in the block. dom = javascriptExpression Selenium finds an element by evaluating the specified string that allows us to traverse through the HTML Document Object Model using JavaScript. Users cannot return a value but can evaluate as an expression in the block. xpath = xpathExpression Locate an element using an XPath expression. xpath = xpathExpression Locate an element using an XPath expression. link = textPattern Select the link element (within anchor tags) which contains text matching the specified pattern. link = textPattern Select the link element (within anchor tags) which contains text matching the specified pattern. css = cssSelectorSyntax Select the element using css selector. css = cssSelectorSyntax Select the element using css selector. WebDriver is a tool for automating testing web applications. It is popularly known as Selenium 2.0. WebDriver uses a different underlying framework, while Selenium RC uses JavaScript Selenium-Core embedded within the browser which has got some limitations. WebDriver interacts directly with the browser without any intermediary, unlike Selenium RC that depends on a server. It is used in the following context − Multi-browser testing including improved functionality for browsers which is not well-supported by Selenium RC (Selenium 1.0). Multi-browser testing including improved functionality for browsers which is not well-supported by Selenium RC (Selenium 1.0). Handling multiple frames, multiple browser windows, popups, and alerts. Handling multiple frames, multiple browser windows, popups, and alerts. Complex page navigation. Complex page navigation. Advanced user navigation such as drag-and-drop. Advanced user navigation such as drag-and-drop. AJAX-based UI elements. AJAX-based UI elements. WebDriver is best explained with a simple architecture diagram as shown below. Let us understand how to work with WebDriver. For demonstration, we would use https://www.calculator.net/. We will perform a "Percent Calculator" which is located under "Math Calculator". We have already downloaded the required WebDriver JAR's. Refer the chapter "Environmental Setup" for details. Step 1 − Launch "Eclipse" from the Extracted Eclipse folder. Step 2 − Select the Workspace by clicking the 'Browse' button. Step 3 − Now create a 'New Project' from 'File' menu. Step 4 − Enter the Project Name and Click 'Next'. Step 5 − Go to Libraries Tab and select all the JAR's that we have downloaded. Add reference to all the JAR's of Selenium WebDriver Library folder and also selenium-java-2.42.2.jar and selenium-java-2.42.2-srcs.jar. Step 6 − The Package is created as shown below. Step 7 − Now right-click on the package and select 'New' >> 'Class' to create a 'class'. Step 8 − Now name the class and make it the main function. Step 9 − The class outline is shown as below. Step 10 − Now it is time to code. The following script is easier to understand, as it has comments embedded in it to explain the steps clearly. Please take a look at the chapter "Locators" to understand how to capture object properties. import java.util.concurrent.TimeUnit; import org.openqa.selenium.*; import org.openqa.selenium.firefox.FirefoxDriver; public class webdriverdemo { public static void main(String[] args) { WebDriver driver = new FirefoxDriver(); //Puts an Implicit wait, Will wait for 10 seconds before throwing exception driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS); //Launch website driver.navigate().to("http://www.calculator.net/"); //Maximize the browser driver.manage().window().maximize(); // Click on Math Calculators driver.findElement(By.xpath(".//*[@id = 'menu']/div[3]/a")).click(); // Click on Percent Calculators driver.findElement(By.xpath(".//*[@id = 'menu']/div[4]/div[3]/a")).click(); // Enter value 10 in the first number of the percent Calculator driver.findElement(By.id("cpar1")).sendKeys("10"); // Enter value 50 in the second number of the percent Calculator driver.findElement(By.id("cpar2")).sendKeys("50"); // Click Calculate Button driver.findElement(By.xpath(".//*[@id = 'content']/table/tbody/tr[2]/td/input[2]")).click(); // Get the Result Text based on its xpath String result = driver.findElement(By.xpath(".//*[@id = 'content']/p[2]/font/b")).getText(); // Print a Log In message to the screen System.out.println(" The Result is " + result); //Close the Browser. driver.close(); } } Step 11 − The output of the above script would be printed in Console. The following table lists some of the most frequently used commands in WebDriver along with their syntax. driver.get("URL") To navigate to an application. element.sendKeys("inputtext") Enter some text into an input box. element.clear() Clear the contents from the input box. select.deselectAll() Deselect all OPTIONs from the first SELECT on the page. select.selectByVisibleText("some text") Select the OPTION with the input specified by the user. driver.switchTo().window("windowName") Move the focus from one window to another. driver.switchTo().frame("frameName") Swing from frame to frame. driver.switchTo().alert() Helps in handling alerts. driver.navigate().to("URL") Navigate to the URL. driver.navigate().forward() To navigate forward. driver.navigate().back() To navigate back. driver.close() Closes the current browser associated with the driver. driver.quit() Quits the driver and closes all the associated window of that driver. driver.refresh() Refreshes the current page. Locating elements in Selenium WebDriver is performed with the help of findElement() and findElements() methods provided by WebDriver and WebElement class. findElement() returns a WebElement object based on a specified search criteria or ends up throwing an exception if it does not find any element matching the search criteria. findElement() returns a WebElement object based on a specified search criteria or ends up throwing an exception if it does not find any element matching the search criteria. findElements() returns a list of WebElements matching the search criteria. If no elements are found, it returns an empty list. findElements() returns a list of WebElements matching the search criteria. If no elements are found, it returns an empty list. The following table lists all the Java syntax for locating elements in Selenium WebDriver. Now let us understand the practical usage of each of the locator methods with the help of https://www.calculator.net Here an object is accessed with the help of IDs. In this case, it is the ID of the text box. Values are entered into the text box using the sendkeys method with the help of ID(cdensity). driver.findElement(By.id("cdensity")).sendKeys("10"); Here an object is accessed with the help of names. In this case, it is the name of the text box. Values are entered into the text box using the sendkeys method with the help of ID(cdensity). driver.findElement(By.name("cdensity")).sendKeys("10"); Here an object is accessed with the help of Class Names. In this case, it is the Class name of the WebElement. The Value can be accessed with the help of the gettext method. List<WebElement> byclass = driver.findElements(By.className("smalltext smtb")); The DOM Tag Name of an element can be used to locate that particular element in the WebDriver. It is very easy to handle tables with the help of this method. Take a look at the following code. WebElement table = driver.findElement(By.id("calctable")); List<WebElement> row = table.findElements(By.tagName("tr")); int rowcount = row.size(); This method helps to locate a link element with matching visible text. driver.findElements(By.linkText("Volume")).click(); This methods helps locate a link element with partial matching visible text. driver.findElement(By.partialLinkText("Volume")).click(); The CSS is used as a method to identify the webobject, however NOT all browsers support CSS identification. WebElement loginButton = driver.findElement(By.cssSelector("input.login")); XPath stands for XML path language. It is a query language for selecting nodes from an XML document. XPath is based on the tree representation of XML documents and provides the ability to navigate around the tree by selecting nodes using a variety of criteria. driver.findElement(By.xpath(".//*[@id = 'content']/table[1]/tbody/tr/td/table/tbody/tr[2]/td[1]/input")).sendkeys("100"); Selenium WebDriver is the most frequently used tool among all the tools available in the Selenium tool set. Therefore it is important to understand how to use Selenium to interact with web apps. In this module, let us understand how to interact with GUI objects using Selenium webDriver. We need to interact with the application using some basic actions or even some advanced user action by developing user-defined functions for which there are no predefined commands. Listed below are the different kinds of actions against those GUI objects − Text Box Interaction Text Box Interaction Radio Button Selection Radio Button Selection Check Box Selection Check Box Selection Drop Down Item Selection Drop Down Item Selection Synchronization Synchronization Drag & Drop Drag & Drop Keyboard Actions Keyboard Actions Mouse Actions Mouse Actions Multi Select Multi Select Find All Links Find All Links There are various components involved in designing the tests. Let us understand some of the important components involved in designing a framework as well. We will learn the following topics in this chapter − Page Object Model Page Object Model Parameterizing using Excel Parameterizing using Excel Log4j Logging Log4j Logging Exception Handling Exception Handling Multi Browser Testing Multi Browser Testing Capture Screenshots Capture Screenshots Capture Videos Capture Videos TestNG is a powerful testing framework, an enhanced version of JUnit which was in use for a long time before TestNG came into existence. NG stands for 'Next Generation'. TestNG framework provides the following features − Annotations help us organize the tests easily. Flexible test configuration. Test cases can be grouped more easily. Parallelization of tests can be achieved using TestNG. Support for data-driven testing. Inbuilt reporting. Step 1 − Launch Eclipse and select 'Install New Software'. Step 2 − Enter the URL as 'http://beust.com/eclipse' and click 'Add'. Step 3 − The dialog box 'Add Repository' opens. Enter the name as 'TestNG' and click 'OK' Step 4 − Click 'Select All' and 'TestNG' would be selected as shown in the figure. Step 5 − Click 'Next' to continue. Step 6 − Review the items that are selected and click 'Next'. Step 7 − "Accept the License Agreement" and click 'Finish'. Step 8 − TestNG starts installing and the progress would be shown follows. Step 9 − Security Warning pops up as the validity of the software cannot be established. Click 'Ok'. Step 10 − The Installer prompts to restart Eclipse for the changes to take effect. Click 'Yes'. Annotations were formally added to the Java language in JDK 5 and TestNG made the choice to use annotations to annotate test classes. Following are some of the benefits of using annotations. More about TestNG can be found here TestNG identifies the methods it is interested in by looking up annotations. Hence, method names are not restricted to any pattern or format. TestNG identifies the methods it is interested in by looking up annotations. Hence, method names are not restricted to any pattern or format. We can pass additional parameters to annotations. We can pass additional parameters to annotations. Annotations are strongly typed, so the compiler will flag any mistakes right away. Annotations are strongly typed, so the compiler will flag any mistakes right away. Test classes no longer need to extend anything (such as TestCase, for JUnit 3). Test classes no longer need to extend anything (such as TestCase, for JUnit 3). @BeforeSuite The annotated method will be run only once before all the tests in this suite have run. @AfterSuite The annotated method will be run only once after all the tests in this suite have run. @BeforeClass The annotated method will be run only once before the first test method in the current class is invoked. @AfterClass The annotated method will be run only once after all the test methods in the current class have run. @BeforeTest The annotated method will be run before any test method belonging to the classes inside the <test> tag is run. @AfterTest The annotated method will be run after all the test methods belonging to the classes inside the <test> tag have run. @BeforeGroups The list of groups that this configuration method will run before. This method is guaranteed to run shortly before the first test method that belongs to any of these groups is invoked. @AfterGroups The list of groups that this configuration method will run after. This method is guaranteed to run shortly after the last test method that belongs to any of these groups is invoked. @BeforeMethod The annotated method will be run before each test method. @AfterMethod The annotated method will be run after each test method. @DataProvider Marks a method as supplying data for a test method. The annotated method must return an Object[ ][ ] where each Object[ ] can be assigned the parameter list of the test method. The @Test method that wants to receive data from this DataProvider needs to use a dataProvider name equals to the name of this annotation. @Factory Marks a method as a factory that returns objects that will be used by TestNG as Test classes. The method must return Object[ ]. @Listeners Defines listeners on a test class. @Parameters Describes how to pass parameters to a @Test method. @Test Marks a class or a method as part of the test. Step 1 − Launch Eclipse and create a 'New Java Project' as shown below. Step 2 − Enter the project name and click 'Next'. Step 3 − Navigate to "Libraries" Tab and Add the Selenium Remote Control Server JAR file by clicking on "Add External JAR's" as shown below. Step 4 − The added JAR file is shown here. Click 'Add Library'. Step 5 − The 'Add Library' dialog opens. Select 'TestNG' and click 'Next' in the 'Add Library' dialog box. Step 6 − The added 'TestNG' Library is added and it is displayed as shown below. Step 7 − Upon creating the project, the structure of the project would be as shown below. Step 8 − Right-click on 'src' folder and select New >> Other. Step 9 − Select 'TestNG' and click 'Next'. Step 10 − Select the 'Source Folder' name and click 'Ok'. Step 11 − Select the 'Package name', the 'class name', and click 'Finish'. Step 12 − The Package explorer and the created class would be displayed. Now let us start scripting using TestNG. Let us script for the same example that we used for understanding the WebDriver. We will use the demo application, www.calculator.net, and perform percent calculator. In the following test, you will notice that there is NO main method, as testNG will drive the program execution flow. After initializing the driver, it will execute the '@BeforeTest' method followed by '@Test' and then '@AfterTest'. Please note that there can be any number of '@Test' annotation in a class but '@BeforeTest' and '@AfterTest' can appear only once. package TestNG; import java.util.concurrent.TimeUnit; import org.openqa.selenium.*; import org.openqa.selenium.firefox.FirefoxDriver; import org.testng.annotations.AfterTest; import org.testng.annotations.BeforeTest; import org.testng.annotations.Test; public class TestNGClass { WebDriver driver = new FirefoxDriver(); @BeforeTest public void launchapp() { // Puts an Implicit wait, Will wait for 10 seconds before throwing exception driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS); // Launch website driver.navigate().to("http://www.calculator.net"); driver.manage().window().maximize(); } @Test public void calculatepercent() { // Click on Math Calculators driver.findElement(By.xpath(".//*[@id='menu']/div[3]/a")).click(); // Click on Percent Calculators driver.findElement(By.xpath(".//*[@id='menu']/div[4]/div[3]/a")).click(); // Enter value 10 in the first number of the percent Calculator driver.findElement(By.id("cpar1")).sendKeys("10"); // Enter value 50 in the second number of the percent Calculator driver.findElement(By.id("cpar2")).sendKeys("50"); // Click Calculate Button driver.findElement(By.xpath(".//*[@id='content']/table/tbody/tr/td[2]/input")).click(); // Get the Result Text based on its xpath String result = driver.findElement(By.xpath(".//*[@id='content']/p[2]/span/font/b")).getText(); // Print a Log In message to the screen System.out.println(" The Result is " + result); if(result.equals("5")) { System.out.println(" The Result is Pass"); } else { System.out.println(" The Result is Fail"); } } @AfterTest public void terminatetest() { driver.close(); } } To execute, right click on the created XML and select "Run As" >> "TestNG Suite" The output is thrown to the console and it would appear as shown below. The console output also has an execution summary. The result of TestNG can also be seen in a different tab. Click on 'HTML Report View' button as shown below. The HTML result would be displayed as shown below. Selenium Grid is a tool that distributes the tests across multiple physical or virtual machines so that we can execute scripts in parallel (simultaneously). It dramatically accelerates the testing process across browsers and across platforms by giving us quick and accurate feedback. Selenium Grid allows us to execute multiple instances of WebDriver or Selenium Remote Control tests in parallel which uses the same code base, hence the code need NOT be present on the system they execute. The selenium-server-standalone package includes Hub, WebDriver, and Selenium RC to execute the scripts in grid. Selenium Grid has a Hub and a Node. Hub − The hub can also be understood as a server which acts as the central point where the tests would be triggered. A Selenium Grid has only one Hub and it is launched on a single machine once. Hub − The hub can also be understood as a server which acts as the central point where the tests would be triggered. A Selenium Grid has only one Hub and it is launched on a single machine once. Node − Nodes are the Selenium instances that are attached to the Hub which execute the tests. There can be one or more nodes in a grid which can be of any OS and can contain any of the Selenium supported browsers. Node − Nodes are the Selenium instances that are attached to the Hub which execute the tests. There can be one or more nodes in a grid which can be of any OS and can contain any of the Selenium supported browsers. The following diagram shows the architecture of Selenium Grid. In order to work with the Grid, we need to follow certain protocols. Listen below are the major steps involved in this process − Configuring the Hub Configuring the Nodes Develop the Script and Prepare the XML File Test Execution Result Analysis Let us discuss each of these steps in detail. Step 1 − Download the latest Selenium Server standalone JAR file from http://docs.seleniumhq.org/download/. Download it by clicking on the version as shown below. Step 2 − Start the Hub by launching the Selenium Server using the following command. Now we will use the port '4444' to start the hub. Note − Ensure that there are no other applications that are running on port# 4444. java -jar selenium-server-standalone-2.25.0.jar -port 4444 -role hub -nodeTimeout 1000 Step 3 − Now open the browser and navigate to the URL http//localhost:4444 from the Hub (The system where you have executed Step#2). Step 4 − Now click on the 'console' link and click 'view config'. The config of the hub would be displayed as follows. As of now, we haven't got any nodes, hence we will not be able to see the details. Step 1 − Logon to the node (where you would like to execute the scripts) and place the 'selenium-server-standalone-2.42.2' in a folder. We need to point to the selenium-server-standalone JAR while launching the nodes. Step 2 − Launch FireFox Node using the following below command. java -jar D:\JAR\selenium-server-standalone-2.42.2.jar -role node -hub http://10.30.217.157:4444/grid/register -browser browserName = firefox -port 5555 Where, D:\JAR\selenium-server-standalone-2.42.2.jar = Location of the Selenium Server Standalone Jar File(on the Node Machine) http://10.30.217.157:4444 = IP Address of the Hub and 4444 is the port of the Hub browserName = firefox (Parameter to specify the Browser name on Nodes) 5555 = Port on which Firefox Node would be up and running. Step 3 − After executing the command, come back to the Hub. Navigate to the URL - http://10.30.217.157:4444 and the Hub would now display the node attached to it. Step 4 − Now let us launch the Internet Explorer Node. For launching the IE Node, we need to have the Internet Explorer driver downloaded on the node machine. Step 5 − To download the Internet Explorer driver, navigate to http://docs.seleniumhq.org/download/ and download the appropriate file based on the architecture of your OS. After you have downloaded, unzip the exe file and place in it a folder which has to be referred while launching IE nodes. Step 6 − Launch IE using the following command. C:\>java -Dwebdriver.ie.driver = D:\IEDriverServer.exe -jar D:\JAR\selenium-server-standalone-2.42.2.jar -role webdriver -hub http://10.30.217.157:4444/grid/register -browser browserName = ie,platform = WINDOWS -port 5558 Where, D:\IEDriverServer.exe = The location of the downloaded the IE Driver(on the Node Machine) D:\JAR\selenium-server-standalone-2.42.2.jar = Location of the Selenium Server Standalone Jar File(on the Node Machine) http://10.30.217.157:4444 = IP Address of the Hub and 4444 is the port of the Hub browserName = ie (Parameter to specify the Browser name on Nodes) 5558 = Port on which IE Node would be up and running. Step 7 − After executing the command, come back to the Hub. Navigate to the URL - http://10.30.217.157:4444 and the Hub would now display the IE node attached to it. Step 8 − Let us now launch Chrome Node. For launching the Chrome Node, we need to have the Chrome driver downloaded on the node machine. Step 9 − To download the Chrome Driver, navigate to http://docs.seleniumhq.org/download/ and then navigate to Third Party Browser Drivers area and click on the version number '2.10' as shown below. Step 10 − Download the driver based on the type of your OS. We will execute it on Windows environment, hence we will download the Windows Chrome Driver. After you have downloaded, unzip the exe file and place it in a folder which has to be referred while launching chrome nodes. Step 11 − Launch Chrome using the following command. C:\>java -Dwebdriver.chrome.driver = D:\chromedriver.exe -jar D:\JAR\selenium-server-standalone-2.42.2.jar -role webdriver -hub http://10.30.217.157:4444/grid/register -browser browserName = chrome, platform = WINDOWS -port 5557 Where, D:\chromedriver.exe = The location of the downloaded the chrome Driver(on the Node Machine) D:\JAR\selenium-server-standalone-2.42.2.jar = Location of the Selenium Server Standalone Jar File(on the Node Machine) http://10.30.217.157:4444 = IP Address of the Hub and 4444 is the port of the Hub browserName = chrome (Parameter to specify the Browser name on Nodes) 5557 = Port on which chrome Node would be up and running. Step 12 − After executing the command, come back to the Hub. Navigate to the URL - http://10.30.217.157:4444 and the Hub would now display the chrome node attached to it. Step 1 − We will develop a test using TestNG. In the following example, we will launch each one of those browsers using remote webDriver. It can pass on their capabilities to the driver so that the driver has all information to execute on Nodes. The Browser Parameter would be passed from the "XML" file. package TestNG; import org.openqa.selenium.*; import org.openqa.selenium.remote.RemoteWebDriver; import org.openqa.selenium.remote.DesiredCapabilities; import org.testng.annotations.AfterTest; import org.testng.annotations.BeforeTest; import org.testng.annotations.Parameters; import org.testng.annotations.Test; import java.net.URL; import java.util.concurrent.TimeUnit; import java.net.MalformedURLException; public class TestNGClass { public WebDriver driver; public String URL, Node; protected ThreadLocal<RemoteWebDriver> threadDriver = null; @Parameters("browser") @BeforeTest public void launchapp(String browser) throws MalformedURLException { String URL = "http://www.calculator.net"; if (browser.equalsIgnoreCase("firefox")) { System.out.println(" Executing on FireFox"); String Node = "http://10.112.66.52:5555/wd/hub"; DesiredCapabilities cap = DesiredCapabilities.firefox(); cap.setBrowserName("firefox"); driver = new RemoteWebDriver(new URL(Node), cap); // Puts an Implicit wait, Will wait for 10 seconds before throwing exception driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS); // Launch website driver.navigate().to(URL); driver.manage().window().maximize(); } else if (browser.equalsIgnoreCase("chrome")) { System.out.println(" Executing on CHROME"); DesiredCapabilities cap = DesiredCapabilities.chrome(); cap.setBrowserName("chrome"); String Node = "http://10.112.66.52:5557/wd/hub"; driver = new RemoteWebDriver(new URL(Node), cap); driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS); // Launch website driver.navigate().to(URL); driver.manage().window().maximize(); } else if (browser.equalsIgnoreCase("ie")) { System.out.println(" Executing on IE"); DesiredCapabilities cap = DesiredCapabilities.chrome(); cap.setBrowserName("ie"); String Node = "http://10.112.66.52:5558/wd/hub"; driver = new RemoteWebDriver(new URL(Node), cap); driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS); // Launch website driver.navigate().to(URL); driver.manage().window().maximize(); } else { throw new IllegalArgumentException("The Browser Type is Undefined"); } } @Test public void calculatepercent() { // Click on Math Calculators driver.findElement(By.xpath(".//*[@id = 'menu']/div[3]/a")).click(); // Click on Percent Calculators driver.findElement(By.xpath(".//*[@id = 'menu']/div[4]/div[3]/a")).click(); // Enter value 10 in the first number of the percent Calculator driver.findElement(By.id("cpar1")).sendKeys("10"); // Enter value 50 in the second number of the percent Calculator driver.findElement(By.id("cpar2")).sendKeys("50"); // Click Calculate Button // driver.findElement(By.xpath(".//*[@id = 'content']/table/tbody/tr/td[2]/input")).click(); // Get the Result Text based on its xpath String result = driver.findElement(By.xpath(".//*[@id = 'content']/p[2]/span/font/b")).getText(); // Print a Log In message to the screen System.out.println(" The Result is " + result); if(result.equals("5")) { System.out.println(" The Result is Pass"); } else { System.out.println(" The Result is Fail"); } } @AfterTest public void closeBrowser() { driver.quit(); } } Step 2 − The Browser parameter will be passed using XML. Create an XML under the project folder. Step 3 − Select 'File' from 'General' and click 'Next'. Step 4 − Enter the name of the file and click 'Finish'. Step 5 − TestNg.XML is created under the project folder as shown below. Step 6 − The contents of the XML file are shown below. We create 3 tests and put them in a suite and mention parallel="tests" so that all the tests would be executed in parallel. <?xml version = "1.0" encoding = "UTF-8"?> <!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd"> <suite name = "Suite" parallel = "tests"> <test name = "FirefoxTest"> <parameter name = "browser" value = "firefox" /> <classes> <class name = "TestNG.TestNGClass" /> </classes> </test> <test name = "ChromeTest"> <parameter name = "browser" value = "chrome" /> <classes> <class name = "TestNG.TestNGClass" /> </classes> </test> <test name = "IETest"> <parameter name = "browser" value = "ie" /> <classes> <class name = "TestNG.TestNGClass" /> </classes> </test> </suite> Step 1 − Select the created XML; right-click and choose 'Run As' >> 'TestNG Suite'. Step 2 − Now open the Node, where we have launched all the browser nodes. You will see all the three browsers in execution simultaneously. Step 1 − Upon completing the execution, we can analyze the result like any other execution. The result summary is printed in the console as shown in the following snapshot. Step 2 − Navigate to the 'Results of Running Suite' Tab and TestNG would display the result summary as shown below. Step 3 − Upon generating the HTML, we will be able to see the test results in HTML format. 46 Lectures 5.5 hours Aditya Dua 296 Lectures 146 hours Arun Motoori 411 Lectures 38.5 hours In28Minutes Official 22 Lectures 7 hours Arun Motoori 118 Lectures 17 hours Arun Motoori 278 Lectures 38.5 hours Lets Kode It Print Add Notes Bookmark this page
[ { "code": null, "e": 2185, "s": 1875, "text": "Selenium is an open-source and a portable automated software testing tool for testing web applications. It has capabilities to operate across different browsers and operating systems. Selenium is not just a single tool but a set of tools that helps testers to automate web-based applications more efficiently." }, { "code": null, "e": 2278, "s": 2185, "text": "Let us now understand each one of the tools available in the Selenium suite and their usage." }, { "code": null, "e": 2291, "s": 2278, "text": "Selenium IDE" }, { "code": null, "e": 2455, "s": 2291, "text": "Selenium Integrated Development Environment (IDE) is a Firefox plugin that lets testers to record their actions as they follow the workflow that they need to test." }, { "code": null, "e": 2467, "s": 2455, "text": "Selenium RC" }, { "code": null, "e": 2730, "s": 2467, "text": "Selenium Remote Control (RC) was the flagship testing framework that allowed more than simple browser actions and linear execution. It makes use of the full power of programming languages such as Java, C#, PHP, Python, Ruby and PERL to create more complex tests." }, { "code": null, "e": 2749, "s": 2730, "text": "Selenium WebDriver" }, { "code": null, "e": 2868, "s": 2749, "text": "Selenium WebDriver is the successor to Selenium RC which sends commands directly to the browser and retrieves results." }, { "code": null, "e": 2882, "s": 2868, "text": "Selenium Grid" }, { "code": null, "e": 3040, "s": 2882, "text": "Selenium Grid is a tool used to run parallel tests across different machines and different browsers simultaneously which results in minimized execution time." }, { "code": null, "e": 3191, "s": 3040, "text": "QTP and Selenium are the most used tools in the market for software automation testing. Hence it makes sense to compare the pros of Selenium over QTP." }, { "code": null, "e": 3245, "s": 3191, "text": "Let us now discuss the pitfalls of Selenium over QTP." }, { "code": null, "e": 3568, "s": 3245, "text": "The Selenium-IDE (Integrated Development Environment) is an easy-to-use Firefox plug-in to develop Selenium test cases. It provides a Graphical User Interface for recording user actions using Firefox which is used to learn and use Selenium, but it can only be used with Firefox browser as other browsers are not supported." }, { "code": null, "e": 3731, "s": 3568, "text": "However, the recorded scripts can be converted into various programming languages supported by Selenium and the scripts can be executed on other browsers as well." }, { "code": null, "e": 3814, "s": 3731, "text": "The following table lists the sections that we are going to cover in this chapter." }, { "code": null, "e": 3882, "s": 3814, "text": "This section deals with how to download and configure Selenium IDE." }, { "code": null, "e": 3946, "s": 3882, "text": "This section deals with the features available in Selenium IDE." }, { "code": null, "e": 4019, "s": 3946, "text": "This section deals with how to create IDE tests using recording feature." }, { "code": null, "e": 4078, "s": 4019, "text": "This section deals with debugging the Selenium IDE script." }, { "code": null, "e": 4152, "s": 4078, "text": "This section describes how to insert verification points in Selenium IDE." }, { "code": null, "e": 4224, "s": 4152, "text": "This section deals with how to work with regular expressions using IDE." }, { "code": null, "e": 4297, "s": 4224, "text": "The Java script that allows users to customize or add new functionality." }, { "code": null, "e": 4380, "s": 4297, "text": "This section deals with how to execute Selenium IDE scripts on different browsers." }, { "code": null, "e": 4559, "s": 4380, "text": "In order to develop Selenium RC or WebDriver scripts, users have to ensure that they have the initial configuration done. Setting up the environment involves the following steps." }, { "code": null, "e": 4585, "s": 4559, "text": "Download and Install Java" }, { "code": null, "e": 4616, "s": 4585, "text": "Download and Configure Eclipse" }, { "code": null, "e": 4647, "s": 4616, "text": "Configure FireBug and FirePath" }, { "code": null, "e": 4669, "s": 4647, "text": "Configure Selenium RC" }, { "code": null, "e": 4698, "s": 4669, "text": "Configure Selenium WebDriver" }, { "code": null, "e": 4847, "s": 4698, "text": "We need to have JDK (Java Development Kit) installed in order to work with Selenium WebDriver/Selenium. Let us see how to download and install Java." }, { "code": null, "e": 4876, "s": 4847, "text": "Step 1 − Navigate to the UR." }, { "code": null, "e": 4944, "s": 4876, "text": "https://www.oracle.com/technetwork/java/javase/downloads/index.html" }, { "code": null, "e": 5006, "s": 4944, "text": "Step 2 − Go to \"Downloads\" section and select \"JDK Download\"." }, { "code": null, "e": 5063, "s": 5006, "text": "Step 3 − Select \"Accept License Agreement\" radio button." }, { "code": null, "e": 5213, "s": 5063, "text": "Step 4 − Select the appropriate installation. In this case, it is 'Windows 7-64' bit. Click the appropriate link and save the .exe file to your disk." }, { "code": null, "e": 5308, "s": 5213, "text": "Step 5 − Run the downloaded exe file to launch the Installer wizard. Click 'Next' to continue." }, { "code": null, "e": 5355, "s": 5308, "text": "Step 6 − Select the features and click 'Next'." }, { "code": null, "e": 5432, "s": 5355, "text": "Step 7 − The installer is extracted and its progress is shown in the wizard." }, { "code": null, "e": 5500, "s": 5432, "text": "Step 8 − The user can choose the install location and click 'Next'." }, { "code": null, "e": 5573, "s": 5500, "text": "Step 9 − The installer installs the JDK and new files are copied across." }, { "code": null, "e": 5654, "s": 5573, "text": "Step 10 − The Installer installs successfully and displays the same to the user." }, { "code": null, "e": 5929, "s": 5654, "text": "Step 11 − To verify if the installation was successful, go to the command prompt and just type 'java' as a command. The output of the command is shown below. If the Java installation is unsuccessful or if it had NOT been installed, it would throw an \"unknown command\" error." }, { "code": null, "e": 6059, "s": 5929, "text": "Step 1 − Navigate to the URL: https://www.eclipse.org/downloads/ and download the appropriate file based on your OS architecture." }, { "code": null, "e": 6097, "s": 6059, "text": "Step 2 − Click the 'Download' button." }, { "code": null, "e": 6168, "s": 6097, "text": "Step 3 − The download would be in a Zipped format. Unzip the contents." }, { "code": null, "e": 6226, "s": 6168, "text": "Step 4 − Locate Eclipse.exe and double click on the file." }, { "code": null, "e": 6324, "s": 6226, "text": "Step 5 − To configure the workspace, select the location where the development has to take place." }, { "code": null, "e": 6374, "s": 6324, "text": "Step 6 − The Eclipse window opens as shown below." }, { "code": null, "e": 6535, "s": 6374, "text": "To work with Selenium RC or WebDriver, we need to locate elements based on their XPath or ID or name, etc. In order to locate an element, we need tools/plugins." }, { "code": null, "e": 6643, "s": 6535, "text": "Step 1 − Navigate to the URL : https://addons.mozilla.org/en-US/firefox/addon/firebug/ and download plugin." }, { "code": null, "e": 6750, "s": 6643, "text": "Step 2 − The add-on installer is shown to the user and it is installed upon clicking the 'Install' button." }, { "code": null, "e": 6849, "s": 6750, "text": "Step 3 − After installing, we can launch the plugin by navigating to \"Web Developer\" >> \"Firebug\"." }, { "code": null, "e": 7045, "s": 6849, "text": "Step 4 − FirePath, a plugin that works within Firebug, helps users to grab the 'XPath' of an element. Install FirePath by navigating to \"https://addons.mozilla.org/en-US/firefox/addon/firepath/\"" }, { "code": null, "e": 7152, "s": 7045, "text": "Step 5 − The add-on installer is shown to the user and it is installed upon clicking the 'Install' button." }, { "code": null, "e": 7239, "s": 7152, "text": "Step 6 − Now launch \"Firebug\" by navigating to \"Tools\" >> \"Webdeveloper\" >> \"Firebug\"." }, { "code": null, "e": 7416, "s": 7239, "text": "Now let us understand how to use FireBug and FirePath with an example. For demonstration, we will use www.google.com and capture the properties of the text box of \"google.com\"." }, { "code": null, "e": 7719, "s": 7416, "text": "Step 1 − First click on the arrow icon as highlighted in the following screenshot and drag it to the object for which we would like to capture the properties. The HTML/DOM of the object would be displayed as shown below. We are able to capture the 'ID' of the input text box with which we can interact." }, { "code": null, "e": 7816, "s": 7719, "text": "Step 2 − To fetch the XPath of the object, go to 'firepath' tab and perform the following steps." }, { "code": null, "e": 7836, "s": 7816, "text": "Click the Spy icon." }, { "code": null, "e": 7901, "s": 7836, "text": "Select the Control for which we would like to capture the XPath." }, { "code": null, "e": 7951, "s": 7901, "text": "XPath of the selected control would be generated." }, { "code": null, "e": 8161, "s": 7951, "text": "Now let us look at how to configure Selenium Remote control. We will understand how to develop scripts with Selenium RC in later chapters, however for now, we will understand just the configuration part of it." }, { "code": null, "e": 8328, "s": 8161, "text": "Step 1 − Navigate to the Selenium downloads section http://www.seleniumhq.org/download/ and download Selenium Server by clicking on its version number as shown below." }, { "code": null, "e": 8505, "s": 8328, "text": "Step 2 − After downloading, we need to start the Selenium Server. To do so, open command prompt and navigate to the folder where the downloaded JAR file is kept as shown below." }, { "code": null, "e": 8720, "s": 8505, "text": "Step 3 − To start the server, use the command 'java -jar <<downloaded jar name >> and if java JDK is installed properly, you would get a success message as shown below. Now we can start writing Selenium RC scripts." }, { "code": null, "e": 8932, "s": 8720, "text": "Now let us look at how to configure Selenium WebDriver. We will understand how to develop scripts with Selenium WebDriver in later chapters, however for now, we will understand just the configuration part of it." }, { "code": null, "e": 9102, "s": 8932, "text": "Step 1 − Navigate to the selenium downloads section http://www.seleniumhq.org/download/ and download Selenium WebDriver by clicking on its version number as shown below." }, { "code": null, "e": 9218, "s": 9102, "text": "Step 2 − The downloaded file is in Zipped format and one has to unzip the contents to map it to the project folder." }, { "code": null, "e": 9388, "s": 9218, "text": "Step 3 − The Unzipped contents would be displayed as shown below. How to map it to the project folder and how to start scripting would be dealt in the webDriver chapter." }, { "code": null, "e": 9679, "s": 9388, "text": "Selenium Remote Control (RC) was the main Selenium project that sustained for a long time before Selenium WebDriver(Selenium 2.0) came into existence. Now Selenium RC is hardly in use, as WebDriver offers more powerful features, however users can still continue to develop scripts using RC." }, { "code": null, "e": 9940, "s": 9679, "text": "It allows us to write automated web application UI tests with the help of full power of programming languages such as Java, C#, Perl, Python and PHP to create more complex tests such as reading and writing files, querying a database, and emailing test results." }, { "code": null, "e": 10187, "s": 9940, "text": "Selenium RC works in such a way that the client libraries can communicate with the Selenium RC Server passing each Selenium command for execution. Then the server passes the Selenium command to the browser using Selenium-Core JavaScript commands." }, { "code": null, "e": 10263, "s": 10187, "text": "The browser executes the Selenium command using its JavaScript interpreter." }, { "code": null, "e": 10295, "s": 10263, "text": "Selenium RC comes in two parts." }, { "code": null, "e": 10548, "s": 10295, "text": "The Selenium Server launches and kills browsers. In addition to that, it interprets and executes the Selenese commands. It also acts as an HTTP proxy by intercepting and verifying HTTP messages passed between the browser and the application under test." }, { "code": null, "e": 10801, "s": 10548, "text": "The Selenium Server launches and kills browsers. In addition to that, it interprets and executes the Selenese commands. It also acts as an HTTP proxy by intercepting and verifying HTTP messages passed between the browser and the application under test." }, { "code": null, "e": 10951, "s": 10801, "text": "Client libraries that provide an interface between each one of the programming languages (Java, C#, Perl, Python and PHP) and the Selenium-RC Server." }, { "code": null, "e": 11101, "s": 10951, "text": "Client libraries that provide an interface between each one of the programming languages (Java, C#, Perl, Python and PHP) and the Selenium-RC Server." }, { "code": null, "e": 11352, "s": 11101, "text": "Now let us write a sample script using Selenium Remote Control. Let us use http://www.calculator.net/ for understanding Selenium RC. We will perform a Percent calculation using 'Percent Calculator' that is present under the 'Math Calculators' module." }, { "code": null, "e": 11426, "s": 11352, "text": "Step 1 − Start Selenium Remote Control (with the help of command prompt)." }, { "code": null, "e": 11520, "s": 11426, "text": "Step 2 − After launching Selenium RC, open Eclipse and create a \"New Project\" as shown below." }, { "code": null, "e": 11577, "s": 11520, "text": "Step 3 − Enter the project name and click 'Next' button." }, { "code": null, "e": 11664, "s": 11577, "text": "Step 4 − Verify the Source, Projects, Libraries, and Output folder and click 'Finish'." }, { "code": null, "e": 11743, "s": 11664, "text": "Step 5 − Right click on 'project' container and choose 'Configure Build Path'." }, { "code": null, "e": 11941, "s": 11743, "text": "Step 6 − Properties for 'selrcdemo' opens up. Navigate to 'Libraries' tab and select 'Add External JARs'. Choose the Selenium RC jar file that we have downloaded and it would appear as shown below." }, { "code": null, "e": 12005, "s": 11941, "text": "Step 7 − The referenced Libraries are shown as displayed below." }, { "code": null, "e": 12111, "s": 12005, "text": "Step 8 − Create a new class file by performing a right click on 'src' folder and select 'New' >> 'class'." }, { "code": null, "e": 12204, "s": 12111, "text": "Step 9 − Enter a name of the class file and enable 'public static void main' as shown below." }, { "code": null, "e": 12286, "s": 12204, "text": "Step 10 − The Created Class is created under the folder structure as shown below." }, { "code": null, "e": 12426, "s": 12286, "text": "Step 11 − Now it is time for coding. The following code has comments embedded in it to make the readers understand what has been put forth." }, { "code": null, "e": 13858, "s": 12426, "text": "package selrcdemo;\n\nimport com.thoughtworks.selenium.DefaultSelenium;\nimport com.thoughtworks.selenium.Selenium;\n\npublic class rcdemo {\n public static void main(String[] args) throws InterruptedException {\n\n // Instatiate the RC Server\n Selenium selenium = new DefaultSelenium(\"localhost\", 4444 , \"firefox\", \"http://www.calculator.net\");\n selenium.start(); // Start\n selenium.open(\"/\"); // Open the URL\n selenium.windowMaximize();\n\n // Click on Link Math Calculator\n selenium.click(\"xpath = .//*[@id = 'menu']/div[3]/a\");\n Thread.sleep(2500); // Wait for page load\n\n // Click on Link Percent Calculator\n selenium.click(\"xpath = .//*[@id = 'menu']/div[4]/div[3]/a\");\n Thread.sleep(4000); // Wait for page load\n\n // Focus on text Box\n selenium.focus(\"name = cpar1\");\n \n // enter a value in Text box 1\n selenium.type(\"css=input[name = \\\"cpar1\\\"]\", \"10\");\n \n // enter a value in Text box 2\n selenium.focus(\"name = cpar2\");\n selenium.type(\"css = input[name = \\\"cpar2\\\"]\", \"50\");\n\n // Click Calculate button\n selenium.click(\"xpath = .//*[@id = 'content']/table/tbody/tr/td[2]/input\");\n\n // verify if the result is 5\n String result = selenium.getText(\".//*[@id = 'content']/p[2]\");\n\n if (result == \"5\") {\n System.out.println(\"Pass\");\n } else {\n System.out.println(\"Fail\");\n }\n }\n}" }, { "code": null, "e": 13925, "s": 13858, "text": "Step 12 − Now, let us execute the script by clicking 'Run' Button." }, { "code": null, "e": 14047, "s": 13925, "text": "Step 13 − The script would start executing and user would be able to see the command history under 'Command History' Tab." }, { "code": null, "e": 14194, "s": 14047, "text": "Step 14 − The final state of the application is shown as below. The percentage is calculated and it displayed the result on screen as shown below." }, { "code": null, "e": 14399, "s": 14194, "text": "Step 15 − The output of the test is printed on the Eclipse console as shown below as we have printed the output to the console. In real time the output is written to an HTML file or in a simple Text file." }, { "code": null, "e": 14547, "s": 14399, "text": "A command refers to what Selenium has to do and commands in selenium are of three types. Click on each one of them to know more about the commands." }, { "code": null, "e": 14555, "s": 14547, "text": "Actions" }, { "code": null, "e": 14563, "s": 14555, "text": "Actions" }, { "code": null, "e": 14573, "s": 14563, "text": "Accessors" }, { "code": null, "e": 14583, "s": 14573, "text": "Accessors" }, { "code": null, "e": 14594, "s": 14583, "text": "Assertions" }, { "code": null, "e": 14605, "s": 14594, "text": "Assertions" }, { "code": null, "e": 14838, "s": 14605, "text": "Element Locators help Selenium to identify the HTML element the command refers to. All these locators can be identified with the help of FirePath and FireBug plugin of Mozilla. Please refer the Environment Setup chapter for details." }, { "code": null, "e": 14987, "s": 14838, "text": "identifier = id Select the element with the specified \"id\" attribute and if there is no match, select the first element whose @name attribute is id." }, { "code": null, "e": 15136, "s": 14987, "text": "identifier = id Select the element with the specified \"id\" attribute and if there is no match, select the first element whose @name attribute is id." }, { "code": null, "e": 15198, "s": 15136, "text": "id = id Select the element with the specified \"id\" attribute." }, { "code": null, "e": 15260, "s": 15198, "text": "id = id Select the element with the specified \"id\" attribute." }, { "code": null, "e": 15333, "s": 15260, "text": "name = name Select the first element with the specified \"name\" attribute" }, { "code": null, "e": 15406, "s": 15333, "text": "name = name Select the first element with the specified \"name\" attribute" }, { "code": null, "e": 15654, "s": 15406, "text": "dom = javascriptExpression Selenium finds an element by evaluating the specified string that allows us to traverse through the HTML Document Object Model using JavaScript. Users cannot return a value but can evaluate as an expression in the block." }, { "code": null, "e": 15902, "s": 15654, "text": "dom = javascriptExpression Selenium finds an element by evaluating the specified string that allows us to traverse through the HTML Document Object Model using JavaScript. Users cannot return a value but can evaluate as an expression in the block." }, { "code": null, "e": 15971, "s": 15902, "text": "xpath = xpathExpression Locate an element using an XPath expression." }, { "code": null, "e": 16040, "s": 15971, "text": "xpath = xpathExpression Locate an element using an XPath expression." }, { "code": null, "e": 16156, "s": 16040, "text": "link = textPattern Select the link element (within anchor tags) which contains text matching the specified pattern." }, { "code": null, "e": 16272, "s": 16156, "text": "link = textPattern Select the link element (within anchor tags) which contains text matching the specified pattern." }, { "code": null, "e": 16335, "s": 16272, "text": "css = cssSelectorSyntax Select the element using css selector." }, { "code": null, "e": 16398, "s": 16335, "text": "css = cssSelectorSyntax Select the element using css selector." }, { "code": null, "e": 16811, "s": 16398, "text": "WebDriver is a tool for automating testing web applications. It is popularly known as Selenium 2.0. WebDriver uses a different underlying framework, while Selenium RC uses JavaScript Selenium-Core embedded within the browser which has got some limitations. WebDriver interacts directly with the browser without any intermediary, unlike Selenium RC that depends on a server. It is used in the following context −" }, { "code": null, "e": 16939, "s": 16811, "text": "Multi-browser testing including improved functionality for browsers which is not well-supported by Selenium RC (Selenium 1.0)." }, { "code": null, "e": 17067, "s": 16939, "text": "Multi-browser testing including improved functionality for browsers which is not well-supported by Selenium RC (Selenium 1.0)." }, { "code": null, "e": 17139, "s": 17067, "text": "Handling multiple frames, multiple browser windows, popups, and alerts." }, { "code": null, "e": 17211, "s": 17139, "text": "Handling multiple frames, multiple browser windows, popups, and alerts." }, { "code": null, "e": 17236, "s": 17211, "text": "Complex page navigation." }, { "code": null, "e": 17261, "s": 17236, "text": "Complex page navigation." }, { "code": null, "e": 17309, "s": 17261, "text": "Advanced user navigation such as drag-and-drop." }, { "code": null, "e": 17357, "s": 17309, "text": "Advanced user navigation such as drag-and-drop." }, { "code": null, "e": 17381, "s": 17357, "text": "AJAX-based UI elements." }, { "code": null, "e": 17405, "s": 17381, "text": "AJAX-based UI elements." }, { "code": null, "e": 17484, "s": 17405, "text": "WebDriver is best explained with a simple architecture diagram as shown below." }, { "code": null, "e": 17782, "s": 17484, "text": "Let us understand how to work with WebDriver. For demonstration, we would use https://www.calculator.net/. We will perform a \"Percent Calculator\" which is located under \"Math Calculator\". We have already downloaded the required WebDriver JAR's. Refer the chapter \"Environmental Setup\" for details." }, { "code": null, "e": 17843, "s": 17782, "text": "Step 1 − Launch \"Eclipse\" from the Extracted Eclipse folder." }, { "code": null, "e": 17906, "s": 17843, "text": "Step 2 − Select the Workspace by clicking the 'Browse' button." }, { "code": null, "e": 17960, "s": 17906, "text": "Step 3 − Now create a 'New Project' from 'File' menu." }, { "code": null, "e": 18010, "s": 17960, "text": "Step 4 − Enter the Project Name and Click 'Next'." }, { "code": null, "e": 18226, "s": 18010, "text": "Step 5 − Go to Libraries Tab and select all the JAR's that we have downloaded. Add reference to all the JAR's of Selenium WebDriver Library folder and also selenium-java-2.42.2.jar and selenium-java-2.42.2-srcs.jar." }, { "code": null, "e": 18274, "s": 18226, "text": "Step 6 − The Package is created as shown below." }, { "code": null, "e": 18363, "s": 18274, "text": "Step 7 − Now right-click on the package and select 'New' >> 'Class' to create a 'class'." }, { "code": null, "e": 18422, "s": 18363, "text": "Step 8 − Now name the class and make it the main function." }, { "code": null, "e": 18468, "s": 18422, "text": "Step 9 − The class outline is shown as below." }, { "code": null, "e": 18705, "s": 18468, "text": "Step 10 − Now it is time to code. The following script is easier to understand, as it has comments embedded in it to explain the steps clearly. Please take a look at the chapter \"Locators\" to understand how to capture object properties." }, { "code": null, "e": 20254, "s": 18705, "text": "import java.util.concurrent.TimeUnit;\n\nimport org.openqa.selenium.*;\nimport org.openqa.selenium.firefox.FirefoxDriver;\n\npublic class webdriverdemo {\n public static void main(String[] args) {\n \n WebDriver driver = new FirefoxDriver();\n //Puts an Implicit wait, Will wait for 10 seconds before throwing exception\n driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);\n \n //Launch website\n driver.navigate().to(\"http://www.calculator.net/\");\n \n //Maximize the browser\n driver.manage().window().maximize();\n \n // Click on Math Calculators\n driver.findElement(By.xpath(\".//*[@id = 'menu']/div[3]/a\")).click();\n \n // Click on Percent Calculators\n driver.findElement(By.xpath(\".//*[@id = 'menu']/div[4]/div[3]/a\")).click();\n \n // Enter value 10 in the first number of the percent Calculator\n driver.findElement(By.id(\"cpar1\")).sendKeys(\"10\");\n \n // Enter value 50 in the second number of the percent Calculator\n driver.findElement(By.id(\"cpar2\")).sendKeys(\"50\");\n \n // Click Calculate Button\n driver.findElement(By.xpath(\".//*[@id = 'content']/table/tbody/tr[2]/td/input[2]\")).click();\n\n \n // Get the Result Text based on its xpath\n String result =\n driver.findElement(By.xpath(\".//*[@id = 'content']/p[2]/font/b\")).getText();\n\n \n // Print a Log In message to the screen\n System.out.println(\" The Result is \" + result);\n \n //Close the Browser.\n driver.close();\n }\n}" }, { "code": null, "e": 20324, "s": 20254, "text": "Step 11 − The output of the above script would be printed in Console." }, { "code": null, "e": 20430, "s": 20324, "text": "The following table lists some of the most frequently used commands in WebDriver along with their syntax." }, { "code": null, "e": 20448, "s": 20430, "text": "driver.get(\"URL\")" }, { "code": null, "e": 20479, "s": 20448, "text": "To navigate to an application." }, { "code": null, "e": 20509, "s": 20479, "text": "element.sendKeys(\"inputtext\")" }, { "code": null, "e": 20544, "s": 20509, "text": "Enter some text into an input box." }, { "code": null, "e": 20560, "s": 20544, "text": "element.clear()" }, { "code": null, "e": 20599, "s": 20560, "text": "Clear the contents from the input box." }, { "code": null, "e": 20620, "s": 20599, "text": "select.deselectAll()" }, { "code": null, "e": 20676, "s": 20620, "text": "Deselect all OPTIONs from the first SELECT on the page." }, { "code": null, "e": 20716, "s": 20676, "text": "select.selectByVisibleText(\"some text\")" }, { "code": null, "e": 20772, "s": 20716, "text": "Select the OPTION with the input specified by the user." }, { "code": null, "e": 20811, "s": 20772, "text": "driver.switchTo().window(\"windowName\")" }, { "code": null, "e": 20854, "s": 20811, "text": "Move the focus from one window to another." }, { "code": null, "e": 20891, "s": 20854, "text": "driver.switchTo().frame(\"frameName\")" }, { "code": null, "e": 20918, "s": 20891, "text": "Swing from frame to frame." }, { "code": null, "e": 20944, "s": 20918, "text": "driver.switchTo().alert()" }, { "code": null, "e": 20970, "s": 20944, "text": "Helps in handling alerts." }, { "code": null, "e": 20998, "s": 20970, "text": "driver.navigate().to(\"URL\")" }, { "code": null, "e": 21019, "s": 20998, "text": "Navigate to the URL." }, { "code": null, "e": 21047, "s": 21019, "text": "driver.navigate().forward()" }, { "code": null, "e": 21068, "s": 21047, "text": "To navigate forward." }, { "code": null, "e": 21093, "s": 21068, "text": "driver.navigate().back()" }, { "code": null, "e": 21111, "s": 21093, "text": "To navigate back." }, { "code": null, "e": 21126, "s": 21111, "text": "driver.close()" }, { "code": null, "e": 21181, "s": 21126, "text": "Closes the current browser associated with the driver." }, { "code": null, "e": 21195, "s": 21181, "text": "driver.quit()" }, { "code": null, "e": 21265, "s": 21195, "text": "Quits the driver and closes all the associated window of that driver." }, { "code": null, "e": 21282, "s": 21265, "text": "driver.refresh()" }, { "code": null, "e": 21310, "s": 21282, "text": "Refreshes the current page." }, { "code": null, "e": 21465, "s": 21310, "text": "Locating elements in Selenium WebDriver is performed with the help of findElement() and findElements() methods provided by WebDriver and WebElement class." }, { "code": null, "e": 21639, "s": 21465, "text": "findElement() returns a WebElement object based on a specified search criteria or ends up throwing an exception if it does not find any element matching the search criteria." }, { "code": null, "e": 21813, "s": 21639, "text": "findElement() returns a WebElement object based on a specified search criteria or ends up throwing an exception if it does not find any element matching the search criteria." }, { "code": null, "e": 21940, "s": 21813, "text": "findElements() returns a list of WebElements matching the search criteria. If no elements are found, it returns an empty list." }, { "code": null, "e": 22067, "s": 21940, "text": "findElements() returns a list of WebElements matching the search criteria. If no elements are found, it returns an empty list." }, { "code": null, "e": 22158, "s": 22067, "text": "The following table lists all the Java syntax for locating elements in Selenium WebDriver." }, { "code": null, "e": 22275, "s": 22158, "text": "Now let us understand the practical usage of each of the locator methods with the help of https://www.calculator.net" }, { "code": null, "e": 22462, "s": 22275, "text": "Here an object is accessed with the help of IDs. In this case, it is the ID of the text box. Values are entered into the text box using the sendkeys method with the help of ID(cdensity)." }, { "code": null, "e": 22516, "s": 22462, "text": "driver.findElement(By.id(\"cdensity\")).sendKeys(\"10\");" }, { "code": null, "e": 22707, "s": 22516, "text": "Here an object is accessed with the help of names. In this case, it is the name of the text box. Values are entered into the text box using the sendkeys method with the help of ID(cdensity)." }, { "code": null, "e": 22763, "s": 22707, "text": "driver.findElement(By.name(\"cdensity\")).sendKeys(\"10\");" }, { "code": null, "e": 22937, "s": 22763, "text": "Here an object is accessed with the help of Class Names. In this case, it is the Class name of the WebElement. The Value can be accessed with the help of the gettext method." }, { "code": null, "e": 23017, "s": 22937, "text": "List<WebElement> byclass = driver.findElements(By.className(\"smalltext smtb\"));" }, { "code": null, "e": 23210, "s": 23017, "text": "The DOM Tag Name of an element can be used to locate that particular element in the WebDriver. It is very easy to handle tables with the help of this method. Take a look at the following code." }, { "code": null, "e": 23357, "s": 23210, "text": "WebElement table = driver.findElement(By.id(\"calctable\"));\nList<WebElement> row = table.findElements(By.tagName(\"tr\"));\nint rowcount = row.size();" }, { "code": null, "e": 23428, "s": 23357, "text": "This method helps to locate a link element with matching visible text." }, { "code": null, "e": 23480, "s": 23428, "text": "driver.findElements(By.linkText(\"Volume\")).click();" }, { "code": null, "e": 23557, "s": 23480, "text": "This methods helps locate a link element with partial matching visible text." }, { "code": null, "e": 23615, "s": 23557, "text": "driver.findElement(By.partialLinkText(\"Volume\")).click();" }, { "code": null, "e": 23723, "s": 23615, "text": "The CSS is used as a method to identify the webobject, however NOT all browsers support CSS identification." }, { "code": null, "e": 23799, "s": 23723, "text": "WebElement loginButton = driver.findElement(By.cssSelector(\"input.login\"));" }, { "code": null, "e": 24060, "s": 23799, "text": "XPath stands for XML path language. It is a query language for selecting nodes from an XML document. XPath is based on the tree representation of XML documents and provides the ability to navigate around the tree by selecting nodes using a variety of criteria." }, { "code": null, "e": 24182, "s": 24060, "text": "driver.findElement(By.xpath(\".//*[@id = 'content']/table[1]/tbody/tr/td/table/tbody/tr[2]/td[1]/input\")).sendkeys(\"100\");" }, { "code": null, "e": 24470, "s": 24182, "text": "Selenium WebDriver is the most frequently used tool among all the tools available in the Selenium tool set. Therefore it is important to understand how to use Selenium to interact with web apps. In this module, let us understand how to interact with GUI objects using Selenium webDriver." }, { "code": null, "e": 24651, "s": 24470, "text": "We need to interact with the application using some basic actions or even some advanced user action by developing user-defined functions for which there are no predefined commands." }, { "code": null, "e": 24727, "s": 24651, "text": "Listed below are the different kinds of actions against those GUI objects −" }, { "code": null, "e": 24748, "s": 24727, "text": "Text Box Interaction" }, { "code": null, "e": 24769, "s": 24748, "text": "Text Box Interaction" }, { "code": null, "e": 24792, "s": 24769, "text": "Radio Button Selection" }, { "code": null, "e": 24815, "s": 24792, "text": "Radio Button Selection" }, { "code": null, "e": 24835, "s": 24815, "text": "Check Box Selection" }, { "code": null, "e": 24855, "s": 24835, "text": "Check Box Selection" }, { "code": null, "e": 24880, "s": 24855, "text": "Drop Down Item Selection" }, { "code": null, "e": 24905, "s": 24880, "text": "Drop Down Item Selection" }, { "code": null, "e": 24921, "s": 24905, "text": "Synchronization" }, { "code": null, "e": 24937, "s": 24921, "text": "Synchronization" }, { "code": null, "e": 24949, "s": 24937, "text": "Drag & Drop" }, { "code": null, "e": 24961, "s": 24949, "text": "Drag & Drop" }, { "code": null, "e": 24979, "s": 24961, "text": "Keyboard Actions " }, { "code": null, "e": 24997, "s": 24979, "text": "Keyboard Actions " }, { "code": null, "e": 25011, "s": 24997, "text": "Mouse Actions" }, { "code": null, "e": 25025, "s": 25011, "text": "Mouse Actions" }, { "code": null, "e": 25038, "s": 25025, "text": "Multi Select" }, { "code": null, "e": 25051, "s": 25038, "text": "Multi Select" }, { "code": null, "e": 25067, "s": 25051, "text": "Find All Links " }, { "code": null, "e": 25083, "s": 25067, "text": "Find All Links " }, { "code": null, "e": 25292, "s": 25083, "text": "There are various components involved in designing the tests. Let us understand some of the important components involved in designing a framework as well. We will learn the following topics in this chapter −" }, { "code": null, "e": 25310, "s": 25292, "text": "Page Object Model" }, { "code": null, "e": 25328, "s": 25310, "text": "Page Object Model" }, { "code": null, "e": 25355, "s": 25328, "text": "Parameterizing using Excel" }, { "code": null, "e": 25382, "s": 25355, "text": "Parameterizing using Excel" }, { "code": null, "e": 25396, "s": 25382, "text": "Log4j Logging" }, { "code": null, "e": 25410, "s": 25396, "text": "Log4j Logging" }, { "code": null, "e": 25429, "s": 25410, "text": "Exception Handling" }, { "code": null, "e": 25448, "s": 25429, "text": "Exception Handling" }, { "code": null, "e": 25470, "s": 25448, "text": "Multi Browser Testing" }, { "code": null, "e": 25492, "s": 25470, "text": "Multi Browser Testing" }, { "code": null, "e": 25512, "s": 25492, "text": "Capture Screenshots" }, { "code": null, "e": 25532, "s": 25512, "text": "Capture Screenshots" }, { "code": null, "e": 25547, "s": 25532, "text": "Capture Videos" }, { "code": null, "e": 25562, "s": 25547, "text": "Capture Videos" }, { "code": null, "e": 25732, "s": 25562, "text": "TestNG is a powerful testing framework, an enhanced version of JUnit which was in use for a long time before TestNG came into existence. NG stands for 'Next Generation'." }, { "code": null, "e": 25783, "s": 25732, "text": "TestNG framework provides the following features −" }, { "code": null, "e": 25830, "s": 25783, "text": "Annotations help us organize the tests easily." }, { "code": null, "e": 25859, "s": 25830, "text": "Flexible test configuration." }, { "code": null, "e": 25898, "s": 25859, "text": "Test cases can be grouped more easily." }, { "code": null, "e": 25953, "s": 25898, "text": "Parallelization of tests can be achieved using TestNG." }, { "code": null, "e": 25986, "s": 25953, "text": "Support for data-driven testing." }, { "code": null, "e": 26005, "s": 25986, "text": "Inbuilt reporting." }, { "code": null, "e": 26064, "s": 26005, "text": "Step 1 − Launch Eclipse and select 'Install New Software'." }, { "code": null, "e": 26134, "s": 26064, "text": "Step 2 − Enter the URL as 'http://beust.com/eclipse' and click 'Add'." }, { "code": null, "e": 26224, "s": 26134, "text": "Step 3 − The dialog box 'Add Repository' opens. Enter the name as 'TestNG' and click 'OK'" }, { "code": null, "e": 26307, "s": 26224, "text": "Step 4 − Click 'Select All' and 'TestNG' would be selected as shown in the figure." }, { "code": null, "e": 26342, "s": 26307, "text": "Step 5 − Click 'Next' to continue." }, { "code": null, "e": 26404, "s": 26342, "text": "Step 6 − Review the items that are selected and click 'Next'." }, { "code": null, "e": 26464, "s": 26404, "text": "Step 7 − \"Accept the License Agreement\" and click 'Finish'." }, { "code": null, "e": 26539, "s": 26464, "text": "Step 8 − TestNG starts installing and the progress would be shown follows." }, { "code": null, "e": 26640, "s": 26539, "text": "Step 9 − Security Warning pops up as the validity of the software cannot be established. Click 'Ok'." }, { "code": null, "e": 26736, "s": 26640, "text": "Step 10 − The Installer prompts to restart Eclipse for the changes to take effect. Click 'Yes'." }, { "code": null, "e": 26964, "s": 26736, "text": "Annotations were formally added to the Java language in JDK 5 and TestNG made the choice to use annotations to annotate test classes. Following are some of the benefits of using annotations. More about TestNG can be found \nhere" }, { "code": null, "e": 27106, "s": 26964, "text": "TestNG identifies the methods it is interested in by looking up annotations. Hence, method names are not restricted to any pattern or format." }, { "code": null, "e": 27248, "s": 27106, "text": "TestNG identifies the methods it is interested in by looking up annotations. Hence, method names are not restricted to any pattern or format." }, { "code": null, "e": 27298, "s": 27248, "text": "We can pass additional parameters to annotations." }, { "code": null, "e": 27348, "s": 27298, "text": "We can pass additional parameters to annotations." }, { "code": null, "e": 27431, "s": 27348, "text": "Annotations are strongly typed, so the compiler will flag any mistakes right away." }, { "code": null, "e": 27514, "s": 27431, "text": "Annotations are strongly typed, so the compiler will flag any mistakes right away." }, { "code": null, "e": 27594, "s": 27514, "text": "Test classes no longer need to extend anything (such as TestCase, for JUnit 3)." }, { "code": null, "e": 27674, "s": 27594, "text": "Test classes no longer need to extend anything (such as TestCase, for JUnit 3)." }, { "code": null, "e": 27687, "s": 27674, "text": "@BeforeSuite" }, { "code": null, "e": 27775, "s": 27687, "text": "The annotated method will be run only once before all the tests in this suite have run." }, { "code": null, "e": 27787, "s": 27775, "text": "@AfterSuite" }, { "code": null, "e": 27874, "s": 27787, "text": "The annotated method will be run only once after all the tests in this suite have run." }, { "code": null, "e": 27887, "s": 27874, "text": "@BeforeClass" }, { "code": null, "e": 27992, "s": 27887, "text": "The annotated method will be run only once before the first test method in the current class is invoked." }, { "code": null, "e": 28004, "s": 27992, "text": "@AfterClass" }, { "code": null, "e": 28105, "s": 28004, "text": "The annotated method will be run only once after all the test methods in the current class have run." }, { "code": null, "e": 28117, "s": 28105, "text": "@BeforeTest" }, { "code": null, "e": 28228, "s": 28117, "text": "The annotated method will be run before any test method belonging to the classes inside the <test> tag is run." }, { "code": null, "e": 28239, "s": 28228, "text": "@AfterTest" }, { "code": null, "e": 28357, "s": 28239, "text": " The annotated method will be run after all the test methods belonging to the classes inside the <test> tag have run." }, { "code": null, "e": 28371, "s": 28357, "text": "@BeforeGroups" }, { "code": null, "e": 28556, "s": 28371, "text": "The list of groups that this configuration method will run before. This method is guaranteed to run shortly before the first test method that belongs to any of these groups is invoked." }, { "code": null, "e": 28569, "s": 28556, "text": "@AfterGroups" }, { "code": null, "e": 28751, "s": 28569, "text": "The list of groups that this configuration method will run after. This method is guaranteed to run shortly after the last test method that belongs to any of these groups is invoked." }, { "code": null, "e": 28765, "s": 28751, "text": "@BeforeMethod" }, { "code": null, "e": 28823, "s": 28765, "text": "The annotated method will be run before each test method." }, { "code": null, "e": 28836, "s": 28823, "text": "@AfterMethod" }, { "code": null, "e": 28893, "s": 28836, "text": "The annotated method will be run after each test method." }, { "code": null, "e": 28907, "s": 28893, "text": "@DataProvider" }, { "code": null, "e": 29223, "s": 28907, "text": "Marks a method as supplying data for a test method. The annotated method must return an Object[ ][ ] where each Object[ ] can be assigned the parameter list of the test method. The @Test method that wants to receive data from this DataProvider needs to use a dataProvider name equals to the name of this annotation." }, { "code": null, "e": 29232, "s": 29223, "text": "@Factory" }, { "code": null, "e": 29360, "s": 29232, "text": "Marks a method as a factory that returns objects that will be used by TestNG as Test classes. The method must return Object[ ]." }, { "code": null, "e": 29371, "s": 29360, "text": "@Listeners" }, { "code": null, "e": 29406, "s": 29371, "text": "Defines listeners on a test class." }, { "code": null, "e": 29418, "s": 29406, "text": "@Parameters" }, { "code": null, "e": 29470, "s": 29418, "text": "Describes how to pass parameters to a @Test method." }, { "code": null, "e": 29476, "s": 29470, "text": "@Test" }, { "code": null, "e": 29523, "s": 29476, "text": "Marks a class or a method as part of the test." }, { "code": null, "e": 29595, "s": 29523, "text": "Step 1 − Launch Eclipse and create a 'New Java Project' as shown below." }, { "code": null, "e": 29645, "s": 29595, "text": "Step 2 − Enter the project name and click 'Next'." }, { "code": null, "e": 29786, "s": 29645, "text": "Step 3 − Navigate to \"Libraries\" Tab and Add the Selenium Remote Control Server JAR file by clicking on \"Add External JAR's\" as shown below." }, { "code": null, "e": 29850, "s": 29786, "text": "Step 4 − The added JAR file is shown here. Click 'Add Library'." }, { "code": null, "e": 29957, "s": 29850, "text": "Step 5 − The 'Add Library' dialog opens. Select 'TestNG' and click 'Next' in the 'Add Library' dialog box." }, { "code": null, "e": 30038, "s": 29957, "text": "Step 6 − The added 'TestNG' Library is added and it is displayed as shown below." }, { "code": null, "e": 30128, "s": 30038, "text": "Step 7 − Upon creating the project, the structure of the project would be as shown below." }, { "code": null, "e": 30190, "s": 30128, "text": "Step 8 − Right-click on 'src' folder and select New >> Other." }, { "code": null, "e": 30233, "s": 30190, "text": "Step 9 − Select 'TestNG' and click 'Next'." }, { "code": null, "e": 30291, "s": 30233, "text": "Step 10 − Select the 'Source Folder' name and click 'Ok'." }, { "code": null, "e": 30366, "s": 30291, "text": "Step 11 − Select the 'Package name', the 'class name', and click 'Finish'." }, { "code": null, "e": 30439, "s": 30366, "text": "Step 12 − The Package explorer and the created class would be displayed." }, { "code": null, "e": 30647, "s": 30439, "text": "Now let us start scripting using TestNG. Let us script for the same example that we used for understanding the WebDriver. We will use the demo application, www.calculator.net, and perform percent calculator." }, { "code": null, "e": 31011, "s": 30647, "text": "In the following test, you will notice that there is NO main method, as testNG will drive the program execution flow. After initializing the driver, it will execute the '@BeforeTest' method followed by '@Test' and then '@AfterTest'. Please note that there can be any number of '@Test' annotation in a class but '@BeforeTest' and '@AfterTest' can appear only once." }, { "code": null, "e": 32883, "s": 31011, "text": "package TestNG;\n\nimport java.util.concurrent.TimeUnit;\n\nimport org.openqa.selenium.*;\nimport org.openqa.selenium.firefox.FirefoxDriver;\n\nimport org.testng.annotations.AfterTest;\nimport org.testng.annotations.BeforeTest;\nimport org.testng.annotations.Test;\n\npublic class TestNGClass {\n WebDriver driver = new FirefoxDriver();\n \n @BeforeTest\n public void launchapp() {\n // Puts an Implicit wait, Will wait for 10 seconds before throwing exception\n driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);\n \n // Launch website\n driver.navigate().to(\"http://www.calculator.net\");\n driver.manage().window().maximize();\n }\n \n @Test\n public void calculatepercent() {\n // Click on Math Calculators\n driver.findElement(By.xpath(\".//*[@id='menu']/div[3]/a\")).click();\n \n // Click on Percent Calculators\n driver.findElement(By.xpath(\".//*[@id='menu']/div[4]/div[3]/a\")).click();\n \n // Enter value 10 in the first number of the percent Calculator\n driver.findElement(By.id(\"cpar1\")).sendKeys(\"10\");\n \n // Enter value 50 in the second number of the percent Calculator\n driver.findElement(By.id(\"cpar2\")).sendKeys(\"50\");\n \n // Click Calculate Button\n driver.findElement(By.xpath(\".//*[@id='content']/table/tbody/tr/td[2]/input\")).click();\n \n // Get the Result Text based on its xpath\n String result =\n driver.findElement(By.xpath(\".//*[@id='content']/p[2]/span/font/b\")).getText();\n \n // Print a Log In message to the screen\n System.out.println(\" The Result is \" + result);\n \n if(result.equals(\"5\")) {\n System.out.println(\" The Result is Pass\");\n } else {\n System.out.println(\" The Result is Fail\");\n }\n }\n \n @AfterTest\n public void terminatetest() {\n driver.close();\n }\n}" }, { "code": null, "e": 32964, "s": 32883, "text": "To execute, right click on the created XML and select \"Run As\" >> \"TestNG Suite\"" }, { "code": null, "e": 33086, "s": 32964, "text": "The output is thrown to the console and it would appear as shown below. The console output also has an execution summary." }, { "code": null, "e": 33195, "s": 33086, "text": "The result of TestNG can also be seen in a different tab. Click on 'HTML Report View' button as shown below." }, { "code": null, "e": 33246, "s": 33195, "text": "The HTML result would be displayed as shown below." }, { "code": null, "e": 33530, "s": 33246, "text": "Selenium Grid is a tool that distributes the tests across multiple physical or virtual machines so that we can execute scripts in parallel (simultaneously). It dramatically accelerates the testing process across browsers and across platforms by giving us quick and accurate feedback." }, { "code": null, "e": 33848, "s": 33530, "text": "Selenium Grid allows us to execute multiple instances of WebDriver or Selenium Remote Control tests in parallel which uses the same code base, hence the code need NOT be present on the system they execute. The selenium-server-standalone package includes Hub, WebDriver, and Selenium RC to execute the scripts in grid." }, { "code": null, "e": 33884, "s": 33848, "text": "Selenium Grid has a Hub and a Node." }, { "code": null, "e": 34079, "s": 33884, "text": "Hub − The hub can also be understood as a server which acts as the central point where the tests would be triggered. A Selenium Grid has only one Hub and it is launched on a single machine once." }, { "code": null, "e": 34274, "s": 34079, "text": "Hub − The hub can also be understood as a server which acts as the central point where the tests would be triggered. A Selenium Grid has only one Hub and it is launched on a single machine once." }, { "code": null, "e": 34488, "s": 34274, "text": "Node − Nodes are the Selenium instances that are attached to the Hub which execute the tests. There can be one or more nodes in a grid which can be of any OS and can contain any of the Selenium supported browsers." }, { "code": null, "e": 34702, "s": 34488, "text": "Node − Nodes are the Selenium instances that are attached to the Hub which execute the tests. There can be one or more nodes in a grid which can be of any OS and can contain any of the Selenium supported browsers." }, { "code": null, "e": 34765, "s": 34702, "text": "The following diagram shows the architecture of Selenium Grid." }, { "code": null, "e": 34894, "s": 34765, "text": "In order to work with the Grid, we need to follow certain protocols. Listen below are the major steps involved in this process −" }, { "code": null, "e": 34914, "s": 34894, "text": "Configuring the Hub" }, { "code": null, "e": 34936, "s": 34914, "text": "Configuring the Nodes" }, { "code": null, "e": 34980, "s": 34936, "text": "Develop the Script and Prepare the XML File" }, { "code": null, "e": 34995, "s": 34980, "text": "Test Execution" }, { "code": null, "e": 35011, "s": 34995, "text": "Result Analysis" }, { "code": null, "e": 35057, "s": 35011, "text": "Let us discuss each of these steps in detail." }, { "code": null, "e": 35220, "s": 35057, "text": "Step 1 − Download the latest Selenium Server standalone JAR file from http://docs.seleniumhq.org/download/. Download it by clicking on the version as shown below." }, { "code": null, "e": 35355, "s": 35220, "text": "Step 2 − Start the Hub by launching the Selenium Server using the following command. Now we will use the port '4444' to start the hub." }, { "code": null, "e": 35438, "s": 35355, "text": "Note − Ensure that there are no other applications that are running on port# 4444." }, { "code": null, "e": 35525, "s": 35438, "text": "java -jar selenium-server-standalone-2.25.0.jar -port 4444 -role hub -nodeTimeout 1000" }, { "code": null, "e": 35658, "s": 35525, "text": "Step 3 − Now open the browser and navigate to the URL http//localhost:4444 from the Hub (The system where you have executed Step#2)." }, { "code": null, "e": 35860, "s": 35658, "text": "Step 4 − Now click on the 'console' link and click 'view config'. The config of the hub would be displayed as follows. As of now, we haven't got any nodes, hence we will not be able to see the details." }, { "code": null, "e": 36078, "s": 35860, "text": "Step 1 − Logon to the node (where you would like to execute the scripts) and place the 'selenium-server-standalone-2.42.2' in a folder. We need to point to the selenium-server-standalone JAR while launching the nodes." }, { "code": null, "e": 36142, "s": 36078, "text": "Step 2 − Launch FireFox Node using the following below command." }, { "code": null, "e": 36302, "s": 36142, "text": "java -jar D:\\JAR\\selenium-server-standalone-2.42.2.jar\n -role node -hub http://10.30.217.157:4444/grid/register\n -browser browserName = firefox -port 5555\n" }, { "code": null, "e": 36309, "s": 36302, "text": "Where," }, { "code": null, "e": 36429, "s": 36309, "text": "D:\\JAR\\selenium-server-standalone-2.42.2.jar = Location of the Selenium Server Standalone Jar File(on the Node Machine)" }, { "code": null, "e": 36511, "s": 36429, "text": "http://10.30.217.157:4444 = IP Address of the Hub and 4444 is the port of the Hub" }, { "code": null, "e": 36582, "s": 36511, "text": "browserName = firefox (Parameter to specify the Browser name on Nodes)" }, { "code": null, "e": 36641, "s": 36582, "text": "5555 = Port on which Firefox Node would be up and running." }, { "code": null, "e": 36804, "s": 36641, "text": "Step 3 − After executing the command, come back to the Hub. Navigate to the URL - http://10.30.217.157:4444 and the Hub would now display the node attached to it." }, { "code": null, "e": 36963, "s": 36804, "text": "Step 4 − Now let us launch the Internet Explorer Node. For launching the IE Node, we need to have the Internet Explorer driver downloaded on the node machine." }, { "code": null, "e": 37257, "s": 36963, "text": "Step 5 − To download the Internet Explorer driver, navigate to http://docs.seleniumhq.org/download/ and download the appropriate file based on the architecture of your OS. After you have downloaded, unzip the exe file and place in it a folder which has to be referred while launching IE nodes." }, { "code": null, "e": 37305, "s": 37257, "text": "Step 6 − Launch IE using the following command." }, { "code": null, "e": 37537, "s": 37305, "text": "C:\\>java -Dwebdriver.ie.driver = D:\\IEDriverServer.exe\n -jar D:\\JAR\\selenium-server-standalone-2.42.2.jar\n -role webdriver -hub http://10.30.217.157:4444/grid/register\n -browser browserName = ie,platform = WINDOWS -port 5558\n" }, { "code": null, "e": 37544, "s": 37537, "text": "Where," }, { "code": null, "e": 37634, "s": 37544, "text": "D:\\IEDriverServer.exe = The location of the downloaded the IE Driver(on the Node Machine)" }, { "code": null, "e": 37754, "s": 37634, "text": "D:\\JAR\\selenium-server-standalone-2.42.2.jar = Location of the Selenium Server Standalone Jar File(on the Node Machine)" }, { "code": null, "e": 37836, "s": 37754, "text": "http://10.30.217.157:4444 = IP Address of the Hub and 4444 is the port of the Hub" }, { "code": null, "e": 37902, "s": 37836, "text": "browserName = ie (Parameter to specify the Browser name on Nodes)" }, { "code": null, "e": 37956, "s": 37902, "text": "5558 = Port on which IE Node would be up and running." }, { "code": null, "e": 38122, "s": 37956, "text": "Step 7 − After executing the command, come back to the Hub. Navigate to the URL - http://10.30.217.157:4444 and the Hub would now display the IE node attached to it." }, { "code": null, "e": 38259, "s": 38122, "text": "Step 8 − Let us now launch Chrome Node. For launching the Chrome Node, we need to have the Chrome driver downloaded on the node machine." }, { "code": null, "e": 38457, "s": 38259, "text": "Step 9 − To download the Chrome Driver, navigate to http://docs.seleniumhq.org/download/ and then navigate to Third Party Browser Drivers area and click on the version number '2.10' as shown below." }, { "code": null, "e": 38736, "s": 38457, "text": "Step 10 − Download the driver based on the type of your OS. We will execute it on Windows environment, hence we will download the Windows Chrome Driver. After you have downloaded, unzip the exe file and place it in a folder which has to be referred while launching chrome nodes." }, { "code": null, "e": 38789, "s": 38736, "text": "Step 11 − Launch Chrome using the following command." }, { "code": null, "e": 39032, "s": 38789, "text": "C:\\>java -Dwebdriver.chrome.driver = D:\\chromedriver.exe \n -jar D:\\JAR\\selenium-server-standalone-2.42.2.jar \n -role webdriver -hub http://10.30.217.157:4444/grid/register \n -browser browserName = chrome, platform = WINDOWS -port 5557\n" }, { "code": null, "e": 39039, "s": 39032, "text": "Where," }, { "code": null, "e": 39131, "s": 39039, "text": "D:\\chromedriver.exe = The location of the downloaded the chrome Driver(on the Node Machine)" }, { "code": null, "e": 39251, "s": 39131, "text": "D:\\JAR\\selenium-server-standalone-2.42.2.jar = Location of the Selenium Server Standalone Jar File(on the Node Machine)" }, { "code": null, "e": 39333, "s": 39251, "text": "http://10.30.217.157:4444 = IP Address of the Hub and 4444 is the port of the Hub" }, { "code": null, "e": 39403, "s": 39333, "text": "browserName = chrome (Parameter to specify the Browser name on Nodes)" }, { "code": null, "e": 39461, "s": 39403, "text": "5557 = Port on which chrome Node would be up and running." }, { "code": null, "e": 39632, "s": 39461, "text": "Step 12 − After executing the command, come back to the Hub. Navigate to the URL - http://10.30.217.157:4444 and the Hub would now display the chrome node attached to it." }, { "code": null, "e": 39878, "s": 39632, "text": "Step 1 − We will develop a test using TestNG. In the following example, we will launch each one of those browsers using remote webDriver. It can pass on their capabilities to the driver so that the driver has all information to execute on Nodes." }, { "code": null, "e": 39937, "s": 39878, "text": "The Browser Parameter would be passed from the \"XML\" file." }, { "code": null, "e": 43638, "s": 39937, "text": "package TestNG;\n\nimport org.openqa.selenium.*;\nimport org.openqa.selenium.remote.RemoteWebDriver;\nimport org.openqa.selenium.remote.DesiredCapabilities;\n\nimport org.testng.annotations.AfterTest;\nimport org.testng.annotations.BeforeTest;\nimport org.testng.annotations.Parameters;\nimport org.testng.annotations.Test;\n\nimport java.net.URL;\nimport java.util.concurrent.TimeUnit;\nimport java.net.MalformedURLException;\n\npublic class TestNGClass {\n public WebDriver driver;\n public String URL, Node;\n protected ThreadLocal<RemoteWebDriver> threadDriver = null;\n \n @Parameters(\"browser\")\n @BeforeTest\n public void launchapp(String browser) throws MalformedURLException {\n String URL = \"http://www.calculator.net\";\n \n if (browser.equalsIgnoreCase(\"firefox\")) {\n System.out.println(\" Executing on FireFox\");\n String Node = \"http://10.112.66.52:5555/wd/hub\";\n DesiredCapabilities cap = DesiredCapabilities.firefox();\n cap.setBrowserName(\"firefox\");\n \n driver = new RemoteWebDriver(new URL(Node), cap);\n // Puts an Implicit wait, Will wait for 10 seconds before throwing exception\n driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);\n \n // Launch website\n driver.navigate().to(URL);\n driver.manage().window().maximize();\n } else if (browser.equalsIgnoreCase(\"chrome\")) {\n System.out.println(\" Executing on CHROME\");\n DesiredCapabilities cap = DesiredCapabilities.chrome();\n cap.setBrowserName(\"chrome\");\n String Node = \"http://10.112.66.52:5557/wd/hub\";\n driver = new RemoteWebDriver(new URL(Node), cap);\n driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);\n \n // Launch website\n driver.navigate().to(URL);\n driver.manage().window().maximize();\n } else if (browser.equalsIgnoreCase(\"ie\")) {\n System.out.println(\" Executing on IE\");\n DesiredCapabilities cap = DesiredCapabilities.chrome();\n cap.setBrowserName(\"ie\");\n String Node = \"http://10.112.66.52:5558/wd/hub\";\n driver = new RemoteWebDriver(new URL(Node), cap);\n driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);\n \n // Launch website\n driver.navigate().to(URL);\n driver.manage().window().maximize();\n } else {\n throw new IllegalArgumentException(\"The Browser Type is Undefined\");\n }\n }\n \n @Test\n public void calculatepercent() {\n // Click on Math Calculators\n driver.findElement(By.xpath(\".//*[@id = 'menu']/div[3]/a\")).click(); \t\n \n // Click on Percent Calculators\n driver.findElement(By.xpath(\".//*[@id = 'menu']/div[4]/div[3]/a\")).click();\n \n // Enter value 10 in the first number of the percent Calculator\n driver.findElement(By.id(\"cpar1\")).sendKeys(\"10\");\n \n // Enter value 50 in the second number of the percent Calculator\n driver.findElement(By.id(\"cpar2\")).sendKeys(\"50\");\n \n // Click Calculate Button\n // driver.findElement(By.xpath(\".//*[@id = 'content']/table/tbody/tr/td[2]/input\")).click();\n // Get the Result Text based on its xpath\n String result =\n driver.findElement(By.xpath(\".//*[@id = 'content']/p[2]/span/font/b\")).getText();\n \n // Print a Log In message to the screen\n System.out.println(\" The Result is \" + result);\n \n if(result.equals(\"5\")) {\n System.out.println(\" The Result is Pass\");\n } else {\n System.out.println(\" The Result is Fail\");\n }\n }\n \n @AfterTest\n public void closeBrowser() {\n driver.quit();\n }\n}" }, { "code": null, "e": 43735, "s": 43638, "text": "Step 2 − The Browser parameter will be passed using XML. Create an XML under the project folder." }, { "code": null, "e": 43791, "s": 43735, "text": "Step 3 − Select 'File' from 'General' and click 'Next'." }, { "code": null, "e": 43847, "s": 43791, "text": "Step 4 − Enter the name of the file and click 'Finish'." }, { "code": null, "e": 43919, "s": 43847, "text": "Step 5 − TestNg.XML is created under the project folder as shown below." }, { "code": null, "e": 44098, "s": 43919, "text": "Step 6 − The contents of the XML file are shown below. We create 3 tests and put them in a suite and mention parallel=\"tests\" so that all the tests would be executed in parallel." }, { "code": null, "e": 44768, "s": 44098, "text": "<?xml version = \"1.0\" encoding = \"UTF-8\"?>\n<!DOCTYPE suite SYSTEM \"http://testng.org/testng-1.0.dtd\">\n<suite name = \"Suite\" parallel = \"tests\">\n\n <test name = \"FirefoxTest\">\n <parameter name = \"browser\" value = \"firefox\" />\n <classes>\n <class name = \"TestNG.TestNGClass\" />\n </classes>\n </test>\n\n <test name = \"ChromeTest\">\n <parameter name = \"browser\" value = \"chrome\" />\n <classes>\n <class name = \"TestNG.TestNGClass\" />\n </classes>\n </test>\n\n <test name = \"IETest\">\n <parameter name = \"browser\" value = \"ie\" />\n <classes>\n <class name = \"TestNG.TestNGClass\" />\n </classes>\n </test>\n \n</suite>" }, { "code": null, "e": 44852, "s": 44768, "text": "Step 1 − Select the created XML; right-click and choose 'Run As' >> 'TestNG Suite'." }, { "code": null, "e": 44991, "s": 44852, "text": "Step 2 − Now open the Node, where we have launched all the browser nodes. You will see all the three browsers in execution simultaneously." }, { "code": null, "e": 45164, "s": 44991, "text": "Step 1 − Upon completing the execution, we can analyze the result like any other execution. The result summary is printed in the console as shown in the following snapshot." }, { "code": null, "e": 45280, "s": 45164, "text": "Step 2 − Navigate to the 'Results of Running Suite' Tab and TestNG would display the result summary as shown below." }, { "code": null, "e": 45371, "s": 45280, "text": "Step 3 − Upon generating the HTML, we will be able to see the test results in HTML format." }, { "code": null, "e": 45406, "s": 45371, "text": "\n 46 Lectures \n 5.5 hours \n" }, { "code": null, "e": 45418, "s": 45406, "text": " Aditya Dua" }, { "code": null, "e": 45454, "s": 45418, "text": "\n 296 Lectures \n 146 hours \n" }, { "code": null, "e": 45468, "s": 45454, "text": " Arun Motoori" }, { "code": null, "e": 45505, "s": 45468, "text": "\n 411 Lectures \n 38.5 hours \n" }, { "code": null, "e": 45527, "s": 45505, "text": " In28Minutes Official" }, { "code": null, "e": 45560, "s": 45527, "text": "\n 22 Lectures \n 7 hours \n" }, { "code": null, "e": 45574, "s": 45560, "text": " Arun Motoori" }, { "code": null, "e": 45609, "s": 45574, "text": "\n 118 Lectures \n 17 hours \n" }, { "code": null, "e": 45623, "s": 45609, "text": " Arun Motoori" }, { "code": null, "e": 45660, "s": 45623, "text": "\n 278 Lectures \n 38.5 hours \n" }, { "code": null, "e": 45674, "s": 45660, "text": " Lets Kode It" }, { "code": null, "e": 45681, "s": 45674, "text": " Print" }, { "code": null, "e": 45692, "s": 45681, "text": " Add Notes" } ]
SQLite - Arithmetic Operators
Following are some simple examples showing the usage of SQLite Arithmetic Operators − sqlite> .mode line sqlite> select 10 + 20; 10 + 20 = 30 sqlite> select 10 - 20; 10 - 20 = -10 sqlite> select 10 * 20; 10 * 20 = 200 sqlite> select 10 / 5; 10 / 5 = 2 sqlite> select 12 % 5; 12 % 5 = 2 25 Lectures 4.5 hours Sandip Bhattacharya 17 Lectures 1 hours Laurence Svekis 5 Lectures 51 mins Vinay Kumar Print Add Notes Bookmark this page
[ { "code": null, "e": 2724, "s": 2638, "text": "Following are some simple examples showing the usage of SQLite Arithmetic Operators −" }, { "code": null, "e": 2930, "s": 2724, "text": "sqlite> .mode line\nsqlite> select 10 + 20;\n10 + 20 = 30\n\nsqlite> select 10 - 20;\n10 - 20 = -10\n\nsqlite> select 10 * 20;\n10 * 20 = 200\n\nsqlite> select 10 / 5;\n10 / 5 = 2\n\nsqlite> select 12 % 5;\n12 % 5 = 2" }, { "code": null, "e": 2965, "s": 2930, "text": "\n 25 Lectures \n 4.5 hours \n" }, { "code": null, "e": 2986, "s": 2965, "text": " Sandip Bhattacharya" }, { "code": null, "e": 3019, "s": 2986, "text": "\n 17 Lectures \n 1 hours \n" }, { "code": null, "e": 3036, "s": 3019, "text": " Laurence Svekis" }, { "code": null, "e": 3067, "s": 3036, "text": "\n 5 Lectures \n 51 mins\n" }, { "code": null, "e": 3080, "s": 3067, "text": " Vinay Kumar" }, { "code": null, "e": 3087, "s": 3080, "text": " Print" }, { "code": null, "e": 3098, "s": 3087, "text": " Add Notes" } ]
Count number of binary strings without consecutive 1's - GeeksforGeeks
17 Nov, 2021 Given a positive integer N, count all possible distinct binary strings of length N such that there are no consecutive 1’s. Examples: Input: N = 2 Output: 3 // The 3 strings are 00, 01, 10 Input: N = 3 Output: 5 // The 5 strings are 000, 001, 010, 100, 101 This problem can be solved using Dynamic Programming. Let a[i] be the number of binary strings of length i which do not contain any two consecutive 1’s and which end in 0. Similarly, let b[i] be the number of such strings which end in 1. We can append either 0 or 1 to a string ending in 0, but we can only append 0 to a string ending in 1. This yields the recurrence relation: a[i] = a[i - 1] + b[i - 1] b[i] = a[i - 1] The base cases of above recurrence are a[1] = b[1] = 1. The total number of strings of length i is just a[i] + b[i].Following is the implementation of above solution. In the following implementation, indexes start from 0. So a[i] represents the number of binary strings for input length i+1. Similarly, b[i] represents binary strings for input length i+1. C++ Java Python3 C# PHP Javascript // C++ program to count all distinct binary strings// without two consecutive 1's#include <iostream>using namespace std; int countStrings(int n){ int a[n], b[n]; a[0] = b[0] = 1; for (int i = 1; i < n; i++) { a[i] = a[i-1] + b[i-1]; b[i] = a[i-1]; } return a[n-1] + b[n-1];} // Driver program to test above functionsint main(){ cout << countStrings(3) << endl; return 0;} class Subset_sum{ static int countStrings(int n) { int a[] = new int [n]; int b[] = new int [n]; a[0] = b[0] = 1; for (int i = 1; i < n; i++) { a[i] = a[i-1] + b[i-1]; b[i] = a[i-1]; } return a[n-1] + b[n-1]; } /* Driver program to test above function */ public static void main (String args[]) { System.out.println(countStrings(3)); }}/* This code is contributed by Rajat Mishra */ # Python program to count# all distinct binary strings# without two consecutive 1's def countStrings(n): a=[0 for i in range(n)] b=[0 for i in range(n)] a[0] = b[0] = 1 for i in range(1,n): a[i] = a[i-1] + b[i-1] b[i] = a[i-1] return a[n-1] + b[n-1] # Driver program to test# above functions print(countStrings(3)) # This code is contributed# by Anant Agarwal. // C# program to count all distinct binary// strings without two consecutive 1'susing System; class Subset_sum{ static int countStrings(int n) { int []a = new int [n]; int []b = new int [n]; a[0] = b[0] = 1; for (int i = 1; i < n; i++) { a[i] = a[i-1] + b[i-1]; b[i] = a[i-1]; } return a[n-1] + b[n-1]; } // Driver Code public static void Main () { Console.Write(countStrings(3)); }} // This code is contributed by nitin mittal <?php// PHP program to count all distinct// binary stringswithout two// consecutive 1's function countStrings($n){ $a[$n] = 0; $b[$n] = 0; $a[0] = $b[0] = 1; for ($i = 1; $i < $n; $i++) { $a[$i] = $a[$i - 1] + $b[$i - 1]; $b[$i] = $a[$i - 1]; } return $a[$n - 1] + $b[$n - 1];} // Driver Code echo countStrings(3) ; // This code is contributed by nitin mittal?> <script> // JavaScript program to count all// distinct binary strings// without two consecutive 1'sfunction countStrings(n){ let a = []; let b = []; a[0] = b[0] = 1; for(let i = 1; i < n; i++) { a[i] = a[i - 1] + b[i - 1]; b[i] = a[i - 1]; } return a[n - 1] + b[n - 1];} // Driver codedocument.write(countStrings(3)); // This code is contributed by rohan07 </script> Output: 5 Time Complexity: O(N) Auxiliary Space: O(N)Source: courses.csail.mit.edu/6.006/oldquizzes/solutions/q2-f2009-sol.pdfIf we take a closer look at the pattern, we can observe that the count is actually (n+2)’th Fibonacci number for n >= 1. The Fibonacci Numbers are 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 141, .... n = 1, count = 2 = fib(3) n = 2, count = 3 = fib(4) n = 3, count = 5 = fib(5) n = 4, count = 8 = fib(6) n = 5, count = 13 = fib(7) ................ Therefore we can count the strings in O(Log n) time also using the method 5 here. Related Post : 1 to n bit numbers with no consecutive 1s in binary representation.This article is contributed by Rahul Jain. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above nitin mittal jit_t rohan07 binary-string Fibonacci Flipkart Microsoft Morgan Stanley Snapdeal Arrays Dynamic Programming Flipkart Morgan Stanley Microsoft Snapdeal Arrays Dynamic Programming Fibonacci Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Introduction to Arrays Python | Using 2D arrays/lists the right way Linked List vs Array Given an array of size n and a number k, find all elements that appear more than n/k times Queue | Set 1 (Introduction and Array Implementation) 0-1 Knapsack Problem | DP-10 Program for Fibonacci numbers Longest Common Subsequence | DP-4 Longest Increasing Subsequence | DP-3 Bellman–Ford Algorithm | DP-23
[ { "code": null, "e": 24749, "s": 24721, "text": "\n17 Nov, 2021" }, { "code": null, "e": 24872, "s": 24749, "text": "Given a positive integer N, count all possible distinct binary strings of length N such that there are no consecutive 1’s." }, { "code": null, "e": 24883, "s": 24872, "text": "Examples: " }, { "code": null, "e": 25008, "s": 24883, "text": "Input: N = 2\nOutput: 3\n// The 3 strings are 00, 01, 10\n\nInput: N = 3\nOutput: 5\n// The 5 strings are 000, 001, 010, 100, 101" }, { "code": null, "e": 25387, "s": 25008, "text": "This problem can be solved using Dynamic Programming. Let a[i] be the number of binary strings of length i which do not contain any two consecutive 1’s and which end in 0. Similarly, let b[i] be the number of such strings which end in 1. We can append either 0 or 1 to a string ending in 0, but we can only append 0 to a string ending in 1. This yields the recurrence relation: " }, { "code": null, "e": 25431, "s": 25387, "text": "a[i] = a[i - 1] + b[i - 1]\nb[i] = a[i - 1] " }, { "code": null, "e": 25787, "s": 25431, "text": "The base cases of above recurrence are a[1] = b[1] = 1. The total number of strings of length i is just a[i] + b[i].Following is the implementation of above solution. In the following implementation, indexes start from 0. So a[i] represents the number of binary strings for input length i+1. Similarly, b[i] represents binary strings for input length i+1." }, { "code": null, "e": 25791, "s": 25787, "text": "C++" }, { "code": null, "e": 25796, "s": 25791, "text": "Java" }, { "code": null, "e": 25804, "s": 25796, "text": "Python3" }, { "code": null, "e": 25807, "s": 25804, "text": "C#" }, { "code": null, "e": 25811, "s": 25807, "text": "PHP" }, { "code": null, "e": 25822, "s": 25811, "text": "Javascript" }, { "code": "// C++ program to count all distinct binary strings// without two consecutive 1's#include <iostream>using namespace std; int countStrings(int n){ int a[n], b[n]; a[0] = b[0] = 1; for (int i = 1; i < n; i++) { a[i] = a[i-1] + b[i-1]; b[i] = a[i-1]; } return a[n-1] + b[n-1];} // Driver program to test above functionsint main(){ cout << countStrings(3) << endl; return 0;}", "e": 26233, "s": 25822, "text": null }, { "code": "class Subset_sum{ static int countStrings(int n) { int a[] = new int [n]; int b[] = new int [n]; a[0] = b[0] = 1; for (int i = 1; i < n; i++) { a[i] = a[i-1] + b[i-1]; b[i] = a[i-1]; } return a[n-1] + b[n-1]; } /* Driver program to test above function */ public static void main (String args[]) { System.out.println(countStrings(3)); }}/* This code is contributed by Rajat Mishra */", "e": 26718, "s": 26233, "text": null }, { "code": "# Python program to count# all distinct binary strings# without two consecutive 1's def countStrings(n): a=[0 for i in range(n)] b=[0 for i in range(n)] a[0] = b[0] = 1 for i in range(1,n): a[i] = a[i-1] + b[i-1] b[i] = a[i-1] return a[n-1] + b[n-1] # Driver program to test# above functions print(countStrings(3)) # This code is contributed# by Anant Agarwal.", "e": 27114, "s": 26718, "text": null }, { "code": "// C# program to count all distinct binary// strings without two consecutive 1'susing System; class Subset_sum{ static int countStrings(int n) { int []a = new int [n]; int []b = new int [n]; a[0] = b[0] = 1; for (int i = 1; i < n; i++) { a[i] = a[i-1] + b[i-1]; b[i] = a[i-1]; } return a[n-1] + b[n-1]; } // Driver Code public static void Main () { Console.Write(countStrings(3)); }} // This code is contributed by nitin mittal", "e": 27646, "s": 27114, "text": null }, { "code": "<?php// PHP program to count all distinct// binary stringswithout two// consecutive 1's function countStrings($n){ $a[$n] = 0; $b[$n] = 0; $a[0] = $b[0] = 1; for ($i = 1; $i < $n; $i++) { $a[$i] = $a[$i - 1] + $b[$i - 1]; $b[$i] = $a[$i - 1]; } return $a[$n - 1] + $b[$n - 1];} // Driver Code echo countStrings(3) ; // This code is contributed by nitin mittal?>", "e": 28076, "s": 27646, "text": null }, { "code": "<script> // JavaScript program to count all// distinct binary strings// without two consecutive 1'sfunction countStrings(n){ let a = []; let b = []; a[0] = b[0] = 1; for(let i = 1; i < n; i++) { a[i] = a[i - 1] + b[i - 1]; b[i] = a[i - 1]; } return a[n - 1] + b[n - 1];} // Driver codedocument.write(countStrings(3)); // This code is contributed by rohan07 </script>", "e": 28483, "s": 28076, "text": null }, { "code": null, "e": 28492, "s": 28483, "text": "Output: " }, { "code": null, "e": 28494, "s": 28492, "text": "5" }, { "code": null, "e": 28516, "s": 28494, "text": "Time Complexity: O(N)" }, { "code": null, "e": 28809, "s": 28516, "text": "Auxiliary Space: O(N)Source: courses.csail.mit.edu/6.006/oldquizzes/solutions/q2-f2009-sol.pdfIf we take a closer look at the pattern, we can observe that the count is actually (n+2)’th Fibonacci number for n >= 1. The Fibonacci Numbers are 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 141, .... " }, { "code": null, "e": 28961, "s": 28809, "text": "n = 1, count = 2 = fib(3)\nn = 2, count = 3 = fib(4)\nn = 3, count = 5 = fib(5)\nn = 4, count = 8 = fib(6)\nn = 5, count = 13 = fib(7)\n................" }, { "code": null, "e": 29043, "s": 28961, "text": "Therefore we can count the strings in O(Log n) time also using the method 5 here." }, { "code": null, "e": 29293, "s": 29043, "text": "Related Post : 1 to n bit numbers with no consecutive 1s in binary representation.This article is contributed by Rahul Jain. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above " }, { "code": null, "e": 29306, "s": 29293, "text": "nitin mittal" }, { "code": null, "e": 29312, "s": 29306, "text": "jit_t" }, { "code": null, "e": 29320, "s": 29312, "text": "rohan07" }, { "code": null, "e": 29334, "s": 29320, "text": "binary-string" }, { "code": null, "e": 29344, "s": 29334, "text": "Fibonacci" }, { "code": null, "e": 29353, "s": 29344, "text": "Flipkart" }, { "code": null, "e": 29363, "s": 29353, "text": "Microsoft" }, { "code": null, "e": 29378, "s": 29363, "text": "Morgan Stanley" }, { "code": null, "e": 29387, "s": 29378, "text": "Snapdeal" }, { "code": null, "e": 29394, "s": 29387, "text": "Arrays" }, { "code": null, "e": 29414, "s": 29394, "text": "Dynamic Programming" }, { "code": null, "e": 29423, "s": 29414, "text": "Flipkart" }, { "code": null, "e": 29438, "s": 29423, "text": "Morgan Stanley" }, { "code": null, "e": 29448, "s": 29438, "text": "Microsoft" }, { "code": null, "e": 29457, "s": 29448, "text": "Snapdeal" }, { "code": null, "e": 29464, "s": 29457, "text": "Arrays" }, { "code": null, "e": 29484, "s": 29464, "text": "Dynamic Programming" }, { "code": null, "e": 29494, "s": 29484, "text": "Fibonacci" }, { "code": null, "e": 29592, "s": 29494, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29601, "s": 29592, "text": "Comments" }, { "code": null, "e": 29614, "s": 29601, "text": "Old Comments" }, { "code": null, "e": 29637, "s": 29614, "text": "Introduction to Arrays" }, { "code": null, "e": 29682, "s": 29637, "text": "Python | Using 2D arrays/lists the right way" }, { "code": null, "e": 29703, "s": 29682, "text": "Linked List vs Array" }, { "code": null, "e": 29794, "s": 29703, "text": "Given an array of size n and a number k, find all elements that appear more than n/k times" }, { "code": null, "e": 29848, "s": 29794, "text": "Queue | Set 1 (Introduction and Array Implementation)" }, { "code": null, "e": 29877, "s": 29848, "text": "0-1 Knapsack Problem | DP-10" }, { "code": null, "e": 29907, "s": 29877, "text": "Program for Fibonacci numbers" }, { "code": null, "e": 29941, "s": 29907, "text": "Longest Common Subsequence | DP-4" }, { "code": null, "e": 29979, "s": 29941, "text": "Longest Increasing Subsequence | DP-3" } ]
Uplift Modeling. Maximizing the incremental return of... | by Barış Karaman | Towards Data Science
This series of articles was designed to explain how to use Python in a simplistic way to fuel your company’s growth by applying the predictive approach to all your actions. It will be a combination of programming, data analysis, and machine learning. I will cover all the topics in the following nine articles: 1- Know Your Metrics 2- Customer Segmentation 3- Customer Lifetime Value Prediction 4- Churn Prediction 5- Predicting Next Purchase Day 6- Predicting Sales 7- Market Response Models 8- Uplift Modeling 9- A/B Testing Design and Execution Articles will have their own code snippets to make you easily apply them. If you are super new to programming, you can have a good introduction for Python and Pandas (a famous library that we will use on everything) here. But still without a coding introduction, you can learn the concepts, how to use your data and start generating value out of it: Sometimes you gotta run before you can walk — Tony Stark As a pre-requisite, be sure Jupyter Notebook and Python are installed on your computer. The code snippets will run on Jupyter Notebook only. Alright, let’s start. One of the most critical jobs of Growth Hacker is to be efficient by all means as much as possible. First of all, you need to be time-efficient. That means you have to quickly ideate, experiment, learn and re-iterate. Second, you need to be cost-efficient. It means bringing the maximum return for a given budget/time/effort. Segmentation helps Growth Hackers to increase conversion and hence be cost-efficient. But imagine a case that you are about to launch a promotional campaign and you know which segment you want to target. Do you need to send the offer to everyone? The answer is no. In your current target group, there will be customers who are going to purchase anyways. You will cannibalize yourself by giving the promotion. We can summarize the segments based on this approach like below: Treatment Responders: Customers that will purchase only if they receive an offer Treatment Non-Responders: Customer that won’t purchase in any case Control Responders: Customers that will purchase without an offer Control Non-Responders: Customers that will not purchase if they don’t receive an offer The picture is very obvious. You need to target Treatment Responders (TR) and Control Non-Responders (CN). Since they won’t purchase unless you give an offer, these groups are boosting your uplift in promotional campaigns. On the other hand, you need to avoid targeting Treatment Non-Responders (TN) and Control Responders (CR). You will not benefit from targeting TN and, CN will make you cannibalize. There is one last simple thing to do. We need to identify which customers fall into which buckets. The answer is Uplift Modeling. It has two simple steps: 1- Predict the probabilities of being in each group for all customers: we are going to build a multi-classification model for that. 2- We will calculate the uplift score. Uplift score formula is: We will sum up the probability of being TR and CN and subtract the probability of falling into other buckets. The higher score means higher uplift. Alright, let’s see how we can implement this with an example. We will be using the same dataset in the previous article that you can find here. We start with importing the libraries and functions we need: Then we will import our data: df_data = pd.read_csv('response_data.csv')df_data.head(10) As you can recall from the previous article, we have the data of customers who received Discount and Buy One Get One offers and how they reacted. We also have a control group that didn’t receive anything. Column descriptions are as follows: recency: months since last purchase history: $value of the historical purchases used_discount/used_bogo: indicates if the customer used a discount or buy one get one before zip_code: class of the zip code as Suburban/Urban/Rural is_referral: indicates if the customer was acquired from referral channel channel: channels that the customer using, Phone/Web/Multichannel offer: the offers sent to the customers, Discount/But One Get One/No Offer Before building the model, let’s apply our calc_uplift function to see the current uplift of this campaign as a benchmark: calc_uplift(df_data) Conversion uplift is 7.66% for discount and 4.52% for buy one get one (BOGO). Next, we will start building our model. Currently, our label is if a customer converted or not (1 or 0). We need to create four classes for TR, TN, CR, and CN. We know that the customers who received discount and bogo offers are Treatment and the rest is control. Let’s create a campaign_group column make this info visible: df_data['campaign_group'] = 'treatment'df_data.loc[df_data.offer == 'No Offer', 'campaign_group'] = 'control' Perfect, now we need to create our new labels: df_data['target_class'] = 0 #CNdf_data.loc[(df_data.campaign_group == 'control') & (df_data.conversion > 0),'target_class'] = 1 #CRdf_data.loc[(df_data.campaign_group == 'treatment') & (df_data.conversion == 0),'target_class'] = 2 #TNdf_data.loc[(df_data.campaign_group == 'treatment') & (df_data.conversion > 0),'target_class'] = 3 #TR In this example, the mapping of the classes are below: 0 -> Control Non-Responders 1 -> Control Responders 2 -> Treatment Non-Responders 3 -> Treatment Responders There is one small feature engineering step before training our model. We will create clusters from history column and apply get_dummies for converting categorical columns into numerical: #creating the clusterskmeans = KMeans(n_clusters=5)kmeans.fit(df_data[['history']])df_data['history_cluster'] = kmeans.predict(df_data[['history']])#order the clustersdf_data = order_cluster('history_cluster', 'history',df_data,True)#creating a new dataframe as model and dropping columns that defines the labeldf_model = df_data.drop(['offer','campaign_group','conversion'],axis=1)#convert categorical columnsdf_model = pd.get_dummies(df_model) Let’s fit our model and get the probabilities for each class: #create feature set and labelsX = df_model.drop(['target_class'],axis=1)y = df_model.target_class#splitting train and test groupsX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=56)#fitting the model and predicting the probabilitiesxgb_model = xgb.XGBClassifier().fit(X_train, y_train)class_probs = xgb_model.predict_proba(X_test) Variable class_probs possesses the probabilities for each customer. Let’s check out an example: For this specific customer, we can map the probabilities as below: CN: 32% CR: 2% TN: 58.9% TR: 6.9% So the uplift score for this customer is: 0.32 + 0.069- 0.02- 0.589 = -0.22 Let’s apply this to all users and calculate the uplift score: #probabilities for all customersoverall_proba = xgb_model.predict_proba(df_model.drop(['target_class'],axis=1))#assign probabilities to 4 different columnsdf_model['proba_CN'] = overall_proba[:,0] df_model['proba_CR'] = overall_proba[:,1] df_model['proba_TN'] = overall_proba[:,2] df_model['proba_TR'] = overall_proba[:,3]#calculate uplift score for all customersdf_model['uplift_score'] = df_model.eval('proba_CN + proba_TR - proba_TN - proba_CR')#assign it back to main dataframedf_data['uplift_score'] = df_model['uplift_score'] By running the code above, we added a uplift_score column in our main dataframe and it looks like below: It is time to check the most critical part of having this model. Is the model really working? It is a bit hard to evaluate the true performance of uplift modeling. We will check how the uplift is changing across uplift score quantiles to see if we can use the model in real life. To evaluate our model, we will create two different groups and compare them with our benchmark. Groups are: 1- High Uplift Score: Customers have uplift score > 3rd quantile 2- Low Uplift Score: Customers have uplift score < 2nd quantile We are going to compare: Conversion uplift Revenue uplift per target customer to see if our model can make our actions more efficient. Here is our benchmark for the discount campaign. Total Targeted Customer Count: 21307Discount Conversion Uplift: 7.66%Discount Order Uplift: 1631.89Discount Revenue Uplift: $40797.35Revenue Uplift Per Targeted Customer: $1.91 Let’s create the first group and see the numbers: df_data_lift = df_data.copy()uplift_q_75 = df_data_lift.uplift_score.quantile(0.75)df_data_lift = df_data_lift[(df_data_lift.offer != 'Buy One Get One') & (df_data_lift.uplift_score > uplift_q_75)].reset_index(drop=True)#calculate the upliftcalc_uplift(df_data_lift)results:User Count: 5282Discount Conversion Uplift: 12.18%Discount Order Uplift: 643.57Discount Revenue Uplift: $16089.36Revenue Uplift Per Targeted Customer: $3.04 The results are great. Revenue uplift per target customer is 57% better and we can easily see that 25% of the target group is contributing to 40% of the revenue uplift. We will check the same numbers for the group with the lower uplift score: df_data_lift = df_data.copy()uplift_q_5 = df_data_lift.uplift_score.quantile(0.5)df_data_lift = df_data_lift[(df_data_lift.offer != 'Buy One Get One') & (df_data_lift.uplift_score < uplift_q_5)].reset_index(drop=True)#calculate the upliftcalc_uplift(df_data_lift)results:User Count: 10745Discount Conversion Uplift: 5.63%Discount Order Uplift: 604.62Discount Revenue Uplift: $15115.52Revenue Uplift Per Targeted Customer: $1.4 As expected, revenue uplift per targeted customer decreased to $1.4. Moreover, the group is 50% of the targeted customers contributed to 37% of the revenue uplift. By using this model, we can easily make our campaign more efficient by: Targeting specific segments based on the uplift score Trying different offers based on customer’s uplift score In the next article, I’ll be explaining one of the core elements of Growth Hacking: A/B Testing. That will be our final post on this series. You can find the Jupyter Notebook for this article here. To discuss growth marketing & data science, go ahead and book a free session with me here.
[ { "code": null, "e": 423, "s": 172, "text": "This series of articles was designed to explain how to use Python in a simplistic way to fuel your company’s growth by applying the predictive approach to all your actions. It will be a combination of programming, data analysis, and machine learning." }, { "code": null, "e": 483, "s": 423, "text": "I will cover all the topics in the following nine articles:" }, { "code": null, "e": 504, "s": 483, "text": "1- Know Your Metrics" }, { "code": null, "e": 529, "s": 504, "text": "2- Customer Segmentation" }, { "code": null, "e": 567, "s": 529, "text": "3- Customer Lifetime Value Prediction" }, { "code": null, "e": 587, "s": 567, "text": "4- Churn Prediction" }, { "code": null, "e": 619, "s": 587, "text": "5- Predicting Next Purchase Day" }, { "code": null, "e": 639, "s": 619, "text": "6- Predicting Sales" }, { "code": null, "e": 665, "s": 639, "text": "7- Market Response Models" }, { "code": null, "e": 684, "s": 665, "text": "8- Uplift Modeling" }, { "code": null, "e": 720, "s": 684, "text": "9- A/B Testing Design and Execution" }, { "code": null, "e": 1070, "s": 720, "text": "Articles will have their own code snippets to make you easily apply them. If you are super new to programming, you can have a good introduction for Python and Pandas (a famous library that we will use on everything) here. But still without a coding introduction, you can learn the concepts, how to use your data and start generating value out of it:" }, { "code": null, "e": 1127, "s": 1070, "text": "Sometimes you gotta run before you can walk — Tony Stark" }, { "code": null, "e": 1268, "s": 1127, "text": "As a pre-requisite, be sure Jupyter Notebook and Python are installed on your computer. The code snippets will run on Jupyter Notebook only." }, { "code": null, "e": 1290, "s": 1268, "text": "Alright, let’s start." }, { "code": null, "e": 1616, "s": 1290, "text": "One of the most critical jobs of Growth Hacker is to be efficient by all means as much as possible. First of all, you need to be time-efficient. That means you have to quickly ideate, experiment, learn and re-iterate. Second, you need to be cost-efficient. It means bringing the maximum return for a given budget/time/effort." }, { "code": null, "e": 1863, "s": 1616, "text": "Segmentation helps Growth Hackers to increase conversion and hence be cost-efficient. But imagine a case that you are about to launch a promotional campaign and you know which segment you want to target. Do you need to send the offer to everyone?" }, { "code": null, "e": 2090, "s": 1863, "text": "The answer is no. In your current target group, there will be customers who are going to purchase anyways. You will cannibalize yourself by giving the promotion. We can summarize the segments based on this approach like below:" }, { "code": null, "e": 2171, "s": 2090, "text": "Treatment Responders: Customers that will purchase only if they receive an offer" }, { "code": null, "e": 2238, "s": 2171, "text": "Treatment Non-Responders: Customer that won’t purchase in any case" }, { "code": null, "e": 2304, "s": 2238, "text": "Control Responders: Customers that will purchase without an offer" }, { "code": null, "e": 2392, "s": 2304, "text": "Control Non-Responders: Customers that will not purchase if they don’t receive an offer" }, { "code": null, "e": 2795, "s": 2392, "text": "The picture is very obvious. You need to target Treatment Responders (TR) and Control Non-Responders (CN). Since they won’t purchase unless you give an offer, these groups are boosting your uplift in promotional campaigns. On the other hand, you need to avoid targeting Treatment Non-Responders (TN) and Control Responders (CR). You will not benefit from targeting TN and, CN will make you cannibalize." }, { "code": null, "e": 2950, "s": 2795, "text": "There is one last simple thing to do. We need to identify which customers fall into which buckets. The answer is Uplift Modeling. It has two simple steps:" }, { "code": null, "e": 3082, "s": 2950, "text": "1- Predict the probabilities of being in each group for all customers: we are going to build a multi-classification model for that." }, { "code": null, "e": 3146, "s": 3082, "text": "2- We will calculate the uplift score. Uplift score formula is:" }, { "code": null, "e": 3294, "s": 3146, "text": "We will sum up the probability of being TR and CN and subtract the probability of falling into other buckets. The higher score means higher uplift." }, { "code": null, "e": 3438, "s": 3294, "text": "Alright, let’s see how we can implement this with an example. We will be using the same dataset in the previous article that you can find here." }, { "code": null, "e": 3499, "s": 3438, "text": "We start with importing the libraries and functions we need:" }, { "code": null, "e": 3529, "s": 3499, "text": "Then we will import our data:" }, { "code": null, "e": 3588, "s": 3529, "text": "df_data = pd.read_csv('response_data.csv')df_data.head(10)" }, { "code": null, "e": 3793, "s": 3588, "text": "As you can recall from the previous article, we have the data of customers who received Discount and Buy One Get One offers and how they reacted. We also have a control group that didn’t receive anything." }, { "code": null, "e": 3829, "s": 3793, "text": "Column descriptions are as follows:" }, { "code": null, "e": 3865, "s": 3829, "text": "recency: months since last purchase" }, { "code": null, "e": 3909, "s": 3865, "text": "history: $value of the historical purchases" }, { "code": null, "e": 4002, "s": 3909, "text": "used_discount/used_bogo: indicates if the customer used a discount or buy one get one before" }, { "code": null, "e": 4058, "s": 4002, "text": "zip_code: class of the zip code as Suburban/Urban/Rural" }, { "code": null, "e": 4132, "s": 4058, "text": "is_referral: indicates if the customer was acquired from referral channel" }, { "code": null, "e": 4198, "s": 4132, "text": "channel: channels that the customer using, Phone/Web/Multichannel" }, { "code": null, "e": 4273, "s": 4198, "text": "offer: the offers sent to the customers, Discount/But One Get One/No Offer" }, { "code": null, "e": 4396, "s": 4273, "text": "Before building the model, let’s apply our calc_uplift function to see the current uplift of this campaign as a benchmark:" }, { "code": null, "e": 4417, "s": 4396, "text": "calc_uplift(df_data)" }, { "code": null, "e": 4495, "s": 4417, "text": "Conversion uplift is 7.66% for discount and 4.52% for buy one get one (BOGO)." }, { "code": null, "e": 4535, "s": 4495, "text": "Next, we will start building our model." }, { "code": null, "e": 4820, "s": 4535, "text": "Currently, our label is if a customer converted or not (1 or 0). We need to create four classes for TR, TN, CR, and CN. We know that the customers who received discount and bogo offers are Treatment and the rest is control. Let’s create a campaign_group column make this info visible:" }, { "code": null, "e": 4930, "s": 4820, "text": "df_data['campaign_group'] = 'treatment'df_data.loc[df_data.offer == 'No Offer', 'campaign_group'] = 'control'" }, { "code": null, "e": 4977, "s": 4930, "text": "Perfect, now we need to create our new labels:" }, { "code": null, "e": 5314, "s": 4977, "text": "df_data['target_class'] = 0 #CNdf_data.loc[(df_data.campaign_group == 'control') & (df_data.conversion > 0),'target_class'] = 1 #CRdf_data.loc[(df_data.campaign_group == 'treatment') & (df_data.conversion == 0),'target_class'] = 2 #TNdf_data.loc[(df_data.campaign_group == 'treatment') & (df_data.conversion > 0),'target_class'] = 3 #TR" }, { "code": null, "e": 5369, "s": 5314, "text": "In this example, the mapping of the classes are below:" }, { "code": null, "e": 5397, "s": 5369, "text": "0 -> Control Non-Responders" }, { "code": null, "e": 5421, "s": 5397, "text": "1 -> Control Responders" }, { "code": null, "e": 5451, "s": 5421, "text": "2 -> Treatment Non-Responders" }, { "code": null, "e": 5477, "s": 5451, "text": "3 -> Treatment Responders" }, { "code": null, "e": 5665, "s": 5477, "text": "There is one small feature engineering step before training our model. We will create clusters from history column and apply get_dummies for converting categorical columns into numerical:" }, { "code": null, "e": 6111, "s": 5665, "text": "#creating the clusterskmeans = KMeans(n_clusters=5)kmeans.fit(df_data[['history']])df_data['history_cluster'] = kmeans.predict(df_data[['history']])#order the clustersdf_data = order_cluster('history_cluster', 'history',df_data,True)#creating a new dataframe as model and dropping columns that defines the labeldf_model = df_data.drop(['offer','campaign_group','conversion'],axis=1)#convert categorical columnsdf_model = pd.get_dummies(df_model)" }, { "code": null, "e": 6173, "s": 6111, "text": "Let’s fit our model and get the probabilities for each class:" }, { "code": null, "e": 6541, "s": 6173, "text": "#create feature set and labelsX = df_model.drop(['target_class'],axis=1)y = df_model.target_class#splitting train and test groupsX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=56)#fitting the model and predicting the probabilitiesxgb_model = xgb.XGBClassifier().fit(X_train, y_train)class_probs = xgb_model.predict_proba(X_test)" }, { "code": null, "e": 6637, "s": 6541, "text": "Variable class_probs possesses the probabilities for each customer. Let’s check out an example:" }, { "code": null, "e": 6704, "s": 6637, "text": "For this specific customer, we can map the probabilities as below:" }, { "code": null, "e": 6712, "s": 6704, "text": "CN: 32%" }, { "code": null, "e": 6719, "s": 6712, "text": "CR: 2%" }, { "code": null, "e": 6729, "s": 6719, "text": "TN: 58.9%" }, { "code": null, "e": 6738, "s": 6729, "text": "TR: 6.9%" }, { "code": null, "e": 6780, "s": 6738, "text": "So the uplift score for this customer is:" }, { "code": null, "e": 6814, "s": 6780, "text": "0.32 + 0.069- 0.02- 0.589 = -0.22" }, { "code": null, "e": 6876, "s": 6814, "text": "Let’s apply this to all users and calculate the uplift score:" }, { "code": null, "e": 7408, "s": 6876, "text": "#probabilities for all customersoverall_proba = xgb_model.predict_proba(df_model.drop(['target_class'],axis=1))#assign probabilities to 4 different columnsdf_model['proba_CN'] = overall_proba[:,0] df_model['proba_CR'] = overall_proba[:,1] df_model['proba_TN'] = overall_proba[:,2] df_model['proba_TR'] = overall_proba[:,3]#calculate uplift score for all customersdf_model['uplift_score'] = df_model.eval('proba_CN + proba_TR - proba_TN - proba_CR')#assign it back to main dataframedf_data['uplift_score'] = df_model['uplift_score']" }, { "code": null, "e": 7513, "s": 7408, "text": "By running the code above, we added a uplift_score column in our main dataframe and it looks like below:" }, { "code": null, "e": 7793, "s": 7513, "text": "It is time to check the most critical part of having this model. Is the model really working? It is a bit hard to evaluate the true performance of uplift modeling. We will check how the uplift is changing across uplift score quantiles to see if we can use the model in real life." }, { "code": null, "e": 7901, "s": 7793, "text": "To evaluate our model, we will create two different groups and compare them with our benchmark. Groups are:" }, { "code": null, "e": 7966, "s": 7901, "text": "1- High Uplift Score: Customers have uplift score > 3rd quantile" }, { "code": null, "e": 8030, "s": 7966, "text": "2- Low Uplift Score: Customers have uplift score < 2nd quantile" }, { "code": null, "e": 8055, "s": 8030, "text": "We are going to compare:" }, { "code": null, "e": 8073, "s": 8055, "text": "Conversion uplift" }, { "code": null, "e": 8165, "s": 8073, "text": "Revenue uplift per target customer to see if our model can make our actions more efficient." }, { "code": null, "e": 8214, "s": 8165, "text": "Here is our benchmark for the discount campaign." }, { "code": null, "e": 8391, "s": 8214, "text": "Total Targeted Customer Count: 21307Discount Conversion Uplift: 7.66%Discount Order Uplift: 1631.89Discount Revenue Uplift: $40797.35Revenue Uplift Per Targeted Customer: $1.91" }, { "code": null, "e": 8441, "s": 8391, "text": "Let’s create the first group and see the numbers:" }, { "code": null, "e": 8872, "s": 8441, "text": "df_data_lift = df_data.copy()uplift_q_75 = df_data_lift.uplift_score.quantile(0.75)df_data_lift = df_data_lift[(df_data_lift.offer != 'Buy One Get One') & (df_data_lift.uplift_score > uplift_q_75)].reset_index(drop=True)#calculate the upliftcalc_uplift(df_data_lift)results:User Count: 5282Discount Conversion Uplift: 12.18%Discount Order Uplift: 643.57Discount Revenue Uplift: $16089.36Revenue Uplift Per Targeted Customer: $3.04" }, { "code": null, "e": 9041, "s": 8872, "text": "The results are great. Revenue uplift per target customer is 57% better and we can easily see that 25% of the target group is contributing to 40% of the revenue uplift." }, { "code": null, "e": 9115, "s": 9041, "text": "We will check the same numbers for the group with the lower uplift score:" }, { "code": null, "e": 9542, "s": 9115, "text": "df_data_lift = df_data.copy()uplift_q_5 = df_data_lift.uplift_score.quantile(0.5)df_data_lift = df_data_lift[(df_data_lift.offer != 'Buy One Get One') & (df_data_lift.uplift_score < uplift_q_5)].reset_index(drop=True)#calculate the upliftcalc_uplift(df_data_lift)results:User Count: 10745Discount Conversion Uplift: 5.63%Discount Order Uplift: 604.62Discount Revenue Uplift: $15115.52Revenue Uplift Per Targeted Customer: $1.4" }, { "code": null, "e": 9706, "s": 9542, "text": "As expected, revenue uplift per targeted customer decreased to $1.4. Moreover, the group is 50% of the targeted customers contributed to 37% of the revenue uplift." }, { "code": null, "e": 9778, "s": 9706, "text": "By using this model, we can easily make our campaign more efficient by:" }, { "code": null, "e": 9832, "s": 9778, "text": "Targeting specific segments based on the uplift score" }, { "code": null, "e": 9889, "s": 9832, "text": "Trying different offers based on customer’s uplift score" }, { "code": null, "e": 10030, "s": 9889, "text": "In the next article, I’ll be explaining one of the core elements of Growth Hacking: A/B Testing. That will be our final post on this series." }, { "code": null, "e": 10087, "s": 10030, "text": "You can find the Jupyter Notebook for this article here." } ]
smtp - Unix, Linux Command
smtp [generic Postfix daemon options] The SMTP+LMTP client updates the queue file and marks recipients as finished, or it informs the queue manager that delivery should be tried again at a later time. Delivery status reports are sent to the bounce(8), defer(8) or trace(8) daemon as appropriate. The SMTP+LMTP client looks up a list of mail exchanger addresses for the destination host, sorts the list by preference, and connects to each listed address until it finds a server that responds. When a server is not reachable, or when mail delivery fails due to a recoverable error condition, the SMTP+LMTP client will try to deliver the mail to an alternate host. After a successful mail transaction, a connection may be saved to the scache(8) connection cache server, so that it may be used by any SMTP+LMTP client for a subsequent transaction. By default, connection caching is enabled temporarily for destinations that have a high volume of mail in the active queue. Session caching can be enabled permanently for specific destinations. RFC 821 (SMTP protocol) RFC 822 (ARPA Internet Text Messages) RFC 1651 (SMTP service extensions) RFC 1652 (8bit-MIME transport) RFC 1870 (Message Size Declaration) RFC 2033 (LMTP protocol) RFC 2034 (SMTP Enhanced Error Codes) RFC 2045 (MIME: Format of Internet Message Bodies) RFC 2046 (MIME: Media Types) RFC 2554 (AUTH command) RFC 2821 (SMTP protocol) RFC 2920 (SMTP Pipelining) RFC 3207 (STARTTLS command) RFC 3461 (SMTP DSN Extension) RFC 3463 (Enhanced Status Codes) Depending on the setting of the notify_classes parameter, the postmaster is notified of bounces, protocol problems, and of other trouble. SMTP and LMTP connection caching assumes that SASL credentials are valid for all destinations that map onto the same IP address and TCP port. Most smtp_xxx configuration parameters have an lmtp_xxx "ghost" parameter for the equivalent LMTP feature. This document describes only those LMTP-related parameters that aren’t simply "ghost" parameters. Changes to main.cf are picked up automatically, as smtp(8) processes run for only a limited amount of time. Use the command "postfix reload" to speed up a change. The text below provides only a parameter summary. See postconf(5) for more details including examples. qmgr(8), queue manager bounce(8), delivery status reports scache(8), connection cache server postconf(5), configuration parameters master(5), generic daemon options master(8), process manager tlsmgr(8), TLS session and PRNG management syslogd(8), system logging SASL_README, Postfix SASL howto TLS_README, Postfix STARTTLS howto Wietse Venema IBM T.J. Watson Research P.O. Box 704 Yorktown Heights, NY 10598, USA Command pipelining in cooperation with: Jon Ribbens Oaktree Internet Solutions Ltd., Internet House, Canal Basin, Coventry, CV1 4LY, United Kingdom. SASL support originally by: Till Franke SuSE Rhein/Main AG 65760 Eschborn, Germany Connection caching in cooperation with: Victor Duchovni Morgan Stanley TLS support originally by: Lutz Jaenicke BTU Cottbus Allgemeine Elektrotechnik Universitaetsplatz 3-4 D-03044 Cottbus, Germany Command pipelining in cooperation with: Jon Ribbens Oaktree Internet Solutions Ltd., Internet House, Canal Basin, Coventry, CV1 4LY, United Kingdom. SASL support originally by: Till Franke SuSE Rhein/Main AG 65760 Eschborn, Germany Connection caching in cooperation with: Victor Duchovni Morgan Stanley TLS support originally by: Lutz Jaenicke BTU Cottbus Allgemeine Elektrotechnik Universitaetsplatz 3-4 D-03044 Cottbus, Germany Advertisements 129 Lectures 23 hours Eduonix Learning Solutions 5 Lectures 4.5 hours Frahaan Hussain 35 Lectures 2 hours Pradeep D 41 Lectures 2.5 hours Musab Zayadneh 46 Lectures 4 hours GUHARAJANM 6 Lectures 4 hours Uplatz Print Add Notes Bookmark this page
[ { "code": null, "e": 10616, "s": 10577, "text": "smtp [generic Postfix daemon options]\n" }, { "code": null, "e": 10876, "s": 10616, "text": "\nThe SMTP+LMTP client updates the queue file and marks recipients\nas finished, or it informs the queue manager that delivery should\nbe tried again at a later time. Delivery status reports are sent\nto the bounce(8), defer(8) or trace(8) daemon as\nappropriate.\n" }, { "code": null, "e": 11074, "s": 10876, "text": "\nThe SMTP+LMTP client looks up a list of mail exchanger addresses for\nthe destination host, sorts the list by preference, and connects\nto each listed address until it finds a server that responds.\n" }, { "code": null, "e": 11246, "s": 11074, "text": "\nWhen a server is not reachable, or when mail delivery fails due\nto a recoverable error condition, the SMTP+LMTP client will try to\ndeliver the mail to an alternate host.\n" }, { "code": null, "e": 11430, "s": 11246, "text": "\nAfter a successful mail transaction, a connection may be saved\nto the scache(8) connection cache server, so that it\nmay be used by any SMTP+LMTP client for a subsequent transaction.\n" }, { "code": null, "e": 11626, "s": 11430, "text": "\nBy default, connection caching is enabled temporarily for\ndestinations that have a high volume of mail in the active\nqueue. Session caching can be enabled permanently for\nspecific destinations.\n" }, { "code": null, "e": 12106, "s": 11632, "text": "RFC 821 (SMTP protocol)\nRFC 822 (ARPA Internet Text Messages)\nRFC 1651 (SMTP service extensions)\nRFC 1652 (8bit-MIME transport)\nRFC 1870 (Message Size Declaration)\nRFC 2033 (LMTP protocol)\nRFC 2034 (SMTP Enhanced Error Codes)\nRFC 2045 (MIME: Format of Internet Message Bodies)\nRFC 2046 (MIME: Media Types)\nRFC 2554 (AUTH command)\nRFC 2821 (SMTP protocol)\nRFC 2920 (SMTP Pipelining)\nRFC 3207 (STARTTLS command)\nRFC 3461 (SMTP DSN Extension)\nRFC 3463 (Enhanced Status Codes)\n" }, { "code": null, "e": 12246, "s": 12106, "text": "\nDepending on the setting of the notify_classes parameter,\nthe postmaster is notified of bounces, protocol problems, and of\nother trouble.\n" }, { "code": null, "e": 12390, "s": 12246, "text": "\nSMTP and LMTP connection caching assumes that SASL credentials\nare valid for all destinations that map onto the same IP\naddress and TCP port.\n" }, { "code": null, "e": 12599, "s": 12392, "text": "\nMost smtp_xxx configuration parameters have an\nlmtp_xxx \"ghost\" parameter for the equivalent LMTP\nfeature. This document describes only those LMTP-related\nparameters that aren’t simply \"ghost\" parameters.\n" }, { "code": null, "e": 12764, "s": 12599, "text": "\nChanges to main.cf are picked up automatically, as smtp(8)\nprocesses run for only a limited amount of time. Use the command\n\"postfix reload\" to speed up a change.\n" }, { "code": null, "e": 12869, "s": 12764, "text": "\nThe text below provides only a parameter summary. See\npostconf(5) for more details including examples.\n" }, { "code": null, "e": 13150, "s": 12887, "text": "qmgr(8), queue manager\nbounce(8), delivery status reports\nscache(8), connection cache server\npostconf(5), configuration parameters\nmaster(5), generic daemon options\nmaster(8), process manager\ntlsmgr(8), TLS session and PRNG management\nsyslogd(8), system logging\n" }, { "code": null, "e": 13220, "s": 13152, "text": "SASL_README, Postfix SASL howto\nTLS_README, Postfix STARTTLS howto\n" }, { "code": null, "e": 13741, "s": 13222, "text": "Wietse Venema\nIBM T.J. Watson Research\nP.O. Box 704\nYorktown Heights, NY 10598, USA\n\nCommand pipelining in cooperation with:\nJon Ribbens\nOaktree Internet Solutions Ltd.,\nInternet House,\nCanal Basin,\nCoventry,\nCV1 4LY, United Kingdom.\n\nSASL support originally by:\nTill Franke\nSuSE Rhein/Main AG\n65760 Eschborn, Germany\n\nConnection caching in cooperation with:\nVictor Duchovni\nMorgan Stanley\n\nTLS support originally by:\nLutz Jaenicke\nBTU Cottbus\nAllgemeine Elektrotechnik\nUniversitaetsplatz 3-4\nD-03044 Cottbus, Germany\n" }, { "code": null, "e": 13892, "s": 13741, "text": "\nCommand pipelining in cooperation with:\nJon Ribbens\nOaktree Internet Solutions Ltd.,\nInternet House,\nCanal Basin,\nCoventry,\nCV1 4LY, United Kingdom.\n" }, { "code": null, "e": 13977, "s": 13892, "text": "\nSASL support originally by:\nTill Franke\nSuSE Rhein/Main AG\n65760 Eschborn, Germany\n" }, { "code": null, "e": 14050, "s": 13977, "text": "\nConnection caching in cooperation with:\nVictor Duchovni\nMorgan Stanley\n" }, { "code": null, "e": 14179, "s": 14050, "text": "\nTLS support originally by:\nLutz Jaenicke\nBTU Cottbus\nAllgemeine Elektrotechnik\nUniversitaetsplatz 3-4\nD-03044 Cottbus, Germany\n" }, { "code": null, "e": 14196, "s": 14179, "text": "\nAdvertisements\n" }, { "code": null, "e": 14231, "s": 14196, "text": "\n 129 Lectures \n 23 hours \n" }, { "code": null, "e": 14259, "s": 14231, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 14293, "s": 14259, "text": "\n 5 Lectures \n 4.5 hours \n" }, { "code": null, "e": 14310, "s": 14293, "text": " Frahaan Hussain" }, { "code": null, "e": 14343, "s": 14310, "text": "\n 35 Lectures \n 2 hours \n" }, { "code": null, "e": 14354, "s": 14343, "text": " Pradeep D" }, { "code": null, "e": 14389, "s": 14354, "text": "\n 41 Lectures \n 2.5 hours \n" }, { "code": null, "e": 14405, "s": 14389, "text": " Musab Zayadneh" }, { "code": null, "e": 14438, "s": 14405, "text": "\n 46 Lectures \n 4 hours \n" }, { "code": null, "e": 14450, "s": 14438, "text": " GUHARAJANM" }, { "code": null, "e": 14482, "s": 14450, "text": "\n 6 Lectures \n 4 hours \n" }, { "code": null, "e": 14490, "s": 14482, "text": " Uplatz" }, { "code": null, "e": 14497, "s": 14490, "text": " Print" }, { "code": null, "e": 14508, "s": 14497, "text": " Add Notes" } ]
Modular Approach in Programming
07 Sep, 2018 Modular programming is the process of subdividing a computer program into separate sub-programs. A module is a separate software component. It can often be used in a variety of applications and functions with other components of the system. Some programs might have thousands or millions of lines and to manage such programs it becomes quite difficult as there might be too many of syntax errors or logical errors present in the program, so to manage such type of programs concept of modular programming approached. Each sub-module contains something necessary to execute only one aspect of the desired functionality. Modular programming emphasis on breaking of large programs into small problems to increase the maintainability, readability of the code and to make the program handy to make any changes in future or to correct the errors. Points which should be taken care of prior to modular program development: Limitations of each and every module should be decided.In which way a program is to be partitioned into different modules.Communication among different modules of the code for proper execution of the entire program. Limitations of each and every module should be decided. In which way a program is to be partitioned into different modules. Communication among different modules of the code for proper execution of the entire program. Advantages of Using Modular Programming Approach – Ease of Use :This approach allows simplicity, as rather than focusing on the entire thousands and millions of lines code in one go we can access it in the form of modules. This allows ease in debugging the code and prone to less error.Reusability :It allows the user to reuse the functionality with a different interface without typing the whole program again.Ease of Maintenance : It helps in less collision at the time of working on modules, helping a team to work with proper collaboration while working on a large application. Ease of Use :This approach allows simplicity, as rather than focusing on the entire thousands and millions of lines code in one go we can access it in the form of modules. This allows ease in debugging the code and prone to less error. Reusability :It allows the user to reuse the functionality with a different interface without typing the whole program again. Ease of Maintenance : It helps in less collision at the time of working on modules, helping a team to work with proper collaboration while working on a large application. Example of Modular Programming in C C is called a structured programming language because to solve a large problem, C programming language divides the problem into smaller modules called functions or procedures each of which handles a particular responsibility. The program which solves the entire problem is a collection of such functions.Module is basically a set of interrelated files that share their implementation details but hide it from the outside world. How can we implement modular programming in c? Each function defined in C by default is globally accessible. This can be done by including the header file in which implementation of the function is defined.Suppose, we want to declare a Stack data type and at the same time want to hide the implementation, including its data structure, from users. We can do this by first defining a public file called stack.h which contains generic data Stack data type and the functions which are supported by the stack data type.In the header file we must include only the definitions of constants, structures, variables and functions with the name of the module, that makes easy to identify source of definition in a larger program with many modules.Keywords extern and static help in the implementation of modularity in C. stack.h: extern stack_var1; extern int stack_do_something(void); Now we can create a file named stack.c that contains implementation of stack data type: stack.c #include int stack_var1; static int stack_var2; int stack_do_something(void) { stack_var1 = 2; stack_var2 = 5; } The main file which may includes module stack #include int main(int argc, char*argv[]){ while(1){ stack_do_something(); } } CBSE - Class 11 Picked Programming Basics school-programming School Programming Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 53, "s": 25, "text": "\n07 Sep, 2018" }, { "code": null, "e": 294, "s": 53, "text": "Modular programming is the process of subdividing a computer program into separate sub-programs. A module is a separate software component. It can often be used in a variety of applications and functions with other components of the system." }, { "code": null, "e": 569, "s": 294, "text": "Some programs might have thousands or millions of lines and to manage such programs it becomes quite difficult as there might be too many of syntax errors or logical errors present in the program, so to manage such type of programs concept of modular programming approached." }, { "code": null, "e": 671, "s": 569, "text": "Each sub-module contains something necessary to execute only one aspect of the desired functionality." }, { "code": null, "e": 893, "s": 671, "text": "Modular programming emphasis on breaking of large programs into small problems to increase the maintainability, readability of the code and to make the program handy to make any changes in future or to correct the errors." }, { "code": null, "e": 968, "s": 893, "text": "Points which should be taken care of prior to modular program development:" }, { "code": null, "e": 1184, "s": 968, "text": "Limitations of each and every module should be decided.In which way a program is to be partitioned into different modules.Communication among different modules of the code for proper execution of the entire program." }, { "code": null, "e": 1240, "s": 1184, "text": "Limitations of each and every module should be decided." }, { "code": null, "e": 1308, "s": 1240, "text": "In which way a program is to be partitioned into different modules." }, { "code": null, "e": 1402, "s": 1308, "text": "Communication among different modules of the code for proper execution of the entire program." }, { "code": null, "e": 1453, "s": 1402, "text": "Advantages of Using Modular Programming Approach –" }, { "code": null, "e": 1984, "s": 1453, "text": "Ease of Use :This approach allows simplicity, as rather than focusing on the entire thousands and millions of lines code in one go we can access it in the form of modules. This allows ease in debugging the code and prone to less error.Reusability :It allows the user to reuse the functionality with a different interface without typing the whole program again.Ease of Maintenance : It helps in less collision at the time of working on modules, helping a team to work with proper collaboration while working on a large application." }, { "code": null, "e": 2220, "s": 1984, "text": "Ease of Use :This approach allows simplicity, as rather than focusing on the entire thousands and millions of lines code in one go we can access it in the form of modules. This allows ease in debugging the code and prone to less error." }, { "code": null, "e": 2346, "s": 2220, "text": "Reusability :It allows the user to reuse the functionality with a different interface without typing the whole program again." }, { "code": null, "e": 2517, "s": 2346, "text": "Ease of Maintenance : It helps in less collision at the time of working on modules, helping a team to work with proper collaboration while working on a large application." }, { "code": null, "e": 2553, "s": 2517, "text": "Example of Modular Programming in C" }, { "code": null, "e": 3792, "s": 2553, "text": "C is called a structured programming language because to solve a large problem, C programming language divides the problem into smaller modules called functions or procedures each of which handles a particular responsibility. The program which solves the entire problem is a collection of such functions.Module is basically a set of interrelated files that share their implementation details but hide it from the outside world. How can we implement modular programming in c? Each function defined in C by default is globally accessible. This can be done by including the header file in which implementation of the function is defined.Suppose, we want to declare a Stack data type and at the same time want to hide the implementation, including its data structure, from users. We can do this by first defining a public file called stack.h which contains generic data Stack data type and the functions which are supported by the stack data type.In the header file we must include only the definitions of constants, structures, variables and functions with the name of the module, that makes easy to identify source of definition in a larger program with many modules.Keywords extern and static help in the implementation of modularity in C." }, { "code": null, "e": 3886, "s": 3792, "text": "stack.h:\n extern stack_var1;\n extern int stack_do_something(void);\n " }, { "code": null, "e": 3974, "s": 3886, "text": "Now we can create a file named stack.c that contains implementation of stack data type:" }, { "code": null, "e": 4101, "s": 3974, "text": "stack.c\n#include\nint stack_var1;\nstatic int stack_var2;\n\nint stack_do_something(void)\n{\n stack_var1 = 2;\n stack_var2 = 5;\n}\n" }, { "code": null, "e": 4147, "s": 4101, "text": "The main file which may includes module stack" }, { "code": null, "e": 4232, "s": 4147, "text": "#include\nint main(int argc, char*argv[]){\nwhile(1){\n stack_do_something();\n }\n}\n" }, { "code": null, "e": 4248, "s": 4232, "text": "CBSE - Class 11" }, { "code": null, "e": 4255, "s": 4248, "text": "Picked" }, { "code": null, "e": 4274, "s": 4255, "text": "Programming Basics" }, { "code": null, "e": 4293, "s": 4274, "text": "school-programming" }, { "code": null, "e": 4312, "s": 4293, "text": "School Programming" } ]
RichTextField – Django Models
16 Jun, 2021 RichTextField is generally used for storing paragraphs that can store any type of data. Rich text is the text that is formatted with common formatting options, such as bold, italics, images, URLs that are unavailable with plain text. Syntax: field_name=RichTextField() Django Model RichTextField Explanation Illustration of RichTextField using an Example. Consider a project named geeksforgeeks having an app named geeks. Refer to the following articles to check how to create a project and an app in Django. How to Create a Basic Project using MVT in Django? How to Create an App in Django ? Now install django-ckeditor package by entering the following command in your terminal or command prompt. pip install django-ckeditor Go to settings.py and add the ckeditor and the geeks app to INSTALLED_APPS Python3 # Application definitionINSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'ckeditor', 'geeks',] Enter the following code into the models.py file of the geeks app. Python3 from django.db import modelsfrom django.db.models import Modelfrom ckeditor.fields import RichTextField # Create your models here.class GeeksModel(Model): geeks_field = RichTextField() Now when we run makemigrations command from the terminal, python manage.py makemigrations A new folder named migrations would be created in geeks directory with a file named 0001_initial.py Python3 # Generated by Django 3.2.3 on 2021-05-13 09:40 import ckeditor.fieldsfrom django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='GeeksModel', fields=[ ('id', models.BigAutoField( auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('geeks_field', ckeditor.fields.RichTextField()), ], ), ] Now run, python manage.py migrate Thus, a geeks_field RichTextField is created when you run migrations on the project. It is a field to store large data. Go to admin.py and register your model. Python3 from django.contrib import adminfrom .models import GeeksModel # Register your models here.admin.site.register(GeeksModel) How to use RichTextField ? RichTextField is used for storing large data of different types(images, URLs, bold text, etc) in the database. Now let’s check it in the admin server. Whenever we click on Add Geeks Model we can see a RichTextField varshagumber28 Django-models Python Django 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": "\n16 Jun, 2021" }, { "code": null, "e": 288, "s": 52, "text": "RichTextField is generally used for storing paragraphs that can store any type of data. Rich text is the text that is formatted with common formatting options, such as bold, italics, images, URLs that are unavailable with plain text. " }, { "code": null, "e": 296, "s": 288, "text": "Syntax:" }, { "code": null, "e": 323, "s": 296, "text": "field_name=RichTextField()" }, { "code": null, "e": 362, "s": 323, "text": "Django Model RichTextField Explanation" }, { "code": null, "e": 476, "s": 362, "text": "Illustration of RichTextField using an Example. Consider a project named geeksforgeeks having an app named geeks." }, { "code": null, "e": 563, "s": 476, "text": "Refer to the following articles to check how to create a project and an app in Django." }, { "code": null, "e": 614, "s": 563, "text": "How to Create a Basic Project using MVT in Django?" }, { "code": null, "e": 647, "s": 614, "text": "How to Create an App in Django ?" }, { "code": null, "e": 753, "s": 647, "text": "Now install django-ckeditor package by entering the following command in your terminal or command prompt." }, { "code": null, "e": 781, "s": 753, "text": "pip install django-ckeditor" }, { "code": null, "e": 856, "s": 781, "text": "Go to settings.py and add the ckeditor and the geeks app to INSTALLED_APPS" }, { "code": null, "e": 864, "s": 856, "text": "Python3" }, { "code": "# Application definitionINSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'ckeditor', 'geeks',]", "e": 1115, "s": 864, "text": null }, { "code": null, "e": 1186, "s": 1119, "text": "Enter the following code into the models.py file of the geeks app." }, { "code": null, "e": 1196, "s": 1188, "text": "Python3" }, { "code": "from django.db import modelsfrom django.db.models import Modelfrom ckeditor.fields import RichTextField # Create your models here.class GeeksModel(Model): geeks_field = RichTextField()", "e": 1385, "s": 1196, "text": null }, { "code": null, "e": 1447, "s": 1389, "text": "Now when we run makemigrations command from the terminal," }, { "code": null, "e": 1481, "s": 1449, "text": "python manage.py makemigrations" }, { "code": null, "e": 1583, "s": 1483, "text": "A new folder named migrations would be created in geeks directory with a file named 0001_initial.py" }, { "code": null, "e": 1593, "s": 1585, "text": "Python3" }, { "code": "# Generated by Django 3.2.3 on 2021-05-13 09:40 import ckeditor.fieldsfrom django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='GeeksModel', fields=[ ('id', models.BigAutoField( auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('geeks_field', ckeditor.fields.RichTextField()), ], ), ]", "e": 2150, "s": 1593, "text": null }, { "code": null, "e": 2159, "s": 2150, "text": "Now run," }, { "code": null, "e": 2184, "s": 2159, "text": "python manage.py migrate" }, { "code": null, "e": 2344, "s": 2184, "text": "Thus, a geeks_field RichTextField is created when you run migrations on the project. It is a field to store large data. Go to admin.py and register your model." }, { "code": null, "e": 2352, "s": 2344, "text": "Python3" }, { "code": "from django.contrib import adminfrom .models import GeeksModel # Register your models here.admin.site.register(GeeksModel)", "e": 2476, "s": 2352, "text": null }, { "code": null, "e": 2503, "s": 2476, "text": "How to use RichTextField ?" }, { "code": null, "e": 2718, "s": 2503, "text": "RichTextField is used for storing large data of different types(images, URLs, bold text, etc) in the database. Now let’s check it in the admin server. Whenever we click on Add Geeks Model we can see a RichTextField" }, { "code": null, "e": 2733, "s": 2718, "text": "varshagumber28" }, { "code": null, "e": 2747, "s": 2733, "text": "Django-models" }, { "code": null, "e": 2761, "s": 2747, "text": "Python Django" }, { "code": null, "e": 2768, "s": 2761, "text": "Python" }, { "code": null, "e": 2866, "s": 2768, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2898, "s": 2866, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 2925, "s": 2898, "text": "Python Classes and Objects" }, { "code": null, "e": 2946, "s": 2925, "text": "Python OOPs Concepts" }, { "code": null, "e": 2969, "s": 2946, "text": "Introduction To PYTHON" }, { "code": null, "e": 3000, "s": 2969, "text": "Python | os.path.join() method" }, { "code": null, "e": 3056, "s": 3000, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 3098, "s": 3056, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 3140, "s": 3098, "text": "Check if element exists in list in Python" }, { "code": null, "e": 3179, "s": 3140, "text": "Python | Get unique values from a list" } ]
Python | Pandas Timestamp.weekday_name
08 Jan, 2019 Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier. Pandas Timestamp.weekday_name attribute return the name of the day of the week for the given date in the Timestamp object. Syntax : Timestamp.weekday_name Parameters : None Return : name of the week day Example #1: Use Timestamp.weekday_name attribute to find the name of the weekday for the given date in the Timestamp object. # importing pandas as pdimport pandas as pd # Create the Timestamp objectts = pd.Timestamp(year = 2011, month = 11, day = 21, hour = 10, second = 49, tz = 'US/Central') # Print the Timestamp objectprint(ts) Output : Now we will use the Timestamp.weekday_name attribute to find the weekday name. # return the name of the weekdayts.weekday_name Output : As we can see in the output, the Timestamp.weekday_name attribute has returned ‘Monday’ indicating that the date in the given Timestamp object is ‘Monday’. Example #2: Use Timestamp.weekday_name attribute to find the name of the weekday for the given date in the Timestamp object. # importing pandas as pdimport pandas as pd # Create the Timestamp objectts = pd.Timestamp(year = 2009, month = 5, day = 31, hour = 4, second = 49, tz = 'Europe/Berlin') # Print the Timestamp objectprint(ts) Output : Now we will use the Timestamp.weekday_name attribute to find the weekday name. # return the name of the weekdayts.weekday_name Output : As we can see in the output, the Timestamp.weekday_name attribute has returned ‘Sunday’ indicating that the date in the given Timestamp object is ‘Sunday’. Python Pandas-Timestamp Python-pandas Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n08 Jan, 2019" }, { "code": null, "e": 242, "s": 28, "text": "Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier." }, { "code": null, "e": 365, "s": 242, "text": "Pandas Timestamp.weekday_name attribute return the name of the day of the week for the given date in the Timestamp object." }, { "code": null, "e": 397, "s": 365, "text": "Syntax : Timestamp.weekday_name" }, { "code": null, "e": 415, "s": 397, "text": "Parameters : None" }, { "code": null, "e": 445, "s": 415, "text": "Return : name of the week day" }, { "code": null, "e": 570, "s": 445, "text": "Example #1: Use Timestamp.weekday_name attribute to find the name of the weekday for the given date in the Timestamp object." }, { "code": "# importing pandas as pdimport pandas as pd # Create the Timestamp objectts = pd.Timestamp(year = 2011, month = 11, day = 21, hour = 10, second = 49, tz = 'US/Central') # Print the Timestamp objectprint(ts)", "e": 791, "s": 570, "text": null }, { "code": null, "e": 800, "s": 791, "text": "Output :" }, { "code": null, "e": 879, "s": 800, "text": "Now we will use the Timestamp.weekday_name attribute to find the weekday name." }, { "code": "# return the name of the weekdayts.weekday_name", "e": 927, "s": 879, "text": null }, { "code": null, "e": 936, "s": 927, "text": "Output :" }, { "code": null, "e": 1092, "s": 936, "text": "As we can see in the output, the Timestamp.weekday_name attribute has returned ‘Monday’ indicating that the date in the given Timestamp object is ‘Monday’." }, { "code": null, "e": 1217, "s": 1092, "text": "Example #2: Use Timestamp.weekday_name attribute to find the name of the weekday for the given date in the Timestamp object." }, { "code": "# importing pandas as pdimport pandas as pd # Create the Timestamp objectts = pd.Timestamp(year = 2009, month = 5, day = 31, hour = 4, second = 49, tz = 'Europe/Berlin') # Print the Timestamp objectprint(ts)", "e": 1435, "s": 1217, "text": null }, { "code": null, "e": 1444, "s": 1435, "text": "Output :" }, { "code": null, "e": 1523, "s": 1444, "text": "Now we will use the Timestamp.weekday_name attribute to find the weekday name." }, { "code": "# return the name of the weekdayts.weekday_name", "e": 1571, "s": 1523, "text": null }, { "code": null, "e": 1580, "s": 1571, "text": "Output :" }, { "code": null, "e": 1736, "s": 1580, "text": "As we can see in the output, the Timestamp.weekday_name attribute has returned ‘Sunday’ indicating that the date in the given Timestamp object is ‘Sunday’." }, { "code": null, "e": 1760, "s": 1736, "text": "Python Pandas-Timestamp" }, { "code": null, "e": 1774, "s": 1760, "text": "Python-pandas" }, { "code": null, "e": 1781, "s": 1774, "text": "Python" } ]
Javascript Program For Reversing A Linked List In Groups Of Given Size- Set 2
19 Jan, 2022 Given a linked list, write a function to reverse every k nodes (where k is an input to the function). Examples: Input: 1->2->3->4->5->6->7->8->NULL and k = 3 Output: 3->2->1->6->5->4->8->7->NULL. Input: 1->2->3->4->5->6->7->8->NULL and k = 5 Output: 5->4->3->2->1->8->7->6->NULL. We have already discussed its solution in below post Reverse a Linked List in groups of given size | Set 1In this post, we have used a stack which will store the nodes of the given linked list. Firstly, push the k elements of the linked list in the stack. Now pop elements one by one and keep track of the previously popped node. Point the next pointer of prev node to top element of stack. Repeat this process, until NULL is reached.This algorithm uses O(k) extra space. Javascript <script>// Javascript program to reverse a linked list// in groups of given sizeclass GfG{ // Link list node class Node { constructor() { this.data = 0; this.next = null; } } var head = null; /* Reverses the linked list in groups of size k and returns the pointer to the new head node. */ function Reverse(head, k) { // Create a stack of Node* var mystack = []; var current = head; var prev = null; while (current != null) { // Terminate the loop whichever comes // first either current == NULL or // count >= k var count = 0; while (current != null && count < k) { mystack.push(current); current = current.next; count++; } // Now pop the elements of stack one // by one while (mystack.length > 0) { // If final list has not been // started yet. if (prev == null) { prev = mystack.pop(); head = prev; } else { prev.next = mystack.pop(); prev = prev.next; } } } // Next of last element will point // to NULL. prev.next = null; return head; } // UTILITY FUNCTIONS // Function to push a node function push(new_data) { // Allocate node var new_node = new Node(); // Put in the data new_node.data = new_data; // Link the old list off the // new node new_node.next = head; // Move the head to point to the // new node head = new_node; } // Function to print linked list function printList(node) { while (node != null) { document.write(node.data + " "); node = node.next; } }} // Driver code // Start with the empty list// Node head = null; /* Created Linked list is 1->2->3-> 4->5->6->7->8->9 */push(9);push(8);push(7);push(6);push(5);push(4);push(3);push(2);push(1); document.write("Given linked list <br/>");printList(head);head = Reverse(head, 3);document.write("<br/>"); document.write("Reversed Linked list <br/>");printList(head);// This code contributed by aashish1995</script> Output: Given Linked List 1 2 3 4 5 6 7 8 9 Reversed list 3 2 1 6 5 4 9 8 7 Please refer complete article on Reverse a Linked List in groups of given size | Set 2 for more details! khushboogoyal499 Accolite Adobe Linked Lists MakeMyTrip Microsoft Paytm Snapdeal VMWare JavaScript Linked List Paytm VMWare Accolite Microsoft Snapdeal MakeMyTrip Adobe Linked List Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n19 Jan, 2022" }, { "code": null, "e": 140, "s": 28, "text": "Given a linked list, write a function to reverse every k nodes (where k is an input to the function). Examples:" }, { "code": null, "e": 311, "s": 140, "text": "Input: 1->2->3->4->5->6->7->8->NULL and k = 3 \nOutput: 3->2->1->6->5->4->8->7->NULL. \n\nInput: 1->2->3->4->5->6->7->8->NULL and k = 5\nOutput: 5->4->3->2->1->8->7->6->NULL." }, { "code": null, "e": 783, "s": 311, "text": "We have already discussed its solution in below post Reverse a Linked List in groups of given size | Set 1In this post, we have used a stack which will store the nodes of the given linked list. Firstly, push the k elements of the linked list in the stack. Now pop elements one by one and keep track of the previously popped node. Point the next pointer of prev node to top element of stack. Repeat this process, until NULL is reached.This algorithm uses O(k) extra space." }, { "code": null, "e": 794, "s": 783, "text": "Javascript" }, { "code": "<script>// Javascript program to reverse a linked list// in groups of given sizeclass GfG{ // Link list node class Node { constructor() { this.data = 0; this.next = null; } } var head = null; /* Reverses the linked list in groups of size k and returns the pointer to the new head node. */ function Reverse(head, k) { // Create a stack of Node* var mystack = []; var current = head; var prev = null; while (current != null) { // Terminate the loop whichever comes // first either current == NULL or // count >= k var count = 0; while (current != null && count < k) { mystack.push(current); current = current.next; count++; } // Now pop the elements of stack one // by one while (mystack.length > 0) { // If final list has not been // started yet. if (prev == null) { prev = mystack.pop(); head = prev; } else { prev.next = mystack.pop(); prev = prev.next; } } } // Next of last element will point // to NULL. prev.next = null; return head; } // UTILITY FUNCTIONS // Function to push a node function push(new_data) { // Allocate node var new_node = new Node(); // Put in the data new_node.data = new_data; // Link the old list off the // new node new_node.next = head; // Move the head to point to the // new node head = new_node; } // Function to print linked list function printList(node) { while (node != null) { document.write(node.data + \" \"); node = node.next; } }} // Driver code // Start with the empty list// Node head = null; /* Created Linked list is 1->2->3-> 4->5->6->7->8->9 */push(9);push(8);push(7);push(6);push(5);push(4);push(3);push(2);push(1); document.write(\"Given linked list <br/>\");printList(head);head = Reverse(head, 3);document.write(\"<br/>\"); document.write(\"Reversed Linked list <br/>\");printList(head);// This code contributed by aashish1995</script>", "e": 3303, "s": 794, "text": null }, { "code": null, "e": 3312, "s": 3303, "text": "Output: " }, { "code": null, "e": 3381, "s": 3312, "text": "Given Linked List\n1 2 3 4 5 6 7 8 9 \nReversed list\n3 2 1 6 5 4 9 8 7" }, { "code": null, "e": 3487, "s": 3381, "text": "Please refer complete article on Reverse a Linked List in groups of given size | Set 2 for more details! " }, { "code": null, "e": 3504, "s": 3487, "text": "khushboogoyal499" }, { "code": null, "e": 3513, "s": 3504, "text": "Accolite" }, { "code": null, "e": 3519, "s": 3513, "text": "Adobe" }, { "code": null, "e": 3532, "s": 3519, "text": "Linked Lists" }, { "code": null, "e": 3543, "s": 3532, "text": "MakeMyTrip" }, { "code": null, "e": 3553, "s": 3543, "text": "Microsoft" }, { "code": null, "e": 3559, "s": 3553, "text": "Paytm" }, { "code": null, "e": 3568, "s": 3559, "text": "Snapdeal" }, { "code": null, "e": 3575, "s": 3568, "text": "VMWare" }, { "code": null, "e": 3586, "s": 3575, "text": "JavaScript" }, { "code": null, "e": 3598, "s": 3586, "text": "Linked List" }, { "code": null, "e": 3604, "s": 3598, "text": "Paytm" }, { "code": null, "e": 3611, "s": 3604, "text": "VMWare" }, { "code": null, "e": 3620, "s": 3611, "text": "Accolite" }, { "code": null, "e": 3630, "s": 3620, "text": "Microsoft" }, { "code": null, "e": 3639, "s": 3630, "text": "Snapdeal" }, { "code": null, "e": 3650, "s": 3639, "text": "MakeMyTrip" }, { "code": null, "e": 3656, "s": 3650, "text": "Adobe" }, { "code": null, "e": 3668, "s": 3656, "text": "Linked List" } ]
numpy.outer() function – Python
05 May, 2020 numpy.outer() function compute the outer product of two vectors. Syntax : numpy.outer(a, b, out = None) Parameters :a : [array_like] First input vector. Input is flattened if not already 1-dimensional.b : [array_like] Second input vector. Input is flattened if not already 1-dimensional.out : [ndarray, optional] A location where the result is stored. Return : [ndarray] Returns the outer product of two vectors. out[i, j] = a[i] * b[j] Code #1 : # Python program explaining# numpy.outer() function # importing numpy as geek import numpy as geek a = geek.ones(4)b = geek.linspace(-1, 2, 4) gfg = geek.outer(a, b) print (gfg) Output : [[-1. 0. 1. 2.] [-1. 0. 1. 2.] [-1. 0. 1. 2.] [-1. 0. 1. 2.]] Code #2 : # Python program explaining# numpy.outer() function # importing numpy as geek import numpy as geek a = geek.ones(5)b = geek.linspace(-2, 2, 5) gfg = geek.outer(a, b) print (gfg) Output : [[-2. -1. 0. 1. 2.] [-2. -1. 0. 1. 2.] [-2. -1. 0. 1. 2.] [-2. -1. 0. 1. 2.] [-2. -1. 0. 1. 2.]] Python-numpy Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Python Classes and Objects Python OOPs Concepts Introduction To PYTHON Python | os.path.join() method How to drop one or multiple columns in Pandas Dataframe How To Convert Python Dictionary To JSON? Check if element exists in list in Python Python | Get unique values from a list Python | datetime.timedelta() function
[ { "code": null, "e": 28, "s": 0, "text": "\n05 May, 2020" }, { "code": null, "e": 93, "s": 28, "text": "numpy.outer() function compute the outer product of two vectors." }, { "code": null, "e": 132, "s": 93, "text": "Syntax : numpy.outer(a, b, out = None)" }, { "code": null, "e": 380, "s": 132, "text": "Parameters :a : [array_like] First input vector. Input is flattened if not already 1-dimensional.b : [array_like] Second input vector. Input is flattened if not already 1-dimensional.out : [ndarray, optional] A location where the result is stored." }, { "code": null, "e": 465, "s": 380, "text": "Return : [ndarray] Returns the outer product of two vectors. out[i, j] = a[i] * b[j]" }, { "code": null, "e": 475, "s": 465, "text": "Code #1 :" }, { "code": "# Python program explaining# numpy.outer() function # importing numpy as geek import numpy as geek a = geek.ones(4)b = geek.linspace(-1, 2, 4) gfg = geek.outer(a, b) print (gfg)", "e": 659, "s": 475, "text": null }, { "code": null, "e": 668, "s": 659, "text": "Output :" }, { "code": null, "e": 746, "s": 668, "text": "[[-1. 0. 1. 2.]\n [-1. 0. 1. 2.]\n [-1. 0. 1. 2.]\n [-1. 0. 1. 2.]]\n" }, { "code": null, "e": 757, "s": 746, "text": " Code #2 :" }, { "code": "# Python program explaining# numpy.outer() function # importing numpy as geek import numpy as geek a = geek.ones(5)b = geek.linspace(-2, 2, 5) gfg = geek.outer(a, b) print (gfg)", "e": 941, "s": 757, "text": null }, { "code": null, "e": 950, "s": 941, "text": "Output :" }, { "code": null, "e": 1067, "s": 950, "text": "[[-2. -1. 0. 1. 2.]\n [-2. -1. 0. 1. 2.]\n [-2. -1. 0. 1. 2.]\n [-2. -1. 0. 1. 2.]\n [-2. -1. 0. 1. 2.]]\n" }, { "code": null, "e": 1080, "s": 1067, "text": "Python-numpy" }, { "code": null, "e": 1087, "s": 1080, "text": "Python" }, { "code": null, "e": 1185, "s": 1087, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1217, "s": 1185, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 1244, "s": 1217, "text": "Python Classes and Objects" }, { "code": null, "e": 1265, "s": 1244, "text": "Python OOPs Concepts" }, { "code": null, "e": 1288, "s": 1265, "text": "Introduction To PYTHON" }, { "code": null, "e": 1319, "s": 1288, "text": "Python | os.path.join() method" }, { "code": null, "e": 1375, "s": 1319, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 1417, "s": 1375, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 1459, "s": 1417, "text": "Check if element exists in list in Python" }, { "code": null, "e": 1498, "s": 1459, "text": "Python | Get unique values from a list" } ]
Minimum steps to convert an Array into permutation of numbers from 1 to N
28 Jun, 2022 Given an array arr of length N, the task is to count the minimum number of operations to convert given sequence into a permutation of first N natural numbers (1, 2, ...., N). In each operation, increment or decrement an element by one.Examples: Input: arr[] = {4, 1, 3, 6, 5} Output: 4 Apply decrement operation four times on 6Input : arr[] = {0, 2, 3, 4, 1, 6, 8, 9} Output : 7 Approach: An efficient approach is to sort the given array and for each element, find the difference between the arr[i] and i(1 based indexing). Find the sum of all such difference, and this will be the minimum steps required.Below is the implementation of the above approach: CPP Java Python3 C# Javascript // C++ program to find minimum number of steps to// convert a given sequence into a permutation #include <bits/stdc++.h>using namespace std; // Function to find minimum number of steps to// convert a given sequence into a permutationint get_permutation(int arr[], int n){ // Sort the given array sort(arr, arr + n); // To store the required minimum // number of operations int result = 0; // Find the operations on each step for (int i = 0; i < n; i++) { result += abs(arr[i] - (i + 1)); } // Return the answer return result;} // Driver codeint main(){ int arr[] = { 0, 2, 3, 4, 1, 6, 8, 9 }; int n = sizeof(arr) / sizeof(arr[0]); // Function call cout << get_permutation(arr, n); return 0;} // Java program to find minimum number of steps to// convert a given sequence into a permutationimport java.util.*; class GFG{ // Function to find minimum number of steps to// convert a given sequence into a permutationstatic int get_permutation(int arr[], int n){ // Sort the given array Arrays.sort(arr); // To store the required minimum // number of operations int result = 0; // Find the operations on each step for (int i = 0; i < n; i++) { result += Math.abs(arr[i] - (i + 1)); } // Return the answer return result;} // Driver codepublic static void main(String[] args){ int arr[] = { 0, 2, 3, 4, 1, 6, 8, 9 }; int n = arr.length; // Function call System.out.print(get_permutation(arr, n)); }} // This code is contributed by 29AjayKumar # Python3 program to find minimum number of steps to# convert a given sequence into a permutation # Function to find minimum number of steps to# convert a given sequence into a permutationdef get_permutation(arr, n): # Sort the given array arr = sorted(arr) # To store the required minimum # number of operations result = 0 # Find the operations on each step for i in range(n): result += abs(arr[i] - (i + 1)) # Return the answer return result # Driver codeif __name__ == '__main__': arr=[0, 2, 3, 4, 1, 6, 8, 9] n = len(arr) # Function call print(get_permutation(arr, n)) # This code is contributed by mohit kumar 29 // C# program to find minimum number of steps to// convert a given sequence into a permutationusing System; class GFG{ // Function to find minimum number of steps to// convert a given sequence into a permutationstatic int get_permutation(int []arr, int n){ // Sort the given array Array.Sort(arr); // To store the required minimum // number of operations int result = 0; // Find the operations on each step for (int i = 0; i < n; i++) { result += Math.Abs(arr[i] - (i + 1)); } // Return the answer return result;} // Driver Codepublic static void Main(){ int []arr = { 0, 2, 3, 4, 1, 6, 8, 9 }; int n = arr.Length; // Function call Console.Write(get_permutation(arr, n));}} // This code is contributed by shivanisinghss2110 <script>// javascript program to find minimum number of steps to// convert a given sequence into a permutation // Function to find minimum number of steps to// convert a given sequence into a permutationfunction get_permutation(arr , n){ // Sort the given array arr.sort(); // To store the required minimum // number of operations var result = 0; // Find the operations on each step for (i = 0; i < n; i++) { result += Math.abs(arr[i] - (i + 1)); } // Return the answer return result;} // Driver codevar arr = [ 0, 2, 3, 4, 1, 6, 8, 9 ];var n = arr.length; // Function calldocument.write(get_permutation(arr, n)); // This code is contributed by Amit Katiyar</script> 7 Time Complexity: O(n*log(n))Auxiliary Space: O(1) mohit kumar 29 29AjayKumar shivanisinghss2110 amit143katiyar pushpeshrajdx01 Natural Numbers permutation Arrays Sorting Arrays Sorting permutation Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n28 Jun, 2022" }, { "code": null, "e": 275, "s": 28, "text": "Given an array arr of length N, the task is to count the minimum number of operations to convert given sequence into a permutation of first N natural numbers (1, 2, ...., N). In each operation, increment or decrement an element by one.Examples: " }, { "code": null, "e": 411, "s": 275, "text": "Input: arr[] = {4, 1, 3, 6, 5} Output: 4 Apply decrement operation four times on 6Input : arr[] = {0, 2, 3, 4, 1, 6, 8, 9} Output : 7 " }, { "code": null, "e": 691, "s": 413, "text": "Approach: An efficient approach is to sort the given array and for each element, find the difference between the arr[i] and i(1 based indexing). Find the sum of all such difference, and this will be the minimum steps required.Below is the implementation of the above approach: " }, { "code": null, "e": 695, "s": 691, "text": "CPP" }, { "code": null, "e": 700, "s": 695, "text": "Java" }, { "code": null, "e": 708, "s": 700, "text": "Python3" }, { "code": null, "e": 711, "s": 708, "text": "C#" }, { "code": null, "e": 722, "s": 711, "text": "Javascript" }, { "code": "// C++ program to find minimum number of steps to// convert a given sequence into a permutation #include <bits/stdc++.h>using namespace std; // Function to find minimum number of steps to// convert a given sequence into a permutationint get_permutation(int arr[], int n){ // Sort the given array sort(arr, arr + n); // To store the required minimum // number of operations int result = 0; // Find the operations on each step for (int i = 0; i < n; i++) { result += abs(arr[i] - (i + 1)); } // Return the answer return result;} // Driver codeint main(){ int arr[] = { 0, 2, 3, 4, 1, 6, 8, 9 }; int n = sizeof(arr) / sizeof(arr[0]); // Function call cout << get_permutation(arr, n); return 0;}", "e": 1472, "s": 722, "text": null }, { "code": "// Java program to find minimum number of steps to// convert a given sequence into a permutationimport java.util.*; class GFG{ // Function to find minimum number of steps to// convert a given sequence into a permutationstatic int get_permutation(int arr[], int n){ // Sort the given array Arrays.sort(arr); // To store the required minimum // number of operations int result = 0; // Find the operations on each step for (int i = 0; i < n; i++) { result += Math.abs(arr[i] - (i + 1)); } // Return the answer return result;} // Driver codepublic static void main(String[] args){ int arr[] = { 0, 2, 3, 4, 1, 6, 8, 9 }; int n = arr.length; // Function call System.out.print(get_permutation(arr, n)); }} // This code is contributed by 29AjayKumar", "e": 2277, "s": 1472, "text": null }, { "code": "# Python3 program to find minimum number of steps to# convert a given sequence into a permutation # Function to find minimum number of steps to# convert a given sequence into a permutationdef get_permutation(arr, n): # Sort the given array arr = sorted(arr) # To store the required minimum # number of operations result = 0 # Find the operations on each step for i in range(n): result += abs(arr[i] - (i + 1)) # Return the answer return result # Driver codeif __name__ == '__main__': arr=[0, 2, 3, 4, 1, 6, 8, 9] n = len(arr) # Function call print(get_permutation(arr, n)) # This code is contributed by mohit kumar 29 ", "e": 2949, "s": 2277, "text": null }, { "code": "// C# program to find minimum number of steps to// convert a given sequence into a permutationusing System; class GFG{ // Function to find minimum number of steps to// convert a given sequence into a permutationstatic int get_permutation(int []arr, int n){ // Sort the given array Array.Sort(arr); // To store the required minimum // number of operations int result = 0; // Find the operations on each step for (int i = 0; i < n; i++) { result += Math.Abs(arr[i] - (i + 1)); } // Return the answer return result;} // Driver Codepublic static void Main(){ int []arr = { 0, 2, 3, 4, 1, 6, 8, 9 }; int n = arr.Length; // Function call Console.Write(get_permutation(arr, n));}} // This code is contributed by shivanisinghss2110", "e": 3728, "s": 2949, "text": null }, { "code": "<script>// javascript program to find minimum number of steps to// convert a given sequence into a permutation // Function to find minimum number of steps to// convert a given sequence into a permutationfunction get_permutation(arr , n){ // Sort the given array arr.sort(); // To store the required minimum // number of operations var result = 0; // Find the operations on each step for (i = 0; i < n; i++) { result += Math.abs(arr[i] - (i + 1)); } // Return the answer return result;} // Driver codevar arr = [ 0, 2, 3, 4, 1, 6, 8, 9 ];var n = arr.length; // Function calldocument.write(get_permutation(arr, n)); // This code is contributed by Amit Katiyar</script>", "e": 4441, "s": 3728, "text": null }, { "code": null, "e": 4443, "s": 4441, "text": "7" }, { "code": null, "e": 4495, "s": 4445, "text": "Time Complexity: O(n*log(n))Auxiliary Space: O(1)" }, { "code": null, "e": 4510, "s": 4495, "text": "mohit kumar 29" }, { "code": null, "e": 4522, "s": 4510, "text": "29AjayKumar" }, { "code": null, "e": 4541, "s": 4522, "text": "shivanisinghss2110" }, { "code": null, "e": 4556, "s": 4541, "text": "amit143katiyar" }, { "code": null, "e": 4572, "s": 4556, "text": "pushpeshrajdx01" }, { "code": null, "e": 4588, "s": 4572, "text": "Natural Numbers" }, { "code": null, "e": 4600, "s": 4588, "text": "permutation" }, { "code": null, "e": 4607, "s": 4600, "text": "Arrays" }, { "code": null, "e": 4615, "s": 4607, "text": "Sorting" }, { "code": null, "e": 4622, "s": 4615, "text": "Arrays" }, { "code": null, "e": 4630, "s": 4622, "text": "Sorting" }, { "code": null, "e": 4642, "s": 4630, "text": "permutation" } ]
Multi Page Applications in Flutter
13 Jun, 2022 Apps are widely used by humans in this techie world. The number of apps in the app store is increasing day by day. Due to this competition, app developers have started to add a number of features to their apps. To reduce this complexity, the content of the app is mostly divided into various pages so that the user can navigate between these pages with ease. Flutter is an open-source mobile app SDK, that is used to develop cross-platform mobile applications. Flutter is becoming popular these years because of its stunning features like hot reload, attractive UIs, etc. In Flutter, everything is a Widget. Routes and Navigators: In Flutter, pages/screens are called Routes. The process of navigating from one route to another is performed by a widget called the Navigator. The navigator maintains all its child routes in the form of stacks. It has many methods like push() and pop() which works under stack discipline. But, for multi-page applications, we are going to use a unique method called the pushNamed(). This method mainly follows object-oriented concepts. The Navigator.pushNamed() method is used to call a route, whose class has been created and defined beforehand. It is just like calling a class when needed in OOPs. Now, let us move on to creating our Multi-Page Application. Creating a Route: Routes are mainly created in the form of classes. Each route has a unique class with unique contents and UI in them. Here, we are going to create three routes namely, HomeRoute(), SecondRoute() and ThirdRoute(). Each route will have an App bar containing a unique title and a raised button for navigating between the routes. A route can be created as follows: Dart class HomeRoute extends StatelessWidget { const HomeRoute({Key? key}) : super(key: key); @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: const Text('Geeks for Geeks'), backgroundColor: Colors.green, ), // AppBar body: Center( child: Column( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ ElevatedButton( child: const Text('Click Me!'), onPressed: () { Navigator.pushNamed(context, '/second'); }, ), // ElevatedButton ElevatedButton( child: const Text('Tap Me!'), onPressed: () { Navigator.pushNamed(context, '/third'); }, ), // ElevatedButton ], // <Widget>[] ), // Column ), // Center ); // Scaffold }} Defining the Routes: Before navigating between routes, it is highly essential to define them in the MaterialApp widget. This helps us to access and call them as easily as possible. Since we are initializing the first route, it is not necessary for us to mention the home route. The routes can be defined as follows: Dart // function to trigger build when the app is runvoid main() { runApp(MaterialApp( initialRoute: '/', routes: { '/': (context) => const HomeRoute(), '/second': (context) => const SecondRoute(), '/third': (context) => const ThirdRoute(), }, )); //MaterialApp} From the code, it is understood that each route has been named uniquely. So, when the navigator widget encounters any of these names in the route class then it navigates to the respective route. The initialRoute in this code specifies the starting route of the app and it is symbolized by ‘/’ symbol. It is a mandatory thing to initialize the home page in this widget. Navigating to a Page: The Navigator.pushNamed() method comes into play in this segment. This method calls the name of a particular route in a route class. Thereby, initializing the navigation process. The navigation can be done as follows: Dart onPressed: () { Navigator.pushNamed(context, '/second');} Navigating back: But, when it comes to visiting the most recent route visited, Navigator.pop() method can be used. It helps us to navigate back to the last route. In this case, the stack discipline is as followed. The pop method is used as follows: Dart onPressed: () { Navigator.pop(context);} So, now let’s see how it’s all these codes have been combined to create this Multi-Page Application. Dart import 'package:flutter/material.dart'; // function to trigger build when the app is runvoid main() { runApp(MaterialApp( initialRoute: '/', routes: { '/': (context) => const HomeRoute(), '/second': (context) => const SecondRoute(), '/third': (context) => const ThirdRoute(), }, )); //MaterialApp} class HomeRoute extends StatelessWidget { const HomeRoute({Key? key}) : super(key: key); @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: const Text('Geeks for Geeks'), backgroundColor: Colors.green, ), // AppBar body: Center( child: Column( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ ElevatedButton( child: const Text('Click Me!'), onPressed: () { Navigator.pushNamed(context, '/second'); }, ), // ElevatedButton ElevatedButton( child: const Text('Tap Me!'), onPressed: () { Navigator.pushNamed(context, '/third'); }, ), // ElevatedButton ], // <Widget>[] ), // Column ), // Center ); // Scaffold }} class SecondRoute extends StatelessWidget { const SecondRoute({Key? key}) : super(key: key); @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: const Text("Click Me Page"), backgroundColor: Colors.green, ), // AppBar body: Center( child: ElevatedButton( onPressed: () { Navigator.pop(context); }, child: const Text('Back!'), ), // ElevatedButton ), // Center ); // Scaffold }} class ThirdRoute extends StatelessWidget { const ThirdRoute({Key? key}) : super(key: key); @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: const Text("Tap Me Page"), backgroundColor: Colors.green, ), // AppBar ); // Scaffold }} Output: ankit_kumar_ Flutter Web Technologies Web technologies Questions Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n13 Jun, 2022" }, { "code": null, "e": 413, "s": 54, "text": "Apps are widely used by humans in this techie world. The number of apps in the app store is increasing day by day. Due to this competition, app developers have started to add a number of features to their apps. To reduce this complexity, the content of the app is mostly divided into various pages so that the user can navigate between these pages with ease." }, { "code": null, "e": 662, "s": 413, "text": "Flutter is an open-source mobile app SDK, that is used to develop cross-platform mobile applications. Flutter is becoming popular these years because of its stunning features like hot reload, attractive UIs, etc. In Flutter, everything is a Widget." }, { "code": null, "e": 1122, "s": 662, "text": "Routes and Navigators: In Flutter, pages/screens are called Routes. The process of navigating from one route to another is performed by a widget called the Navigator. The navigator maintains all its child routes in the form of stacks. It has many methods like push() and pop() which works under stack discipline. But, for multi-page applications, we are going to use a unique method called the pushNamed(). This method mainly follows object-oriented concepts." }, { "code": null, "e": 1346, "s": 1122, "text": "The Navigator.pushNamed() method is used to call a route, whose class has been created and defined beforehand. It is just like calling a class when needed in OOPs. Now, let us move on to creating our Multi-Page Application." }, { "code": null, "e": 1724, "s": 1346, "text": "Creating a Route: Routes are mainly created in the form of classes. Each route has a unique class with unique contents and UI in them. Here, we are going to create three routes namely, HomeRoute(), SecondRoute() and ThirdRoute(). Each route will have an App bar containing a unique title and a raised button for navigating between the routes. A route can be created as follows:" }, { "code": null, "e": 1729, "s": 1724, "text": "Dart" }, { "code": "class HomeRoute extends StatelessWidget { const HomeRoute({Key? key}) : super(key: key); @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: const Text('Geeks for Geeks'), backgroundColor: Colors.green, ), // AppBar body: Center( child: Column( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ ElevatedButton( child: const Text('Click Me!'), onPressed: () { Navigator.pushNamed(context, '/second'); }, ), // ElevatedButton ElevatedButton( child: const Text('Tap Me!'), onPressed: () { Navigator.pushNamed(context, '/third'); }, ), // ElevatedButton ], // <Widget>[] ), // Column ), // Center ); // Scaffold }}", "e": 2628, "s": 1729, "text": null }, { "code": null, "e": 2944, "s": 2628, "text": "Defining the Routes: Before navigating between routes, it is highly essential to define them in the MaterialApp widget. This helps us to access and call them as easily as possible. Since we are initializing the first route, it is not necessary for us to mention the home route. The routes can be defined as follows:" }, { "code": null, "e": 2949, "s": 2944, "text": "Dart" }, { "code": "// function to trigger build when the app is runvoid main() { runApp(MaterialApp( initialRoute: '/', routes: { '/': (context) => const HomeRoute(), '/second': (context) => const SecondRoute(), '/third': (context) => const ThirdRoute(), }, )); //MaterialApp}", "e": 3233, "s": 2949, "text": null }, { "code": null, "e": 3604, "s": 3233, "text": "From the code, it is understood that each route has been named uniquely. So, when the navigator widget encounters any of these names in the route class then it navigates to the respective route. The initialRoute in this code specifies the starting route of the app and it is symbolized by ‘/’ symbol. It is a mandatory thing to initialize the home page in this widget. " }, { "code": null, "e": 3844, "s": 3604, "text": "Navigating to a Page: The Navigator.pushNamed() method comes into play in this segment. This method calls the name of a particular route in a route class. Thereby, initializing the navigation process. The navigation can be done as follows:" }, { "code": null, "e": 3849, "s": 3844, "text": "Dart" }, { "code": "onPressed: () { Navigator.pushNamed(context, '/second');}", "e": 3908, "s": 3849, "text": null }, { "code": null, "e": 4157, "s": 3908, "text": "Navigating back: But, when it comes to visiting the most recent route visited, Navigator.pop() method can be used. It helps us to navigate back to the last route. In this case, the stack discipline is as followed. The pop method is used as follows:" }, { "code": null, "e": 4162, "s": 4157, "text": "Dart" }, { "code": "onPressed: () { Navigator.pop(context);}", "e": 4204, "s": 4162, "text": null }, { "code": null, "e": 4305, "s": 4204, "text": "So, now let’s see how it’s all these codes have been combined to create this Multi-Page Application." }, { "code": null, "e": 4310, "s": 4305, "text": "Dart" }, { "code": "import 'package:flutter/material.dart'; // function to trigger build when the app is runvoid main() { runApp(MaterialApp( initialRoute: '/', routes: { '/': (context) => const HomeRoute(), '/second': (context) => const SecondRoute(), '/third': (context) => const ThirdRoute(), }, )); //MaterialApp} class HomeRoute extends StatelessWidget { const HomeRoute({Key? key}) : super(key: key); @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: const Text('Geeks for Geeks'), backgroundColor: Colors.green, ), // AppBar body: Center( child: Column( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ ElevatedButton( child: const Text('Click Me!'), onPressed: () { Navigator.pushNamed(context, '/second'); }, ), // ElevatedButton ElevatedButton( child: const Text('Tap Me!'), onPressed: () { Navigator.pushNamed(context, '/third'); }, ), // ElevatedButton ], // <Widget>[] ), // Column ), // Center ); // Scaffold }} class SecondRoute extends StatelessWidget { const SecondRoute({Key? key}) : super(key: key); @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: const Text(\"Click Me Page\"), backgroundColor: Colors.green, ), // AppBar body: Center( child: ElevatedButton( onPressed: () { Navigator.pop(context); }, child: const Text('Back!'), ), // ElevatedButton ), // Center ); // Scaffold }} class ThirdRoute extends StatelessWidget { const ThirdRoute({Key? key}) : super(key: key); @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: const Text(\"Tap Me Page\"), backgroundColor: Colors.green, ), // AppBar ); // Scaffold }}", "e": 6345, "s": 4310, "text": null }, { "code": null, "e": 6354, "s": 6345, "text": " Output:" }, { "code": null, "e": 6369, "s": 6356, "text": "ankit_kumar_" }, { "code": null, "e": 6377, "s": 6369, "text": "Flutter" }, { "code": null, "e": 6394, "s": 6377, "text": "Web Technologies" }, { "code": null, "e": 6421, "s": 6394, "text": "Web technologies Questions" } ]
Kotlin Android Extensions
30 May, 2022 If you’ve been developing Android Apps for some time, you’re probably already tired of working with findViewById in your day-to-day life to recover views. Or maybe you gave up and started using the famous Butterknife library. If that’s your case, then you’ll love Kotlin Android Extensions. Kotlin has a built-in view injection for Android, allowing to skip manual binding or need for frameworks such as ButterKnife. Some of the advantages are a nicer syntax, better static typing, and thus being less error-prone. In your project-local (not top-level) build.gradle append extensions plugin declaration below your Kotlin plugin, on top-level indentation level. buildscript { ... } id : "com.android.application" ... id: "kotlin-android" id "kotlin-android-extensions" ... Assuming we have an activity with an example layout called activity_main.xml: XML <?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent"> <Button android:id="@+id/my_button" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="My button"/></LinearLayout> We can use Kotlin extensions to call the button without any additional binding like so: Kotlin import kotlinx.android.synthetic.main.activity_main.my_button class MainActivity: Activity() { override fun onCreate(savedInstanceBundle: Bundle?) { super.onCreate(savedInstanceBundle) setContentView(R.layout.activity_main) // my_button is already casted // to a proper type of "Button" // instead of being a "View" my_button.setText("Kotlin rocks!") }} You can also import all ids appearing in layout with a * notation // my_button can be used the same way as before import kotlinx.android.synthetic.main.activity_main.* Synthetic views can’t be used outside of Activities/Fragments/Views with that layout inflated: Kotlin import kotlinx.android.synthetic.main.activity_main.my_button class NotAView { init { // This sample won't compile! my_button.setText("Kotlin rocks!") }} Android extensions also work with multiple Android Product Flavors. For example, if we have flavors in the build.gradle like so: android { productFlavors { paid { ... } free { ... } } } And for example, only the free flavor has a buy button: XML <?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent"> <Button android:id="@+id/buy_button" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Buy full version"/></LinearLayout> We can bind to the flavor specifically: import kotlinx.android.synthetic.free.main_activity.buy_button Painful listener for getting noticed, when the view is completely drawn now is so simple and awesome with Kotlin’s extension mView.afterMeasured { // inside this block the view is completely drawn // you can get view's height/width, it.height / it.width } Under the Hood Kotlin inline fun View.afterMeasured(crossinline f: View.() -> Unit) { viewTreeObserver.addOnGlobalLayoutListener(object : ViewTreeObserver.OnGlobalLayoutListener { override fun onGlobalLayout() { if (measuredHeight > 0 && measuredWidth > 0) { viewTreeObserver.removeOnGlobalLayoutListener(this) f() } } })} ubedk Kotlin Android Android Kotlin Android Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n30 May, 2022" }, { "code": null, "e": 689, "s": 28, "text": "If you’ve been developing Android Apps for some time, you’re probably already tired of working with findViewById in your day-to-day life to recover views. Or maybe you gave up and started using the famous Butterknife library. If that’s your case, then you’ll love Kotlin Android Extensions. Kotlin has a built-in view injection for Android, allowing to skip manual binding or need for frameworks such as ButterKnife. Some of the advantages are a nicer syntax, better static typing, and thus being less error-prone. In your project-local (not top-level) build.gradle append extensions plugin declaration below your Kotlin plugin, on top-level indentation level." }, { "code": null, "e": 800, "s": 689, "text": "buildscript {\n...\n}\nid : \"com.android.application\"\n...\nid: \"kotlin-android\"\nid \"kotlin-android-extensions\"\n..." }, { "code": null, "e": 878, "s": 800, "text": "Assuming we have an activity with an example layout called activity_main.xml:" }, { "code": null, "e": 882, "s": 878, "text": "XML" }, { "code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><LinearLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\"> <Button android:id=\"@+id/my_button\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:text=\"My button\"/></LinearLayout>", "e": 1258, "s": 882, "text": null }, { "code": null, "e": 1346, "s": 1258, "text": "We can use Kotlin extensions to call the button without any additional binding like so:" }, { "code": null, "e": 1353, "s": 1346, "text": "Kotlin" }, { "code": "import kotlinx.android.synthetic.main.activity_main.my_button class MainActivity: Activity() { override fun onCreate(savedInstanceBundle: Bundle?) { super.onCreate(savedInstanceBundle) setContentView(R.layout.activity_main) // my_button is already casted // to a proper type of \"Button\" // instead of being a \"View\" my_button.setText(\"Kotlin rocks!\") }}", "e": 1728, "s": 1353, "text": null }, { "code": null, "e": 1794, "s": 1728, "text": "You can also import all ids appearing in layout with a * notation" }, { "code": null, "e": 1842, "s": 1794, "text": "// my_button can be used the same way as before" }, { "code": null, "e": 1896, "s": 1842, "text": "import kotlinx.android.synthetic.main.activity_main.*" }, { "code": null, "e": 1991, "s": 1896, "text": "Synthetic views can’t be used outside of Activities/Fragments/Views with that layout inflated:" }, { "code": null, "e": 1998, "s": 1991, "text": "Kotlin" }, { "code": "import kotlinx.android.synthetic.main.activity_main.my_button class NotAView { init { // This sample won't compile! my_button.setText(\"Kotlin rocks!\") }}", "e": 2160, "s": 1998, "text": null }, { "code": null, "e": 2289, "s": 2160, "text": "Android extensions also work with multiple Android Product Flavors. For example, if we have flavors in the build.gradle like so:" }, { "code": null, "e": 2374, "s": 2289, "text": "android {\n productFlavors {\n paid {\n ...\n }\n free {\n ...\n }\n }\n}" }, { "code": null, "e": 2430, "s": 2374, "text": "And for example, only the free flavor has a buy button:" }, { "code": null, "e": 2434, "s": 2430, "text": "XML" }, { "code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><LinearLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\"> <Button android:id=\"@+id/buy_button\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:text=\"Buy full version\"/></LinearLayout>", "e": 2800, "s": 2434, "text": null }, { "code": null, "e": 2840, "s": 2800, "text": "We can bind to the flavor specifically:" }, { "code": null, "e": 2903, "s": 2840, "text": "import kotlinx.android.synthetic.free.main_activity.buy_button" }, { "code": null, "e": 3028, "s": 2903, "text": "Painful listener for getting noticed, when the view is completely drawn now is so simple and awesome with Kotlin’s extension" }, { "code": null, "e": 3159, "s": 3028, "text": "mView.afterMeasured {\n// inside this block the view is completely drawn\n// you can get view's height/width, it.height / it.width\n}" }, { "code": null, "e": 3174, "s": 3159, "text": "Under the Hood" }, { "code": null, "e": 3181, "s": 3174, "text": "Kotlin" }, { "code": "inline fun View.afterMeasured(crossinline f: View.() -> Unit) { viewTreeObserver.addOnGlobalLayoutListener(object : ViewTreeObserver.OnGlobalLayoutListener { override fun onGlobalLayout() { if (measuredHeight > 0 && measuredWidth > 0) { viewTreeObserver.removeOnGlobalLayoutListener(this) f() } } })}", "e": 3508, "s": 3181, "text": null }, { "code": null, "e": 3514, "s": 3508, "text": "ubedk" }, { "code": null, "e": 3529, "s": 3514, "text": "Kotlin Android" }, { "code": null, "e": 3537, "s": 3529, "text": "Android" }, { "code": null, "e": 3544, "s": 3537, "text": "Kotlin" }, { "code": null, "e": 3552, "s": 3544, "text": "Android" } ]
NLP Gensim Tutorial – Complete Guide For Beginners
16 Aug, 2021 This tutorial is going to provide you with a walk-through of the Gensim library.Gensim : It is an open source library in python written by Radim Rehurek which is used in unsupervised topic modelling and natural language processing. It is designed to extract semantic topics from documents. It can handle large text collections. Hence it makes it different from other machine learning software packages which target memory processing. Gensim also provides efficient multicore implementations for various algorithms to increase processing speed. It provides more convenient facilities for text processing than other packages like Scikit-learn, R etc.This tutorial will cover these concepts: Create a Corpus from a given DatasetCreate a TFIDF matrix in GensimCreate Bigrams and Trigrams with GensimCreate Word2Vec model using GensimCreate Doc2Vec model using GensimCreate Topic Model with LDACreate Topic Model with LSICompute Similarity MatricesSummarize text documents Create a Corpus from a given Dataset Create a TFIDF matrix in Gensim Create Bigrams and Trigrams with Gensim Create Word2Vec model using Gensim Create Doc2Vec model using Gensim Create Topic Model with LDA Create Topic Model with LSI Compute Similarity Matrices Summarize text documents Let us understand what some of the below mentioned terms mean before moving forward. Corpus: A collection of text documents. Vector: Form of representing text. Model: Algorithm used to generate representation of data. Topic Modelling: It is an information mining tool which is used to extract semantic topics from documents. Topic: A repeating group of words frequently occurring together. For example: You have a document which consists of words like - bat, car, racquet, score, glass, drive, cup, keys, water, game, steering, liquid These can be grouped into different topics as- Some of the Topic Modelling Techniques are – Latent Semantic Indexing(LSI) Latent Dirichlet Allocation(LDA) Now that we have the basic idea of the terminologies let’s start with the use of Gensim package.First Install the library using the commands- #for linux #for anaconda prompt Step 1: Create a Corpus from a given Dataset You need to follow these steps to create your corpus: Load your DatasetPreprocess the DatasetCreate a DictionaryCreate Bag of Words Corpus Load your Dataset Preprocess the Dataset Create a Dictionary Create Bag of Words Corpus 1.1 Load your Dataset: You can have a .txt file as your dataset or you can also load datasets using the Gensim Downloader API. Code: python3 import os # open the text file as an objectdoc = open('sample_data.txt', encoding ='utf-8') Gensim Downloader API: This is a module available in the Gensim library which is an API for downloading, getting information and loading datasets/models. Code: python3 import gensim.downloader as api # check available models and datasetsinfo_datasets = api.info()print(info_datasets)#>{'corpora':#> {'semeval-2016-2017-task3-subtaskBC':#> {'num_records': -1, 'record_format': 'dict', 'file_size': 6344358, ....} # information of a particular datasetdataset_info = api.info("text8") # load the "text8" datasetdataset = api.load("text8") # load a pre-trained modelword2vec_model = api.load('word2vec-google-news-300') Here we are going to consider a text file as raw dataset which consist of data from a wikipedia page. 1.2 Preprocess the Dataset Text preprocessing: In natural language preprocessing, text preprocessing is the practice of cleaning and preparing text data. For this purpose we will use the simple_preprocess( ) function.This function returns a list of tokens after tokenizing and normalizing them. Code: python3 import gensimimport osfrom gensim.utils import simple_preprocess # open the text file as an objectdoc = open('sample_data.txt', encoding ='utf-8') # preprocess the file to get a list of tokenstokenized =[]for sentence in doc.read().split('.'): # the simple_preprocess function returns a list of each sentence tokenized.append(simple_preprocess(sentence, deacc = True)) print(tokenized) Output: Output: tokenized 1.3 Create a Dictionary Now we have our preprocessed data which can be converted into a dictionary by using the corpora.Dictionary( ) function. This dictionary is a map for unique tokens.Code: python3 from gensim import corpora# storing the extracted tokens into the dictionarymy_dictionary = corpora.Dictionary(tokenized)print(my_dictionary) Output: my_dictionary 1.3.1 Saving Dictionary on Disk or as Text File You can save/load your dictionary on the disk as well as a text file as mentioned below: Code: python3 # save your dictionary to diskmy_dictionary.save('my_dictionary.dict') # load backload_dict = corpora.Dictionary.load(my_dictionary.dict') # save your dictionary as text filefrom gensim.test.utils import get_tmpfiletmp_fname = get_tmpfile("dictionary")my_dictionary.save_as_text(tmp_fname) # load your dictionary text fileload_dict = corpora.Dictionary.load_from_text(tmp_fname) 1.4 Create Bag of Words Corpus Once we have the dictionary we can create a Bag of Word corpus using the doc2bow( ) function. This function counts the number of occurrences of each distinct word, convert the word to its integer word id and then the result is returned as a sparse vector.Code: python3 # converting to a bag of word corpusBoW_corpus =[my_dictionary.doc2bow(doc, allow_update = True) for doc in tokenized]print(BoW_corpus) Output: BoW_corpus 1.4.1 Saving Corpus on Disk: Code: To save/load your corpus python3 from gensim.corpora import MmCorpusfrom gensim.test.utils import get_tmpfile output_fname = get_tmpfile("BoW_corpus.mm") # save corpus to diskMmCorpus.serialize(output_fname, BoW_corpus) # load corpusload_corpus = MmCorpus(output_fname) Step 2: Create a TFIDF matrix in Gensim TFIDF: Stands for Term Frequency – Inverse Document Frequency. It is a commonly used natural language processing model that helps you determine the most important words in each document in a corpus. This was designed for a modest-size corpora.Some words might not be stopwords but may occur more often in the documents and may be of less importance. Hence these words need to be removed or down-weighted in importance. The TFIDF model takes the text that share a common language and ensures that most common words across the entire corpus don’t show as keywords. You can build a TFIDF model using Gensim and the corpus you developed previously as:Code: python3 from gensim import modelsimport numpy as np # Word weight in Bag of Words corpusword_weight =[]for doc in BoW_corpus: for id, freq in doc: word_weight.append([my_dictionary[id], freq])print(word_weight) Output: Word weight before applying TFIDF Model Code: applying TFIDF model python3 # create TF-IDF modeltfIdf = models.TfidfModel(BoW_corpus, smartirs ='ntc') # TF-IDF Word Weightweight_tfidf =[]for doc in tfIdf[BoW_corpus]: for id, freq in doc: weight_tfidf.append([my_dictionary[id], np.around(freq, decimals = 3)])print(weight_tfidf) Output: word weights after applying TFIDF model You can see that the words occurring frequently across the documents now have lower weights assigned.Step 3: Creating Bigrams and Trigrams with Genism Many words tend to occur in the content together. The words when occur together have a different meaning than as individuals. for example: Beatboxing --> the word beat and boxing individually have meanings of their own but these together have a different meaning. Bigrams: Group of two words Trigrams: Group of three wordsWe will be using the text8 dataset here which can be downloaded using the Gensim downloader API Code: Building bigrams and trigrams python3 import gensim.downloader as apifrom gensim.models.phrases import Phrases # load the text8 datasetdataset = api.load("text8") # extract a list of words from the datasetdata =[]for word in dataset: data.append(word) # Bigram using Phraser Model bigram_model = Phrases(data, min_count = 3, threshold = 10) print(bigram_model[data[0]]) Bigram model To create a Trigram we simply pass the above obtained bigram model to the same function. Code: python3 # Trigram using Phraser Modeltrigram_model = Phrases(bigram_model[data], threshold = 10) # trigramprint(trigram_model[bigram_model[data[0]]]) Output: Trigram python3 import gensim.downloader as apifrom multiprocessing import cpu_countfrom gensim.models.word2vec import Word2Vec # load the text8 datasetdataset = api.load("text8") # extract a list of words from the datasetdata =[]for word in dataset: data.append(word) # We will split the data into two partsdata_1 = data[:1200] # this is used to train the modeldata_2 = data[1200:] # this part will be used to update the model # Training the Word2Vec modelw2v_model = Word2Vec(data_1, min_count = 0, workers = cpu_count()) # word vector for the word "time"print(w2v_model['time']) Output: word vector for the word time You can also use the most_similar( ) function to find similar words to a given word.Code: python3 # similar words to the word "time"print(w2v_model.most_similar('time')) # save your modelw2v_model.save('Word2VecModel') # load your modelmodel = Word2Vec.load('Word2VecModel') Output: most similar words to ‘time’ 4.2) Update the modelCode: python3 # build model vocabulary from a sequence of sentencesw2v_model.build_vocab(data_2, update = True) # train word vectorsw2v_model.train(data_2, total_examples = w2v_model.corpus_count, epochs = w2v_model.iter) print(w2v_model['time']) Output: Step 5: Create Doc2Vec model using Gensim In contrast to the Word2Vec model, the Doc2Vec model gives the vector representation for an entire document or group of words. With the help of this model, we can find the relationship among different documents such as- If we train the model for literature such as "Through the Looking Glass".We can say that- 5.1) Train the modelCode: python3 import gensimimport gensim.downloader as apifrom gensim.models import doc2vec # get datasetdataset = api.load("text8")data =[]for w in dataset: data.append(w) # To train the model we need a list of tagged documentsdef tagged_document(list_of_ListOfWords): for x, ListOfWords in enumerate(list_of_ListOfWords): yield doc2vec.TaggedDocument(ListOfWords, [x]) # training datadata_train = list(tagged_document(data)) # print trained datasetprint(data_train[:1]) Output: OUTPUT – trained dataset 5.2) Update the modelCode: python3 # Initialize the modeld2v_model = doc2vec.Doc2Vec(vector_size = 40, min_count = 2, epochs = 30) # build the vocabularyd2v_model.build_vocab(data_train) # Train Doc2Vec modeld2v_model.train(data_train, total_examples = d2v_model.corpus_count, epochs = d2v_model.epochs) # Analyzing the outputAnalyze = d2v_model.infer_vector(['violent', 'means', 'to', 'destroy'])print(Analyze) Output: Output of updated model Step 6: Create Topic model with LDA LDA is a popular method for topic modelling which considers each document as a collection of topics in a certain proportion. We need to take out the good quality of topics such as how segregated and meaningful they are. The good quality topics depend on- the quality of text processingfinding the optimal number of topicsTuning parameters of the algorithm the quality of text processing finding the optimal number of topics Tuning parameters of the algorithm NOTE: If you run this code on python3.7 version you might get a StopIteration Error. It is advisable to use python3.6 version for this. Follow the below steps to create the model: 6.1 Prepare the Data This is done by removing the stopwords and then lemmatizing it. In order to lemmatize using Gensim, we need to first download the pattern package and the stopwords. #download pattern package pip install pattern #run in python console >> import nltk >> nltk.download('stopwords') Code: python3 import gensimfrom gensim import corporafrom gensim.models import LdaModel, LdaMulticoreimport gensim.downloader as apifrom gensim.utils import simple_preprocess, lemmatize# from pattern.en import lemmaimport nltk# nltk.download('stopwords')from nltk.corpus import stopwordsimport reimport logging logging.basicConfig(format ='%(asctime)s : %(levelname)s : %(message)s')logging.root.setLevel(level = logging.INFO) # import stopwordsstop_words = stopwords.words('english')# add stopwordsstop_words = stop_words + ['subject', 'com', 'are', 'edu', 'would', 'could'] # import the datasetdataset = api.load("text8")data = [w for w in dataset] # Preparing the dataprocessed_data = [] for x, doc in enumerate(data[:100]): doc_out = [] for word in doc: if word not in stop_words: # to remove stopwords Lemmatized_Word = lemmatize(word, allowed_tags = re.compile('(NN|JJ|RB)')) # lemmatize if Lemmatized_Word: doc_out.append(Lemmatized_Word[0].split(b'/')[0].decode('utf-8')) else: continue processed_data.append(doc_out) # processed_data is a list of list of words # Print sample print(processed_data[0][:10]) Output: OUTPUT – processed_data 6.2 Create Dictionary and Corpus The processed data will now be used to create the dictionary and corpus. Code: python3 # create dictionary and corpusdict = corpora.Dictionary(processed_data)Corpus = [dict.doc2bow(l) for l in processed_data] 6.3 Train LDA model We will be training the LDA model with 5 topics using the dictionary and corpus created previously.Here the LdaModel( ) function is used but you can also use the LdaMulticore( ) function as it allows parallel processing. Code: python3 # TrainingLDA_model = LdaModel(corpus = LDA_corpus, num_topics = 5)# save modelLDA_model.save('LDA_model.model') # show topicsprint(LDA_model.print_topics(-1)) Output: OUTPUT – topics The words which can be seen in more than one topic and are of less relevance can be added to the stopwords list.6.4 Interpret the Output The LDA model majorly gives us information regarding 3 things: Topics in the documentWhat topic each word belongs toPhi value Topics in the document What topic each word belongs to Phi value Phi value: It is the probability of a word to lie in a particular topic.For a given word, sum of the phi values give the number of times that word occured in the document.Code: python3 # probability of a word belonging to a topicLDA_model.get_term_topics('fire') bow_list =['time', 'space', 'car']# convert to bag of words format firstbow = LDA_model.id2word.doc2bow(bow_list) # interpreting the datadoc_topics, word_topics, phi_values = LDA_model.get_document_topics(bow, per_word_topics = True) Step 7: Create Topic Model with LSI To create the model with LSI just follow the steps same as with LDA. The only difference will be while training the model.Use the LsiModel( ) function instead of the LdaMulticore( ) or LdaModel( ). Code: python3 # Training the model with LSILSI_model = LsiModel(corpus = Corpus, id2word = dct, num_topics = 7, decay = 0.5) # Topicsprint(LSI_model.print_topics(-1)) Step 8: Compute Similarity Matrices Cosine Similarity: It is a measure of similarity between two non-zero vectors of an inner product space. It is defined to equal the cosine of the angle between them.Soft Cosine Similarity: It is similar to cosine similarity but the difference is that cosine similarity considers the vector space model(VSM) features as independent whereas soft cosine proposes to consider the similarity of features in VSM.We need to take a word embedding model to compute soft cosines.Here we are using the pre-trained word2vec model. Note: If you run this code on python3.7 version you might get a StopIteration Error. It is advisable to use python3.6 version for this. Code: python3 import gensim.downloader as apifrom gensim.matutils import softcossimfrom gensim import corpora s1 = ' Afghanistan is an Asian country and capital is Kabul'.split()s2 = 'India is an Asian country and capital is Delhi'.split()s3 = 'Greece is an European country and capital is Athens'.split() # load pre-trained modelword2vec_model = api.load('word2vec-google-news-300') # Prepare the similarity matrixsimilarity_matrix = word2vec_model.similarity_matrix(dictionary, tfidf = None, threshold = 0.0, exponent = 2.0, nonzero_limit = 100) # Prepare a dictionary and a corpus.docs = [s1, s2, s3]dictionary = corpora.Dictionary(docs) # Convert the sentences into bag-of-words vectors.s1 = dictionary.doc2bow(s1)s2 = dictionary.doc2bow(s2)s3 = dictionary.doc2bow(s3) # Compute soft cosine similarityprint(softcossim(s1, s2, similarity_matrix)) # similarity between s1 &s2 print(softcossim(s1, s3, similarity_matrix)) # similarity between s1 &s3 print(softcossim(s2, s3, similarity_matrix)) # similarity between s2 &s3 Some of the similarity and distance metrics which can be calculated for this word embedding model are mentioned below: Code: python3 # Find Odd one outprint(word2vec_model.doesnt_match(['india', 'bhutan', 'china', 'mango'])) #> mango # cosine distance between two words.word2vec_model.distance('man', 'woman') # cosine distances from given word or vector to other words.word2vec_model.distances('king', ['queen', 'man', 'woman']) # Compute cosine similaritiesword2vec_model.cosine_similarities(word2vec_model['queen'], vectors_all =(word2vec_model['king'], word2vec_model['woman'], word2vec_model['man'], word2vec_model['king'] + word2vec_model['woman']))# king + woman is very similar to queen. # words closer to w1 than w2word2vec_model.words_closer_than(w1 ='queen', w2 ='kingdom') # top-N most similar words.word2vec_model.most_similar(positive ='king', negative = None, topn = 5, restrict_vocab = None, indexer = None) # top-N most similar words, using the multiplicative combination objective,word2vec_model.most_similar_cosmul(positive ='queen', negative = None, topn = 5) Step 9: Summarize Text Documents The summarize( ) function implements the text rank summarization.You do not have to generate a tokenized list by splitting the sentences as that is already handled by the gensim.summarization.textcleaner module. Code: python3 from gensim.summarization import summarize, keywordsimport os text = " ".join((l for l in open('sample_data.txt', encoding ='utf-8'))) # Summarize the paragraphprint(summarize(text, word_count = 25)) Output: OUTPUT – Summary You can get the keywords by: Code: python3 # Important keywords from the paragraphprint(keywords(text)) OUTPUT – Keywords Conclusion: These are some of the features of the Gensim library.This comes most handy while you are working on language processing.You can make use of these as per your need.For any queries feel free to leave a comment down below. gabaa406 sagar0719kumar clintra Natural-language-processing Machine Learning Machine Learning Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n16 Aug, 2021" }, { "code": null, "e": 720, "s": 28, "text": "This tutorial is going to provide you with a walk-through of the Gensim library.Gensim : It is an open source library in python written by Radim Rehurek which is used in unsupervised topic modelling and natural language processing. It is designed to extract semantic topics from documents. It can handle large text collections. Hence it makes it different from other machine learning software packages which target memory processing. Gensim also provides efficient multicore implementations for various algorithms to increase processing speed. It provides more convenient facilities for text processing than other packages like Scikit-learn, R etc.This tutorial will cover these concepts: " }, { "code": null, "e": 999, "s": 720, "text": "Create a Corpus from a given DatasetCreate a TFIDF matrix in GensimCreate Bigrams and Trigrams with GensimCreate Word2Vec model using GensimCreate Doc2Vec model using GensimCreate Topic Model with LDACreate Topic Model with LSICompute Similarity MatricesSummarize text documents" }, { "code": null, "e": 1036, "s": 999, "text": "Create a Corpus from a given Dataset" }, { "code": null, "e": 1068, "s": 1036, "text": "Create a TFIDF matrix in Gensim" }, { "code": null, "e": 1108, "s": 1068, "text": "Create Bigrams and Trigrams with Gensim" }, { "code": null, "e": 1143, "s": 1108, "text": "Create Word2Vec model using Gensim" }, { "code": null, "e": 1177, "s": 1143, "text": "Create Doc2Vec model using Gensim" }, { "code": null, "e": 1205, "s": 1177, "text": "Create Topic Model with LDA" }, { "code": null, "e": 1233, "s": 1205, "text": "Create Topic Model with LSI" }, { "code": null, "e": 1261, "s": 1233, "text": "Compute Similarity Matrices" }, { "code": null, "e": 1286, "s": 1261, "text": "Summarize text documents" }, { "code": null, "e": 1372, "s": 1286, "text": "Let us understand what some of the below mentioned terms mean before moving forward. " }, { "code": null, "e": 1412, "s": 1372, "text": "Corpus: A collection of text documents." }, { "code": null, "e": 1447, "s": 1412, "text": "Vector: Form of representing text." }, { "code": null, "e": 1505, "s": 1447, "text": "Model: Algorithm used to generate representation of data." }, { "code": null, "e": 1612, "s": 1505, "text": "Topic Modelling: It is an information mining tool which is used to extract semantic topics from documents." }, { "code": null, "e": 1677, "s": 1612, "text": "Topic: A repeating group of words frequently occurring together." }, { "code": null, "e": 1880, "s": 1679, "text": "For example:\n You have a document which consists of words like - \n bat, car, racquet, score, glass, drive, cup, keys, water, game, steering, liquid\nThese can be grouped into different topics as-" }, { "code": null, "e": 1927, "s": 1880, "text": "Some of the Topic Modelling Techniques are – " }, { "code": null, "e": 1957, "s": 1927, "text": "Latent Semantic Indexing(LSI)" }, { "code": null, "e": 1990, "s": 1957, "text": "Latent Dirichlet Allocation(LDA)" }, { "code": null, "e": 2134, "s": 1990, "text": "Now that we have the basic idea of the terminologies let’s start with the use of Gensim package.First Install the library using the commands- " }, { "code": null, "e": 2168, "s": 2134, "text": "#for linux\n\n\n#for anaconda prompt" }, { "code": null, "e": 2269, "s": 2168, "text": "Step 1: Create a Corpus from a given Dataset You need to follow these steps to create your corpus: " }, { "code": null, "e": 2354, "s": 2269, "text": "Load your DatasetPreprocess the DatasetCreate a DictionaryCreate Bag of Words Corpus" }, { "code": null, "e": 2372, "s": 2354, "text": "Load your Dataset" }, { "code": null, "e": 2395, "s": 2372, "text": "Preprocess the Dataset" }, { "code": null, "e": 2415, "s": 2395, "text": "Create a Dictionary" }, { "code": null, "e": 2442, "s": 2415, "text": "Create Bag of Words Corpus" }, { "code": null, "e": 2576, "s": 2442, "text": "1.1 Load your Dataset: You can have a .txt file as your dataset or you can also load datasets using the Gensim Downloader API. Code: " }, { "code": null, "e": 2584, "s": 2576, "text": "python3" }, { "code": "import os # open the text file as an objectdoc = open('sample_data.txt', encoding ='utf-8')", "e": 2676, "s": 2584, "text": null }, { "code": null, "e": 2830, "s": 2676, "text": "Gensim Downloader API: This is a module available in the Gensim library which is an API for downloading, getting information and loading datasets/models." }, { "code": null, "e": 2837, "s": 2830, "text": "Code: " }, { "code": null, "e": 2845, "s": 2837, "text": "python3" }, { "code": "import gensim.downloader as api # check available models and datasetsinfo_datasets = api.info()print(info_datasets)#>{'corpora':#> {'semeval-2016-2017-task3-subtaskBC':#> {'num_records': -1, 'record_format': 'dict', 'file_size': 6344358, ....} # information of a particular datasetdataset_info = api.info(\"text8\") # load the \"text8\" datasetdataset = api.load(\"text8\") # load a pre-trained modelword2vec_model = api.load('word2vec-google-news-300')", "e": 3303, "s": 2845, "text": null }, { "code": null, "e": 3707, "s": 3303, "text": "Here we are going to consider a text file as raw dataset which consist of data from a wikipedia page. 1.2 Preprocess the Dataset Text preprocessing: In natural language preprocessing, text preprocessing is the practice of cleaning and preparing text data. For this purpose we will use the simple_preprocess( ) function.This function returns a list of tokens after tokenizing and normalizing them. Code: " }, { "code": null, "e": 3715, "s": 3707, "text": "python3" }, { "code": "import gensimimport osfrom gensim.utils import simple_preprocess # open the text file as an objectdoc = open('sample_data.txt', encoding ='utf-8') # preprocess the file to get a list of tokenstokenized =[]for sentence in doc.read().split('.'): # the simple_preprocess function returns a list of each sentence tokenized.append(simple_preprocess(sentence, deacc = True)) print(tokenized)", "e": 4103, "s": 3715, "text": null }, { "code": null, "e": 4113, "s": 4103, "text": "Output: " }, { "code": null, "e": 4131, "s": 4113, "text": "Output: tokenized" }, { "code": null, "e": 4325, "s": 4131, "text": "1.3 Create a Dictionary Now we have our preprocessed data which can be converted into a dictionary by using the corpora.Dictionary( ) function. This dictionary is a map for unique tokens.Code: " }, { "code": null, "e": 4333, "s": 4325, "text": "python3" }, { "code": "from gensim import corpora# storing the extracted tokens into the dictionarymy_dictionary = corpora.Dictionary(tokenized)print(my_dictionary)", "e": 4475, "s": 4333, "text": null }, { "code": null, "e": 4485, "s": 4475, "text": "Output: " }, { "code": null, "e": 4499, "s": 4485, "text": "my_dictionary" }, { "code": null, "e": 4644, "s": 4499, "text": "1.3.1 Saving Dictionary on Disk or as Text File You can save/load your dictionary on the disk as well as a text file as mentioned below: Code: " }, { "code": null, "e": 4652, "s": 4644, "text": "python3" }, { "code": "# save your dictionary to diskmy_dictionary.save('my_dictionary.dict') # load backload_dict = corpora.Dictionary.load(my_dictionary.dict') # save your dictionary as text filefrom gensim.test.utils import get_tmpfiletmp_fname = get_tmpfile(\"dictionary\")my_dictionary.save_as_text(tmp_fname) # load your dictionary text fileload_dict = corpora.Dictionary.load_from_text(tmp_fname)", "e": 5065, "s": 4652, "text": null }, { "code": null, "e": 5358, "s": 5065, "text": "1.4 Create Bag of Words Corpus Once we have the dictionary we can create a Bag of Word corpus using the doc2bow( ) function. This function counts the number of occurrences of each distinct word, convert the word to its integer word id and then the result is returned as a sparse vector.Code: " }, { "code": null, "e": 5366, "s": 5358, "text": "python3" }, { "code": "# converting to a bag of word corpusBoW_corpus =[my_dictionary.doc2bow(doc, allow_update = True) for doc in tokenized]print(BoW_corpus)", "e": 5502, "s": 5366, "text": null }, { "code": null, "e": 5512, "s": 5502, "text": "Output: " }, { "code": null, "e": 5523, "s": 5512, "text": "BoW_corpus" }, { "code": null, "e": 5585, "s": 5523, "text": "1.4.1 Saving Corpus on Disk: Code: To save/load your corpus " }, { "code": null, "e": 5593, "s": 5585, "text": "python3" }, { "code": "from gensim.corpora import MmCorpusfrom gensim.test.utils import get_tmpfile output_fname = get_tmpfile(\"BoW_corpus.mm\") # save corpus to diskMmCorpus.serialize(output_fname, BoW_corpus) # load corpusload_corpus = MmCorpus(output_fname)", "e": 5830, "s": 5593, "text": null }, { "code": null, "e": 6524, "s": 5830, "text": "Step 2: Create a TFIDF matrix in Gensim TFIDF: Stands for Term Frequency – Inverse Document Frequency. It is a commonly used natural language processing model that helps you determine the most important words in each document in a corpus. This was designed for a modest-size corpora.Some words might not be stopwords but may occur more often in the documents and may be of less importance. Hence these words need to be removed or down-weighted in importance. The TFIDF model takes the text that share a common language and ensures that most common words across the entire corpus don’t show as keywords. You can build a TFIDF model using Gensim and the corpus you developed previously as:Code: " }, { "code": null, "e": 6532, "s": 6524, "text": "python3" }, { "code": "from gensim import modelsimport numpy as np # Word weight in Bag of Words corpusword_weight =[]for doc in BoW_corpus: for id, freq in doc: word_weight.append([my_dictionary[id], freq])print(word_weight)", "e": 6739, "s": 6532, "text": null }, { "code": null, "e": 6749, "s": 6739, "text": "Output: " }, { "code": null, "e": 6789, "s": 6749, "text": "Word weight before applying TFIDF Model" }, { "code": null, "e": 6818, "s": 6789, "text": "Code: applying TFIDF model " }, { "code": null, "e": 6826, "s": 6818, "text": "python3" }, { "code": "# create TF-IDF modeltfIdf = models.TfidfModel(BoW_corpus, smartirs ='ntc') # TF-IDF Word Weightweight_tfidf =[]for doc in tfIdf[BoW_corpus]: for id, freq in doc: weight_tfidf.append([my_dictionary[id], np.around(freq, decimals = 3)])print(weight_tfidf) ", "e": 7085, "s": 6826, "text": null }, { "code": null, "e": 7095, "s": 7085, "text": "Output: " }, { "code": null, "e": 7135, "s": 7095, "text": "word weights after applying TFIDF model" }, { "code": null, "e": 7414, "s": 7135, "text": "You can see that the words occurring frequently across the documents now have lower weights assigned.Step 3: Creating Bigrams and Trigrams with Genism Many words tend to occur in the content together. The words when occur together have a different meaning than as individuals. " }, { "code": null, "e": 7570, "s": 7414, "text": "for example:\n Beatboxing --> the word beat and boxing individually have meanings of their own \n but these together have a different meaning. " }, { "code": null, "e": 7761, "s": 7570, "text": "Bigrams: Group of two words Trigrams: Group of three wordsWe will be using the text8 dataset here which can be downloaded using the Gensim downloader API Code: Building bigrams and trigrams " }, { "code": null, "e": 7769, "s": 7761, "text": "python3" }, { "code": "import gensim.downloader as apifrom gensim.models.phrases import Phrases # load the text8 datasetdataset = api.load(\"text8\") # extract a list of words from the datasetdata =[]for word in dataset: data.append(word) # Bigram using Phraser Model bigram_model = Phrases(data, min_count = 3, threshold = 10) print(bigram_model[data[0]]) ", "e": 8129, "s": 7769, "text": null }, { "code": null, "e": 8142, "s": 8129, "text": "Bigram model" }, { "code": null, "e": 8238, "s": 8142, "text": "To create a Trigram we simply pass the above obtained bigram model to the same function. Code: " }, { "code": null, "e": 8246, "s": 8238, "text": "python3" }, { "code": "# Trigram using Phraser Modeltrigram_model = Phrases(bigram_model[data], threshold = 10) # trigramprint(trigram_model[bigram_model[data[0]]])", "e": 8388, "s": 8246, "text": null }, { "code": null, "e": 8397, "s": 8388, "text": "Output: " }, { "code": null, "e": 8406, "s": 8397, "text": "Trigram " }, { "code": null, "e": 8414, "s": 8406, "text": "python3" }, { "code": "import gensim.downloader as apifrom multiprocessing import cpu_countfrom gensim.models.word2vec import Word2Vec # load the text8 datasetdataset = api.load(\"text8\") # extract a list of words from the datasetdata =[]for word in dataset: data.append(word) # We will split the data into two partsdata_1 = data[:1200] # this is used to train the modeldata_2 = data[1200:] # this part will be used to update the model # Training the Word2Vec modelw2v_model = Word2Vec(data_1, min_count = 0, workers = cpu_count()) # word vector for the word \"time\"print(w2v_model['time'])", "e": 8985, "s": 8414, "text": null }, { "code": null, "e": 8995, "s": 8985, "text": "Output: " }, { "code": null, "e": 9025, "s": 8995, "text": "word vector for the word time" }, { "code": null, "e": 9117, "s": 9025, "text": "You can also use the most_similar( ) function to find similar words to a given word.Code: " }, { "code": null, "e": 9125, "s": 9117, "text": "python3" }, { "code": "# similar words to the word \"time\"print(w2v_model.most_similar('time')) # save your modelw2v_model.save('Word2VecModel') # load your modelmodel = Word2Vec.load('Word2VecModel')", "e": 9302, "s": 9125, "text": null }, { "code": null, "e": 9312, "s": 9302, "text": "Output: " }, { "code": null, "e": 9341, "s": 9312, "text": "most similar words to ‘time’" }, { "code": null, "e": 9370, "s": 9341, "text": "4.2) Update the modelCode: " }, { "code": null, "e": 9378, "s": 9370, "text": "python3" }, { "code": "# build model vocabulary from a sequence of sentencesw2v_model.build_vocab(data_2, update = True) # train word vectorsw2v_model.train(data_2, total_examples = w2v_model.corpus_count, epochs = w2v_model.iter) print(w2v_model['time'])", "e": 9611, "s": 9378, "text": null }, { "code": null, "e": 9621, "s": 9611, "text": "Output: " }, { "code": null, "e": 9885, "s": 9621, "text": "Step 5: Create Doc2Vec model using Gensim In contrast to the Word2Vec model, the Doc2Vec model gives the vector representation for an entire document or group of words. With the help of this model, we can find the relationship among different documents such as- " }, { "code": null, "e": 9977, "s": 9885, "text": "If we train the model for literature such as \"Through the Looking Glass\".We can say that- " }, { "code": null, "e": 10004, "s": 9977, "text": "5.1) Train the modelCode: " }, { "code": null, "e": 10012, "s": 10004, "text": "python3" }, { "code": "import gensimimport gensim.downloader as apifrom gensim.models import doc2vec # get datasetdataset = api.load(\"text8\")data =[]for w in dataset: data.append(w) # To train the model we need a list of tagged documentsdef tagged_document(list_of_ListOfWords): for x, ListOfWords in enumerate(list_of_ListOfWords): yield doc2vec.TaggedDocument(ListOfWords, [x]) # training datadata_train = list(tagged_document(data)) # print trained datasetprint(data_train[:1])", "e": 10479, "s": 10012, "text": null }, { "code": null, "e": 10489, "s": 10479, "text": "Output: " }, { "code": null, "e": 10514, "s": 10489, "text": "OUTPUT – trained dataset" }, { "code": null, "e": 10542, "s": 10514, "text": "5.2) Update the modelCode: " }, { "code": null, "e": 10550, "s": 10542, "text": "python3" }, { "code": "# Initialize the modeld2v_model = doc2vec.Doc2Vec(vector_size = 40, min_count = 2, epochs = 30) # build the vocabularyd2v_model.build_vocab(data_train) # Train Doc2Vec modeld2v_model.train(data_train, total_examples = d2v_model.corpus_count, epochs = d2v_model.epochs) # Analyzing the outputAnalyze = d2v_model.infer_vector(['violent', 'means', 'to', 'destroy'])print(Analyze)", "e": 10927, "s": 10550, "text": null }, { "code": null, "e": 10937, "s": 10927, "text": "Output: " }, { "code": null, "e": 10961, "s": 10937, "text": "Output of updated model" }, { "code": null, "e": 11254, "s": 10961, "text": "Step 6: Create Topic model with LDA LDA is a popular method for topic modelling which considers each document as a collection of topics in a certain proportion. We need to take out the good quality of topics such as how segregated and meaningful they are. The good quality topics depend on- " }, { "code": null, "e": 11355, "s": 11254, "text": "the quality of text processingfinding the optimal number of topicsTuning parameters of the algorithm" }, { "code": null, "e": 11386, "s": 11355, "text": "the quality of text processing" }, { "code": null, "e": 11423, "s": 11386, "text": "finding the optimal number of topics" }, { "code": null, "e": 11458, "s": 11423, "text": "Tuning parameters of the algorithm" }, { "code": null, "e": 11600, "s": 11458, "text": "NOTE: If you run this code on python3.7 version you might get a StopIteration Error.\n It is advisable to use python3.6 version for this." }, { "code": null, "e": 11832, "s": 11600, "text": "Follow the below steps to create the model: 6.1 Prepare the Data This is done by removing the stopwords and then lemmatizing it. In order to lemmatize using Gensim, we need to first download the pattern package and the stopwords. " }, { "code": null, "e": 11947, "s": 11832, "text": "#download pattern package\npip install pattern\n\n#run in python console\n>> import nltk\n>> nltk.download('stopwords')" }, { "code": null, "e": 11954, "s": 11947, "text": "Code: " }, { "code": null, "e": 11962, "s": 11954, "text": "python3" }, { "code": "import gensimfrom gensim import corporafrom gensim.models import LdaModel, LdaMulticoreimport gensim.downloader as apifrom gensim.utils import simple_preprocess, lemmatize# from pattern.en import lemmaimport nltk# nltk.download('stopwords')from nltk.corpus import stopwordsimport reimport logging logging.basicConfig(format ='%(asctime)s : %(levelname)s : %(message)s')logging.root.setLevel(level = logging.INFO) # import stopwordsstop_words = stopwords.words('english')# add stopwordsstop_words = stop_words + ['subject', 'com', 'are', 'edu', 'would', 'could'] # import the datasetdataset = api.load(\"text8\")data = [w for w in dataset] # Preparing the dataprocessed_data = [] for x, doc in enumerate(data[:100]): doc_out = [] for word in doc: if word not in stop_words: # to remove stopwords Lemmatized_Word = lemmatize(word, allowed_tags = re.compile('(NN|JJ|RB)')) # lemmatize if Lemmatized_Word: doc_out.append(Lemmatized_Word[0].split(b'/')[0].decode('utf-8')) else: continue processed_data.append(doc_out) # processed_data is a list of list of words # Print sample print(processed_data[0][:10])", "e": 13138, "s": 11962, "text": null }, { "code": null, "e": 13148, "s": 13138, "text": "Output: " }, { "code": null, "e": 13172, "s": 13148, "text": "OUTPUT – processed_data" }, { "code": null, "e": 13286, "s": 13172, "text": "6.2 Create Dictionary and Corpus The processed data will now be used to create the dictionary and corpus. Code: " }, { "code": null, "e": 13294, "s": 13286, "text": "python3" }, { "code": "# create dictionary and corpusdict = corpora.Dictionary(processed_data)Corpus = [dict.doc2bow(l) for l in processed_data]", "e": 13416, "s": 13294, "text": null }, { "code": null, "e": 13664, "s": 13416, "text": "6.3 Train LDA model We will be training the LDA model with 5 topics using the dictionary and corpus created previously.Here the LdaModel( ) function is used but you can also use the LdaMulticore( ) function as it allows parallel processing. Code: " }, { "code": null, "e": 13672, "s": 13664, "text": "python3" }, { "code": "# TrainingLDA_model = LdaModel(corpus = LDA_corpus, num_topics = 5)# save modelLDA_model.save('LDA_model.model') # show topicsprint(LDA_model.print_topics(-1))", "e": 13832, "s": 13672, "text": null }, { "code": null, "e": 13842, "s": 13832, "text": "Output: " }, { "code": null, "e": 13858, "s": 13842, "text": "OUTPUT – topics" }, { "code": null, "e": 14060, "s": 13858, "text": "The words which can be seen in more than one topic and are of less relevance can be added to the stopwords list.6.4 Interpret the Output The LDA model majorly gives us information regarding 3 things: " }, { "code": null, "e": 14123, "s": 14060, "text": "Topics in the documentWhat topic each word belongs toPhi value" }, { "code": null, "e": 14146, "s": 14123, "text": "Topics in the document" }, { "code": null, "e": 14178, "s": 14146, "text": "What topic each word belongs to" }, { "code": null, "e": 14188, "s": 14178, "text": "Phi value" }, { "code": null, "e": 14367, "s": 14188, "text": "Phi value: It is the probability of a word to lie in a particular topic.For a given word, sum of the phi values give the number of times that word occured in the document.Code: " }, { "code": null, "e": 14375, "s": 14367, "text": "python3" }, { "code": "# probability of a word belonging to a topicLDA_model.get_term_topics('fire') bow_list =['time', 'space', 'car']# convert to bag of words format firstbow = LDA_model.id2word.doc2bow(bow_list) # interpreting the datadoc_topics, word_topics, phi_values = LDA_model.get_document_topics(bow, per_word_topics = True)", "e": 14687, "s": 14375, "text": null }, { "code": null, "e": 14929, "s": 14687, "text": "Step 7: Create Topic Model with LSI To create the model with LSI just follow the steps same as with LDA. The only difference will be while training the model.Use the LsiModel( ) function instead of the LdaMulticore( ) or LdaModel( ). Code: " }, { "code": null, "e": 14937, "s": 14929, "text": "python3" }, { "code": "# Training the model with LSILSI_model = LsiModel(corpus = Corpus, id2word = dct, num_topics = 7, decay = 0.5) # Topicsprint(LSI_model.print_topics(-1))", "e": 15090, "s": 14937, "text": null }, { "code": null, "e": 15647, "s": 15090, "text": "Step 8: Compute Similarity Matrices Cosine Similarity: It is a measure of similarity between two non-zero vectors of an inner product space. It is defined to equal the cosine of the angle between them.Soft Cosine Similarity: It is similar to cosine similarity but the difference is that cosine similarity considers the vector space model(VSM) features as independent whereas soft cosine proposes to consider the similarity of features in VSM.We need to take a word embedding model to compute soft cosines.Here we are using the pre-trained word2vec model. " }, { "code": null, "e": 15789, "s": 15647, "text": "Note: If you run this code on python3.7 version you might get a StopIteration Error.\n It is advisable to use python3.6 version for this." }, { "code": null, "e": 15797, "s": 15789, "text": "Code: " }, { "code": null, "e": 15805, "s": 15797, "text": "python3" }, { "code": "import gensim.downloader as apifrom gensim.matutils import softcossimfrom gensim import corpora s1 = ' Afghanistan is an Asian country and capital is Kabul'.split()s2 = 'India is an Asian country and capital is Delhi'.split()s3 = 'Greece is an European country and capital is Athens'.split() # load pre-trained modelword2vec_model = api.load('word2vec-google-news-300') # Prepare the similarity matrixsimilarity_matrix = word2vec_model.similarity_matrix(dictionary, tfidf = None, threshold = 0.0, exponent = 2.0, nonzero_limit = 100) # Prepare a dictionary and a corpus.docs = [s1, s2, s3]dictionary = corpora.Dictionary(docs) # Convert the sentences into bag-of-words vectors.s1 = dictionary.doc2bow(s1)s2 = dictionary.doc2bow(s2)s3 = dictionary.doc2bow(s3) # Compute soft cosine similarityprint(softcossim(s1, s2, similarity_matrix)) # similarity between s1 &s2 print(softcossim(s1, s3, similarity_matrix)) # similarity between s1 &s3 print(softcossim(s2, s3, similarity_matrix)) # similarity between s2 &s3", "e": 16815, "s": 15805, "text": null }, { "code": null, "e": 16942, "s": 16815, "text": "Some of the similarity and distance metrics which can be calculated for this word embedding model are mentioned below: Code: " }, { "code": null, "e": 16950, "s": 16942, "text": "python3" }, { "code": "# Find Odd one outprint(word2vec_model.doesnt_match(['india', 'bhutan', 'china', 'mango'])) #> mango # cosine distance between two words.word2vec_model.distance('man', 'woman') # cosine distances from given word or vector to other words.word2vec_model.distances('king', ['queen', 'man', 'woman']) # Compute cosine similaritiesword2vec_model.cosine_similarities(word2vec_model['queen'], vectors_all =(word2vec_model['king'], word2vec_model['woman'], word2vec_model['man'], word2vec_model['king'] + word2vec_model['woman']))# king + woman is very similar to queen. # words closer to w1 than w2word2vec_model.words_closer_than(w1 ='queen', w2 ='kingdom') # top-N most similar words.word2vec_model.most_similar(positive ='king', negative = None, topn = 5, restrict_vocab = None, indexer = None) # top-N most similar words, using the multiplicative combination objective,word2vec_model.most_similar_cosmul(positive ='queen', negative = None, topn = 5)", "e": 18105, "s": 16950, "text": null }, { "code": null, "e": 18358, "s": 18105, "text": "Step 9: Summarize Text Documents The summarize( ) function implements the text rank summarization.You do not have to generate a tokenized list by splitting the sentences as that is already handled by the gensim.summarization.textcleaner module. Code: " }, { "code": null, "e": 18366, "s": 18358, "text": "python3" }, { "code": "from gensim.summarization import summarize, keywordsimport os text = \" \".join((l for l in open('sample_data.txt', encoding ='utf-8'))) # Summarize the paragraphprint(summarize(text, word_count = 25))", "e": 18566, "s": 18366, "text": null }, { "code": null, "e": 18576, "s": 18566, "text": "Output: " }, { "code": null, "e": 18593, "s": 18576, "text": "OUTPUT – Summary" }, { "code": null, "e": 18629, "s": 18593, "text": "You can get the keywords by: Code: " }, { "code": null, "e": 18637, "s": 18629, "text": "python3" }, { "code": "# Important keywords from the paragraphprint(keywords(text))", "e": 18698, "s": 18637, "text": null }, { "code": null, "e": 18716, "s": 18698, "text": "OUTPUT – Keywords" }, { "code": null, "e": 18949, "s": 18716, "text": "Conclusion: These are some of the features of the Gensim library.This comes most handy while you are working on language processing.You can make use of these as per your need.For any queries feel free to leave a comment down below. " }, { "code": null, "e": 18958, "s": 18949, "text": "gabaa406" }, { "code": null, "e": 18973, "s": 18958, "text": "sagar0719kumar" }, { "code": null, "e": 18981, "s": 18973, "text": "clintra" }, { "code": null, "e": 19009, "s": 18981, "text": "Natural-language-processing" }, { "code": null, "e": 19026, "s": 19009, "text": "Machine Learning" }, { "code": null, "e": 19043, "s": 19026, "text": "Machine Learning" } ]
Comparison of static keyword in C++ and Java
22 Nov, 2021 Static keyword is used for almost the same purpose in both C++ and Java. There are some differences though. This post covers similarities and differences of static keyword in C++ and Java. Similarities between C++ and Java for Static Keyword: Static data members can be defined in both languages. Static member functions can be defined in both languages. Easy access of static members is possible, without creating some objects. Differences between C++ and Java for Static Keyword: C++ Java The above points are discussed are in detail below: 1. Static Data Members: Like C++, static data members in Java are class members and shared among all objects. For example, in the following Java program, the static variable count is used to count the number of objects created. Java class Test { static int count = 0; Test() { count++; } public static void main(String arr[]) { Test t1 = new Test(); Test t2 = new Test(); System.out.println("Total " + count + " objects created"); }} Total 2 objects created 2. Static Member Methods: In C++ and Java, static member functions can be defined. Methods declared as static are class members and have the following restrictions: A) They can only call other static methods. For example, the following program fails in the compilation. fun() is non-static and it is called in static main(). Java class Main { public static void main(String args[]) { System.out.println(fun()); } int fun() { return 20; }} B) They must only access static data. C) They cannot access this or super. For example, the following program fails in the compilation. Java class Base { static int x = 0;} class Derived extends Base { public static void fun() { // Compiler Error: non-static variable // cannot be referenced from a static context System.out.println(super.x); }} D) Like C++, static data members and static methods can be accessed without creating an object. They can be accessed using the class names. For example, in the following program, static data member count and static method fun() are accessed without any object. Java class Test { static int count = 0; public static void fun() { System.out.println("Static fun() called"); }} class Main { public static void main(String arr[]) { System.out.println("Test.count = " + Test.count); Test.fun(); }} Test.count = 0 Static fun() called 3. Static Block: Unlike C++, Java supports a special block, called static block (also called static clause) which can be used for static initialization of a class. This code inside the static block is executed only once. See Static blocks in Java for details. 4. Static Local Variables: Unlike Java, C++ supports static local variables. For example, the following Java program fails in the compilation. Java class Test { public static void main(String args[]) { System.out.println(fun()); } static int fun() { // Compiler Error: Static local // variables are not allowed static int x = 10; return x--; }} Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. anshikajain26 C++-Static Keyword Static Keyword C++ Java Java CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n22 Nov, 2021" }, { "code": null, "e": 244, "s": 54, "text": "Static keyword is used for almost the same purpose in both C++ and Java. There are some differences though. This post covers similarities and differences of static keyword in C++ and Java. " }, { "code": null, "e": 298, "s": 244, "text": "Similarities between C++ and Java for Static Keyword:" }, { "code": null, "e": 352, "s": 298, "text": "Static data members can be defined in both languages." }, { "code": null, "e": 410, "s": 352, "text": "Static member functions can be defined in both languages." }, { "code": null, "e": 484, "s": 410, "text": "Easy access of static members is possible, without creating some objects." }, { "code": null, "e": 537, "s": 484, "text": "Differences between C++ and Java for Static Keyword:" }, { "code": null, "e": 541, "s": 537, "text": "C++" }, { "code": null, "e": 546, "s": 541, "text": "Java" }, { "code": null, "e": 598, "s": 546, "text": "The above points are discussed are in detail below:" }, { "code": null, "e": 826, "s": 598, "text": "1. Static Data Members: Like C++, static data members in Java are class members and shared among all objects. For example, in the following Java program, the static variable count is used to count the number of objects created." }, { "code": null, "e": 831, "s": 826, "text": "Java" }, { "code": "class Test { static int count = 0; Test() { count++; } public static void main(String arr[]) { Test t1 = new Test(); Test t2 = new Test(); System.out.println(\"Total \" + count + \" objects created\"); }}", "e": 1095, "s": 831, "text": null }, { "code": null, "e": 1119, "s": 1095, "text": "Total 2 objects created" }, { "code": null, "e": 1284, "s": 1119, "text": "2. Static Member Methods: In C++ and Java, static member functions can be defined. Methods declared as static are class members and have the following restrictions:" }, { "code": null, "e": 1444, "s": 1284, "text": "A) They can only call other static methods. For example, the following program fails in the compilation. fun() is non-static and it is called in static main()." }, { "code": null, "e": 1449, "s": 1444, "text": "Java" }, { "code": "class Main { public static void main(String args[]) { System.out.println(fun()); } int fun() { return 20; }}", "e": 1577, "s": 1449, "text": null }, { "code": null, "e": 1615, "s": 1577, "text": "B) They must only access static data." }, { "code": null, "e": 1713, "s": 1615, "text": "C) They cannot access this or super. For example, the following program fails in the compilation." }, { "code": null, "e": 1718, "s": 1713, "text": "Java" }, { "code": "class Base { static int x = 0;} class Derived extends Base { public static void fun() { // Compiler Error: non-static variable // cannot be referenced from a static context System.out.println(super.x); }}", "e": 1957, "s": 1718, "text": null }, { "code": null, "e": 2219, "s": 1957, "text": "D) Like C++, static data members and static methods can be accessed without creating an object. They can be accessed using the class names. For example, in the following program, static data member count and static method fun() are accessed without any object. " }, { "code": null, "e": 2224, "s": 2219, "text": "Java" }, { "code": "class Test { static int count = 0; public static void fun() { System.out.println(\"Static fun() called\"); }} class Main { public static void main(String arr[]) { System.out.println(\"Test.count = \" + Test.count); Test.fun(); }}", "e": 2492, "s": 2224, "text": null }, { "code": null, "e": 2527, "s": 2492, "text": "Test.count = 0\nStatic fun() called" }, { "code": null, "e": 2787, "s": 2527, "text": "3. Static Block: Unlike C++, Java supports a special block, called static block (also called static clause) which can be used for static initialization of a class. This code inside the static block is executed only once. See Static blocks in Java for details." }, { "code": null, "e": 2931, "s": 2787, "text": "4. Static Local Variables: Unlike Java, C++ supports static local variables. For example, the following Java program fails in the compilation. " }, { "code": null, "e": 2936, "s": 2931, "text": "Java" }, { "code": "class Test { public static void main(String args[]) { System.out.println(fun()); } static int fun() { // Compiler Error: Static local // variables are not allowed static int x = 10; return x--; }}", "e": 3187, "s": 2936, "text": null }, { "code": null, "e": 3312, "s": 3187, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 3326, "s": 3312, "text": "anshikajain26" }, { "code": null, "e": 3345, "s": 3326, "text": "C++-Static Keyword" }, { "code": null, "e": 3360, "s": 3345, "text": "Static Keyword" }, { "code": null, "e": 3364, "s": 3360, "text": "C++" }, { "code": null, "e": 3369, "s": 3364, "text": "Java" }, { "code": null, "e": 3374, "s": 3369, "text": "Java" }, { "code": null, "e": 3378, "s": 3374, "text": "CPP" } ]
Break and Next statements in R
04 May, 2020 In R programming, we require a control structure to run a block of code multiple times. Loops come in the class of the most fundamental and strong programming concepts. A loop is a control statement that allows multiple executions of a statement or a set of statements. The word ‘looping’ means cycling or iterating. Jump statements are used in loops to terminate the loop at a particular iteration or to skip a particular iteration in the loop. The two most commonly used jump statements in loops are: Break Statement Next Statement Note: In R language continue statement is referred to as the next statement. The basic Function of Break and Next statement is to alter the running loop in the program and flow the control outside of the loop. In R language, repeat, for and while loops are used to run the statement or get the desired output N number of times until the given condition to the loop becomes false.Sometimes there will be such a condition where we need to terminate the loop to continue with the rest of the program. In such cases R Break statement is used.Sometimes there will be such condition where we don’t want loop to perform the program for specific condition inside the loop. In such cases, R next statement is used. The break keyword is a jump statement that is used to terminate the loop at a particular iteration.Syntax: if (test_expression) { break } Example 1: Using break in For-loop # R program for break statement in For-loop no <- 1:10 for (val in no){ if (val == 5) { print(paste("Coming out from for loop Where i = ", val)) break } print(paste("Values are: ", val))} Output: [1] "Values are: 1" [1] "Values are: 2" [1] "Values are: 3" [1] "Values are: 4" [1] "Coming out from for loop Where i = 5" Example 2: Using break statement in While-loop # R Break Statement Examplea<-1 while (a < 10){ print(a) if(a==5) break a = a + 1 } Output: [1] 1 [1] 2 [1] 3 [1] 4 [1] 5 The next statement is used to skip the current iteration in the loop and move to the next iteration without exiting from the loop itself.Syntax: if (test_condition) { next } Example 1: Using next statement in For-loop # R Next Statement Example no <- 1:10 for (val in no) { if (val == 6) { print(paste("Skipping for loop Where i = ", val)) next } print(paste("Values are: ", val))} Output: [1] "Values are: 1" [1] "Values are: 2" [1] "Values are: 3" [1] "Values are: 4" [1] "Values are: 5" [1] "Skipping for loop Where i = 6" [1] "Values are: 7" [1] "Values are: 8" [1] "Values are: 9" [1] "Values are: 10" Example 2: Using next statement in While-loop # R Next Statement Examplex <- 1while(x < 5) { x <- x + 1; if (x == 3) next; print(x);} Output: [1] 2 [1] 4 [1] 5 Picked R Language Write From Home Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 53, "s": 25, "text": "\n04 May, 2020" }, { "code": null, "e": 370, "s": 53, "text": "In R programming, we require a control structure to run a block of code multiple times. Loops come in the class of the most fundamental and strong programming concepts. A loop is a control statement that allows multiple executions of a statement or a set of statements. The word ‘looping’ means cycling or iterating." }, { "code": null, "e": 556, "s": 370, "text": "Jump statements are used in loops to terminate the loop at a particular iteration or to skip a particular iteration in the loop. The two most commonly used jump statements in loops are:" }, { "code": null, "e": 572, "s": 556, "text": "Break Statement" }, { "code": null, "e": 587, "s": 572, "text": "Next Statement" }, { "code": null, "e": 664, "s": 587, "text": "Note: In R language continue statement is referred to as the next statement." }, { "code": null, "e": 1293, "s": 664, "text": "The basic Function of Break and Next statement is to alter the running loop in the program and flow the control outside of the loop. In R language, repeat, for and while loops are used to run the statement or get the desired output N number of times until the given condition to the loop becomes false.Sometimes there will be such a condition where we need to terminate the loop to continue with the rest of the program. In such cases R Break statement is used.Sometimes there will be such condition where we don’t want loop to perform the program for specific condition inside the loop. In such cases, R next statement is used." }, { "code": null, "e": 1400, "s": 1293, "text": "The break keyword is a jump statement that is used to terminate the loop at a particular iteration.Syntax:" }, { "code": null, "e": 1431, "s": 1400, "text": "if (test_expression) {\nbreak\n}" }, { "code": null, "e": 1466, "s": 1431, "text": "Example 1: Using break in For-loop" }, { "code": "# R program for break statement in For-loop no <- 1:10 for (val in no){ if (val == 5) { print(paste(\"Coming out from for loop Where i = \", val)) break } print(paste(\"Values are: \", val))}", "e": 1683, "s": 1466, "text": null }, { "code": null, "e": 1691, "s": 1683, "text": "Output:" }, { "code": null, "e": 1820, "s": 1691, "text": "[1] \"Values are: 1\"\n[1] \"Values are: 2\"\n[1] \"Values are: 3\"\n[1] \"Values are: 4\"\n[1] \"Coming out from for loop Where i = 5\"\n" }, { "code": null, "e": 1867, "s": 1820, "text": "Example 2: Using break statement in While-loop" }, { "code": "# R Break Statement Examplea<-1 while (a < 10){ print(a) if(a==5) break a = a + 1 } ", "e": 1993, "s": 1867, "text": null }, { "code": null, "e": 2001, "s": 1993, "text": "Output:" }, { "code": null, "e": 2032, "s": 2001, "text": "[1] 1\n[1] 2\n[1] 3\n[1] 4\n[1] 5\n" }, { "code": null, "e": 2177, "s": 2032, "text": "The next statement is used to skip the current iteration in the loop and move to the next iteration without exiting from the loop itself.Syntax:" }, { "code": null, "e": 2211, "s": 2177, "text": "if (test_condition) \n{\n next\n}" }, { "code": null, "e": 2255, "s": 2211, "text": "Example 1: Using next statement in For-loop" }, { "code": "# R Next Statement Example no <- 1:10 for (val in no) { if (val == 6) { print(paste(\"Skipping for loop Where i = \", val)) next } print(paste(\"Values are: \", val))}", "e": 2452, "s": 2255, "text": null }, { "code": null, "e": 2460, "s": 2452, "text": "Output:" }, { "code": null, "e": 2698, "s": 2460, "text": "[1] \"Values are: 1\"\n[1] \"Values are: 2\"\n[1] \"Values are: 3\"\n[1] \"Values are: 4\"\n[1] \"Values are: 5\"\n[1] \"Skipping for loop Where i = 6\"\n[1] \"Values are: 7\"\n[1] \"Values are: 8\"\n[1] \"Values are: 9\"\n[1] \"Values are: 10\"\n" }, { "code": null, "e": 2744, "s": 2698, "text": "Example 2: Using next statement in While-loop" }, { "code": "# R Next Statement Examplex <- 1while(x < 5) { x <- x + 1; if (x == 3) next; print(x);} ", "e": 2852, "s": 2744, "text": null }, { "code": null, "e": 2860, "s": 2852, "text": "Output:" }, { "code": null, "e": 2879, "s": 2860, "text": "[1] 2\n[1] 4\n[1] 5\n" }, { "code": null, "e": 2886, "s": 2879, "text": "Picked" }, { "code": null, "e": 2897, "s": 2886, "text": "R Language" }, { "code": null, "e": 2913, "s": 2897, "text": "Write From Home" } ]
Program to find Nth odd Fibonacci Number
13 Mar, 2022 Given an integer N. The task is to find the Nth odd Fibonacci number.The odd number fibonacci series is as: 1, 1, 3, 5, 13, 21, 55, 89, 233, 377, 987, 1597.............and so on.Note: In the above series we have omitted even terms from the general fibonacci sequence. Examples: Input: N = 3 Output: 3 Input: N = 4 Output: 5 Approach: On observing carefully, it can be deduced that every third Fibonacci number is even, so the Nth odd Fibonacci number is the {(3*N+1)/2}th term in the general Fibonacci sequence.Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ program for Nth odd fibonacci number #include <bits/stdc++.h>using namespace std; // Function to find nth odd fibonacci numberint oddFib(int n){ n = (3 * n + 1) / 2; int a = -1, b = 1, c, i; for (i = 1; i <= n; i++) { c = a + b; a = b; b = c; } return c;} // Driver Codeint main(){ int n = 4; cout << oddFib(n); return 0;} // Java program for Nth odd fibonacci numberclass GFG{ // Function to find nth odd fibonacci number static int oddFib(int n) { n = (3 * n + 1) / 2; int a = -1, b = 1, c = 0, i; for (i = 1; i <= n; i++) { c = a + b; a = b; b = c; } return c; } // Driver Code public static void main (String[] args) { int n = 4; System.out.println(oddFib(n)); }} // This code is contributed by AnkitRai01 # Python3 program for Nth odd fibonacci number # Function to find nth odd fibonacci numberdef oddFib(n): n = (3 * n + 1) // 2 a = -1 b = 1 c = 0 for i in range(1, n + 1): c = a + b a = b b = c return c # Driver Coden = 4 print(oddFib(n)) # This code is contributed by mohit kumar // C# program for Nth odd fibonacci numberusing System; class GFG{ // Function to find nth odd fibonacci number static int oddFib(int n) { n = (3 * n + 1) / 2; int a = -1, b = 1, c = 0, i; for (i = 1; i <= n; i++) { c = a + b; a = b; b = c; } return c; } // Driver Code public static void Main (String[] args) { int n = 4; Console.WriteLine(oddFib(n)); }} // This code is contributed by 29AjayKumar <script> // JavaScript program for Nth odd fibonacci number // Function to find nth odd fibonacci numberfunction oddFib(n){ n = (3 * n + 1) / 2; var a = -1, b = 1, c, i; for (i = 1; i <= n; i++) { c = a + b; a = b; b = c; } return c;} // Driver Codevar n = 4;document.write(oddFib(n)); </script> 5 Time Complexity: O(N) Auxiliary Space: O(1) mohit kumar 29 ankthon 29AjayKumar rrrtnx sagar0719kumar sooda367 subham348 Fibonacci Numbers Mathematical Mathematical Fibonacci Numbers Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n13 Mar, 2022" }, { "code": null, "e": 164, "s": 54, "text": "Given an integer N. The task is to find the Nth odd Fibonacci number.The odd number fibonacci series is as: " }, { "code": null, "e": 326, "s": 164, "text": "1, 1, 3, 5, 13, 21, 55, 89, 233, 377, 987, 1597.............and so on.Note: In the above series we have omitted even terms from the general fibonacci sequence. " }, { "code": null, "e": 338, "s": 326, "text": "Examples: " }, { "code": null, "e": 385, "s": 338, "text": "Input: N = 3\nOutput: 3\n\nInput: N = 4\nOutput: 5" }, { "code": null, "e": 627, "s": 387, "text": "Approach: On observing carefully, it can be deduced that every third Fibonacci number is even, so the Nth odd Fibonacci number is the {(3*N+1)/2}th term in the general Fibonacci sequence.Below is the implementation of the above approach: " }, { "code": null, "e": 631, "s": 627, "text": "C++" }, { "code": null, "e": 636, "s": 631, "text": "Java" }, { "code": null, "e": 644, "s": 636, "text": "Python3" }, { "code": null, "e": 647, "s": 644, "text": "C#" }, { "code": null, "e": 658, "s": 647, "text": "Javascript" }, { "code": "// C++ program for Nth odd fibonacci number #include <bits/stdc++.h>using namespace std; // Function to find nth odd fibonacci numberint oddFib(int n){ n = (3 * n + 1) / 2; int a = -1, b = 1, c, i; for (i = 1; i <= n; i++) { c = a + b; a = b; b = c; } return c;} // Driver Codeint main(){ int n = 4; cout << oddFib(n); return 0;}", "e": 1043, "s": 658, "text": null }, { "code": "// Java program for Nth odd fibonacci numberclass GFG{ // Function to find nth odd fibonacci number static int oddFib(int n) { n = (3 * n + 1) / 2; int a = -1, b = 1, c = 0, i; for (i = 1; i <= n; i++) { c = a + b; a = b; b = c; } return c; } // Driver Code public static void main (String[] args) { int n = 4; System.out.println(oddFib(n)); }} // This code is contributed by AnkitRai01", "e": 1580, "s": 1043, "text": null }, { "code": "# Python3 program for Nth odd fibonacci number # Function to find nth odd fibonacci numberdef oddFib(n): n = (3 * n + 1) // 2 a = -1 b = 1 c = 0 for i in range(1, n + 1): c = a + b a = b b = c return c # Driver Coden = 4 print(oddFib(n)) # This code is contributed by mohit kumar", "e": 1901, "s": 1580, "text": null }, { "code": "// C# program for Nth odd fibonacci numberusing System; class GFG{ // Function to find nth odd fibonacci number static int oddFib(int n) { n = (3 * n + 1) / 2; int a = -1, b = 1, c = 0, i; for (i = 1; i <= n; i++) { c = a + b; a = b; b = c; } return c; } // Driver Code public static void Main (String[] args) { int n = 4; Console.WriteLine(oddFib(n)); }} // This code is contributed by 29AjayKumar", "e": 2454, "s": 1901, "text": null }, { "code": "<script> // JavaScript program for Nth odd fibonacci number // Function to find nth odd fibonacci numberfunction oddFib(n){ n = (3 * n + 1) / 2; var a = -1, b = 1, c, i; for (i = 1; i <= n; i++) { c = a + b; a = b; b = c; } return c;} // Driver Codevar n = 4;document.write(oddFib(n)); </script>", "e": 2786, "s": 2454, "text": null }, { "code": null, "e": 2788, "s": 2786, "text": "5" }, { "code": null, "e": 2812, "s": 2790, "text": "Time Complexity: O(N)" }, { "code": null, "e": 2835, "s": 2812, "text": "Auxiliary Space: O(1) " }, { "code": null, "e": 2850, "s": 2835, "text": "mohit kumar 29" }, { "code": null, "e": 2858, "s": 2850, "text": "ankthon" }, { "code": null, "e": 2870, "s": 2858, "text": "29AjayKumar" }, { "code": null, "e": 2877, "s": 2870, "text": "rrrtnx" }, { "code": null, "e": 2892, "s": 2877, "text": "sagar0719kumar" }, { "code": null, "e": 2901, "s": 2892, "text": "sooda367" }, { "code": null, "e": 2911, "s": 2901, "text": "subham348" }, { "code": null, "e": 2921, "s": 2911, "text": "Fibonacci" }, { "code": null, "e": 2929, "s": 2921, "text": "Numbers" }, { "code": null, "e": 2942, "s": 2929, "text": "Mathematical" }, { "code": null, "e": 2955, "s": 2942, "text": "Mathematical" }, { "code": null, "e": 2965, "s": 2955, "text": "Fibonacci" }, { "code": null, "e": 2973, "s": 2965, "text": "Numbers" } ]
Travelling Salesman Problem implementation using BackTracking
06 Jun, 2022 Travelling Salesman Problem (TSP): Given a set of cities and distance between every pair of cities, the problem is to find the shortest possible route that visits every city exactly once and returns back to the starting point.Note the difference between Hamiltonian Cycle and TSP. The Hamiltonian cycle problem is to find if there exist a tour that visits every city exactly once. Here we know that Hamiltonian Tour exists (because the graph is complete) and in fact many such tours exist, the problem is to find a minimum weight Hamiltonian Cycle. For example, consider the graph shown in the figure. A TSP tour in the graph is 1 -> 2 -> 4 -> 3 -> 1. The cost of the tour is 10 + 25 + 30 + 15 which is 80.The problem is a famous NP hard problem. There is no polynomial time know solution for this problem. Output of Given Graph: Minimum weight Hamiltonian Cycle : 10 + 25 + 30 + 15 = 80 Approach: In this post, implementation of simple solution is discussed. Consider city 1 (let say 0th node) as the starting and ending point. Since route is cyclic, we can consider any point as starting point. Start traversing from the source to its adjacent nodes in dfs manner. Calculate cost of every traversal and keep track of minimum cost and keep on updating the value of minimum cost stored value. Return the permutation with minimum cost. Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ implementation of the approach#include <bits/stdc++.h>using namespace std;#define V 4 // Function to find the minimum weight Hamiltonian Cyclevoid tsp(int graph[][V], vector<bool>& v, int currPos, int n, int count, int cost, int& ans){ // If last node is reached and it has a link // to the starting node i.e the source then // keep the minimum value out of the total cost // of traversal and "ans" // Finally return to check for more possible values if (count == n && graph[currPos][0]) { ans = min(ans, cost + graph[currPos][0]); return; } // BACKTRACKING STEP // Loop to traverse the adjacency list // of currPos node and increasing the count // by 1 and cost by graph[currPos][i] value for (int i = 0; i < n; i++) { if (!v[i] && graph[currPos][i]) { // Mark as visited v[i] = true; tsp(graph, v, i, n, count + 1, cost + graph[currPos][i], ans); // Mark ith node as unvisited v[i] = false; } }}; // Driver codeint main(){ // n is the number of nodes i.e. V int n = 4; int graph[][V] = { { 0, 10, 15, 20 }, { 10, 0, 35, 25 }, { 15, 35, 0, 30 }, { 20, 25, 30, 0 } }; // Boolean array to check if a node // has been visited or not vector<bool> v(n); for (int i = 0; i < n; i++) v[i] = false; // Mark 0th node as visited v[0] = true; int ans = INT_MAX; // Find the minimum weight Hamiltonian Cycle tsp(graph, v, 0, n, 1, 0, ans); // ans is the minimum weight Hamiltonian Cycle cout << ans; return 0;} // Java implementation of the approachclass GFG{ // Function to find the minimum weight // Hamiltonian Cycle static int tsp(int[][] graph, boolean[] v, int currPos, int n, int count, int cost, int ans) { // If last node is reached and it has a link // to the starting node i.e the source then // keep the minimum value out of the total cost // of traversal and "ans" // Finally return to check for more possible values if (count == n && graph[currPos][0] > 0) { ans = Math.min(ans, cost + graph[currPos][0]); return ans; } // BACKTRACKING STEP // Loop to traverse the adjacency list // of currPos node and increasing the count // by 1 and cost by graph[currPos,i] value for (int i = 0; i < n; i++) { if (v[i] == false && graph[currPos][i] > 0) { // Mark as visited v[i] = true; ans = tsp(graph, v, i, n, count + 1, cost + graph[currPos][i], ans); // Mark ith node as unvisited v[i] = false; } } return ans; } // Driver code public static void main(String[] args) { // n is the number of nodes i.e. V int n = 4; int[][] graph = {{0, 10, 15, 20}, {10, 0, 35, 25}, {15, 35, 0, 30}, {20, 25, 30, 0}}; // Boolean array to check if a node // has been visited or not boolean[] v = new boolean[n]; // Mark 0th node as visited v[0] = true; int ans = Integer.MAX_VALUE; // Find the minimum weight Hamiltonian Cycle ans = tsp(graph, v, 0, n, 1, 0, ans); // ans is the minimum weight Hamiltonian Cycle System.out.println(ans); }} // This code is contributed by Rajput-Ji # Python3 implementation of the approachV = 4answer = [] # Function to find the minimum weight# Hamiltonian Cycledef tsp(graph, v, currPos, n, count, cost): # If last node is reached and it has # a link to the starting node i.e # the source then keep the minimum # value out of the total cost of # traversal and "ans" # Finally return to check for # more possible values if (count == n and graph[currPos][0]): answer.append(cost + graph[currPos][0]) return # BACKTRACKING STEP # Loop to traverse the adjacency list # of currPos node and increasing the count # by 1 and cost by graph[currPos][i] value for i in range(n): if (v[i] == False and graph[currPos][i]): # Mark as visited v[i] = True tsp(graph, v, i, n, count + 1, cost + graph[currPos][i]) # Mark ith node as unvisited v[i] = False # Driver code # n is the number of nodes i.e. Vif __name__ == '__main__': n = 4 graph= [[ 0, 10, 15, 20 ], [ 10, 0, 35, 25 ], [ 15, 35, 0, 30 ], [ 20, 25, 30, 0 ]] # Boolean array to check if a node # has been visited or not v = [False for i in range(n)] # Mark 0th node as visited v[0] = True # Find the minimum weight Hamiltonian Cycle tsp(graph, v, 0, n, 1, 0) # ans is the minimum weight Hamiltonian Cycle print(min(answer)) # This code is contributed by mohit kumar // C# implementation of the approachusing System; class GFG{ // Function to find the minimum weight Hamiltonian Cyclestatic int tsp(int [,]graph, bool []v, int currPos, int n, int count, int cost, int ans){ // If last node is reached and it has a link // to the starting node i.e the source then // keep the minimum value out of the total cost // of traversal and "ans" // Finally return to check for more possible values if (count == n && graph[currPos,0] > 0) { ans = Math.Min(ans, cost + graph[currPos,0]); return ans; } // BACKTRACKING STEP // Loop to traverse the adjacency list // of currPos node and increasing the count // by 1 and cost by graph[currPos,i] value for (int i = 0; i < n; i++) { if (v[i] == false && graph[currPos,i] > 0) { // Mark as visited v[i] = true; ans = tsp(graph, v, i, n, count + 1, cost + graph[currPos,i], ans); // Mark ith node as unvisited v[i] = false; } } return ans;} // Driver codestatic void Main(){ // n is the number of nodes i.e. V int n = 4; int [,]graph = { { 0, 10, 15, 20 }, { 10, 0, 35, 25 }, { 15, 35, 0, 30 }, { 20, 25, 30, 0 } }; // Boolean array to check if a node // has been visited or not bool[] v = new bool[n]; // Mark 0th node as visited v[0] = true; int ans = int.MaxValue; // Find the minimum weight Hamiltonian Cycle ans = tsp(graph, v, 0, n, 1, 0, ans); // ans is the minimum weight Hamiltonian Cycle Console.Write(ans); }} // This code is contributed by mits <script> // Javascript implementation of the approachvar V = 4;var ans = 1000000000;// Boolean array to check if a node// has been visited or notvar v = Array(n).fill(false);// Mark 0th node as visitedv[0] = true; // Function to find the minimum weight Hamiltonian Cyclefunction tsp(graph, currPos, n, count, cost){ // If last node is reached and it has a link // to the starting node i.e the source then // keep the minimum value out of the total cost // of traversal and "ans" // Finally return to check for more possible values if (count == n && graph[currPos][0]) { ans = Math.min(ans, cost + graph[currPos][0]); return; } // BACKTRACKING STEP // Loop to traverse the adjacency list // of currPos node and increasing the count // by 1 and cost by graph[currPos][i] value for (var i = 0; i < n; i++) { if (!v[i] && graph[currPos][i]) { // Mark as visited v[i] = true; tsp(graph, i, n, count + 1, cost + graph[currPos][i]); // Mark ith node as unvisited v[i] = false; } }}; // Driver code// n is the number of nodes i.e. Vvar n = 4;var graph = [ [ 0, 10, 15, 20 ], [ 10, 0, 35, 25 ], [ 15, 35, 0, 30 ], [ 20, 25, 30, 0 ]]; // Find the minimum weight Hamiltonian Cycletsp(graph, 0, n, 1, 0);// ans is the minimum weight Hamiltonian Cycledocument.write( ans); </script> 80 Time Complexity: O(N!), As for the first node there are N possibilities and for the second node there are n – 1 possibilities.For N nodes time complexity = N * (N – 1) * . . . 1 = O(N!)Auxiliary Space: O(N) mohit kumar 29 Mithun Kumar Rajput-Ji sambhav228 rutvik_56 pankajsharmagfg vinayedula Algorithms Backtracking Graph Graph Backtracking Algorithms Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n06 Jun, 2022" }, { "code": null, "e": 860, "s": 52, "text": "Travelling Salesman Problem (TSP): Given a set of cities and distance between every pair of cities, the problem is to find the shortest possible route that visits every city exactly once and returns back to the starting point.Note the difference between Hamiltonian Cycle and TSP. The Hamiltonian cycle problem is to find if there exist a tour that visits every city exactly once. Here we know that Hamiltonian Tour exists (because the graph is complete) and in fact many such tours exist, the problem is to find a minimum weight Hamiltonian Cycle. For example, consider the graph shown in the figure. A TSP tour in the graph is 1 -> 2 -> 4 -> 3 -> 1. The cost of the tour is 10 + 25 + 30 + 15 which is 80.The problem is a famous NP hard problem. There is no polynomial time know solution for this problem. " }, { "code": null, "e": 945, "s": 862, "text": "Output of Given Graph: Minimum weight Hamiltonian Cycle : 10 + 25 + 30 + 15 = 80 " }, { "code": null, "e": 1019, "s": 945, "text": "Approach: In this post, implementation of simple solution is discussed. " }, { "code": null, "e": 1156, "s": 1019, "text": "Consider city 1 (let say 0th node) as the starting and ending point. Since route is cyclic, we can consider any point as starting point." }, { "code": null, "e": 1226, "s": 1156, "text": "Start traversing from the source to its adjacent nodes in dfs manner." }, { "code": null, "e": 1352, "s": 1226, "text": "Calculate cost of every traversal and keep track of minimum cost and keep on updating the value of minimum cost stored value." }, { "code": null, "e": 1394, "s": 1352, "text": "Return the permutation with minimum cost." }, { "code": null, "e": 1447, "s": 1394, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 1451, "s": 1447, "text": "C++" }, { "code": null, "e": 1456, "s": 1451, "text": "Java" }, { "code": null, "e": 1464, "s": 1456, "text": "Python3" }, { "code": null, "e": 1467, "s": 1464, "text": "C#" }, { "code": null, "e": 1478, "s": 1467, "text": "Javascript" }, { "code": "// C++ implementation of the approach#include <bits/stdc++.h>using namespace std;#define V 4 // Function to find the minimum weight Hamiltonian Cyclevoid tsp(int graph[][V], vector<bool>& v, int currPos, int n, int count, int cost, int& ans){ // If last node is reached and it has a link // to the starting node i.e the source then // keep the minimum value out of the total cost // of traversal and \"ans\" // Finally return to check for more possible values if (count == n && graph[currPos][0]) { ans = min(ans, cost + graph[currPos][0]); return; } // BACKTRACKING STEP // Loop to traverse the adjacency list // of currPos node and increasing the count // by 1 and cost by graph[currPos][i] value for (int i = 0; i < n; i++) { if (!v[i] && graph[currPos][i]) { // Mark as visited v[i] = true; tsp(graph, v, i, n, count + 1, cost + graph[currPos][i], ans); // Mark ith node as unvisited v[i] = false; } }}; // Driver codeint main(){ // n is the number of nodes i.e. V int n = 4; int graph[][V] = { { 0, 10, 15, 20 }, { 10, 0, 35, 25 }, { 15, 35, 0, 30 }, { 20, 25, 30, 0 } }; // Boolean array to check if a node // has been visited or not vector<bool> v(n); for (int i = 0; i < n; i++) v[i] = false; // Mark 0th node as visited v[0] = true; int ans = INT_MAX; // Find the minimum weight Hamiltonian Cycle tsp(graph, v, 0, n, 1, 0, ans); // ans is the minimum weight Hamiltonian Cycle cout << ans; return 0;}", "e": 3123, "s": 1478, "text": null }, { "code": "// Java implementation of the approachclass GFG{ // Function to find the minimum weight // Hamiltonian Cycle static int tsp(int[][] graph, boolean[] v, int currPos, int n, int count, int cost, int ans) { // If last node is reached and it has a link // to the starting node i.e the source then // keep the minimum value out of the total cost // of traversal and \"ans\" // Finally return to check for more possible values if (count == n && graph[currPos][0] > 0) { ans = Math.min(ans, cost + graph[currPos][0]); return ans; } // BACKTRACKING STEP // Loop to traverse the adjacency list // of currPos node and increasing the count // by 1 and cost by graph[currPos,i] value for (int i = 0; i < n; i++) { if (v[i] == false && graph[currPos][i] > 0) { // Mark as visited v[i] = true; ans = tsp(graph, v, i, n, count + 1, cost + graph[currPos][i], ans); // Mark ith node as unvisited v[i] = false; } } return ans; } // Driver code public static void main(String[] args) { // n is the number of nodes i.e. V int n = 4; int[][] graph = {{0, 10, 15, 20}, {10, 0, 35, 25}, {15, 35, 0, 30}, {20, 25, 30, 0}}; // Boolean array to check if a node // has been visited or not boolean[] v = new boolean[n]; // Mark 0th node as visited v[0] = true; int ans = Integer.MAX_VALUE; // Find the minimum weight Hamiltonian Cycle ans = tsp(graph, v, 0, n, 1, 0, ans); // ans is the minimum weight Hamiltonian Cycle System.out.println(ans); }} // This code is contributed by Rajput-Ji", "e": 5087, "s": 3123, "text": null }, { "code": "# Python3 implementation of the approachV = 4answer = [] # Function to find the minimum weight# Hamiltonian Cycledef tsp(graph, v, currPos, n, count, cost): # If last node is reached and it has # a link to the starting node i.e # the source then keep the minimum # value out of the total cost of # traversal and \"ans\" # Finally return to check for # more possible values if (count == n and graph[currPos][0]): answer.append(cost + graph[currPos][0]) return # BACKTRACKING STEP # Loop to traverse the adjacency list # of currPos node and increasing the count # by 1 and cost by graph[currPos][i] value for i in range(n): if (v[i] == False and graph[currPos][i]): # Mark as visited v[i] = True tsp(graph, v, i, n, count + 1, cost + graph[currPos][i]) # Mark ith node as unvisited v[i] = False # Driver code # n is the number of nodes i.e. Vif __name__ == '__main__': n = 4 graph= [[ 0, 10, 15, 20 ], [ 10, 0, 35, 25 ], [ 15, 35, 0, 30 ], [ 20, 25, 30, 0 ]] # Boolean array to check if a node # has been visited or not v = [False for i in range(n)] # Mark 0th node as visited v[0] = True # Find the minimum weight Hamiltonian Cycle tsp(graph, v, 0, n, 1, 0) # ans is the minimum weight Hamiltonian Cycle print(min(answer)) # This code is contributed by mohit kumar", "e": 6581, "s": 5087, "text": null }, { "code": "// C# implementation of the approachusing System; class GFG{ // Function to find the minimum weight Hamiltonian Cyclestatic int tsp(int [,]graph, bool []v, int currPos, int n, int count, int cost, int ans){ // If last node is reached and it has a link // to the starting node i.e the source then // keep the minimum value out of the total cost // of traversal and \"ans\" // Finally return to check for more possible values if (count == n && graph[currPos,0] > 0) { ans = Math.Min(ans, cost + graph[currPos,0]); return ans; } // BACKTRACKING STEP // Loop to traverse the adjacency list // of currPos node and increasing the count // by 1 and cost by graph[currPos,i] value for (int i = 0; i < n; i++) { if (v[i] == false && graph[currPos,i] > 0) { // Mark as visited v[i] = true; ans = tsp(graph, v, i, n, count + 1, cost + graph[currPos,i], ans); // Mark ith node as unvisited v[i] = false; } } return ans;} // Driver codestatic void Main(){ // n is the number of nodes i.e. V int n = 4; int [,]graph = { { 0, 10, 15, 20 }, { 10, 0, 35, 25 }, { 15, 35, 0, 30 }, { 20, 25, 30, 0 } }; // Boolean array to check if a node // has been visited or not bool[] v = new bool[n]; // Mark 0th node as visited v[0] = true; int ans = int.MaxValue; // Find the minimum weight Hamiltonian Cycle ans = tsp(graph, v, 0, n, 1, 0, ans); // ans is the minimum weight Hamiltonian Cycle Console.Write(ans); }} // This code is contributed by mits", "e": 8240, "s": 6581, "text": null }, { "code": "<script> // Javascript implementation of the approachvar V = 4;var ans = 1000000000;// Boolean array to check if a node// has been visited or notvar v = Array(n).fill(false);// Mark 0th node as visitedv[0] = true; // Function to find the minimum weight Hamiltonian Cyclefunction tsp(graph, currPos, n, count, cost){ // If last node is reached and it has a link // to the starting node i.e the source then // keep the minimum value out of the total cost // of traversal and \"ans\" // Finally return to check for more possible values if (count == n && graph[currPos][0]) { ans = Math.min(ans, cost + graph[currPos][0]); return; } // BACKTRACKING STEP // Loop to traverse the adjacency list // of currPos node and increasing the count // by 1 and cost by graph[currPos][i] value for (var i = 0; i < n; i++) { if (!v[i] && graph[currPos][i]) { // Mark as visited v[i] = true; tsp(graph, i, n, count + 1, cost + graph[currPos][i]); // Mark ith node as unvisited v[i] = false; } }}; // Driver code// n is the number of nodes i.e. Vvar n = 4;var graph = [ [ 0, 10, 15, 20 ], [ 10, 0, 35, 25 ], [ 15, 35, 0, 30 ], [ 20, 25, 30, 0 ]]; // Find the minimum weight Hamiltonian Cycletsp(graph, 0, n, 1, 0);// ans is the minimum weight Hamiltonian Cycledocument.write( ans); </script>", "e": 9663, "s": 8240, "text": null }, { "code": null, "e": 9666, "s": 9663, "text": "80" }, { "code": null, "e": 9875, "s": 9668, "text": "Time Complexity: O(N!), As for the first node there are N possibilities and for the second node there are n – 1 possibilities.For N nodes time complexity = N * (N – 1) * . . . 1 = O(N!)Auxiliary Space: O(N)" }, { "code": null, "e": 9890, "s": 9875, "text": "mohit kumar 29" }, { "code": null, "e": 9903, "s": 9890, "text": "Mithun Kumar" }, { "code": null, "e": 9913, "s": 9903, "text": "Rajput-Ji" }, { "code": null, "e": 9924, "s": 9913, "text": "sambhav228" }, { "code": null, "e": 9934, "s": 9924, "text": "rutvik_56" }, { "code": null, "e": 9950, "s": 9934, "text": "pankajsharmagfg" }, { "code": null, "e": 9961, "s": 9950, "text": "vinayedula" }, { "code": null, "e": 9972, "s": 9961, "text": "Algorithms" }, { "code": null, "e": 9985, "s": 9972, "text": "Backtracking" }, { "code": null, "e": 9991, "s": 9985, "text": "Graph" }, { "code": null, "e": 9997, "s": 9991, "text": "Graph" }, { "code": null, "e": 10010, "s": 9997, "text": "Backtracking" }, { "code": null, "e": 10021, "s": 10010, "text": "Algorithms" } ]
A single neuron neural network in Python
06 Oct, 2021 Neural networks are the core of deep learning, a field that has practical applications in many different areas. Today neural networks are used for image classification, speech recognition, object detection, etc. Now, Let’s try to understand the basic unit behind all these states of art techniques.A single neuron transforms given input into some output. Depending on the given input and weights assigned to each input, decide whether the neuron fired or not. Let’s assume the neuron has 3 input connections and one output. We will be using tanh activation function in a given example.The end goal is to find the optimal set of weights for this neuron that produces correct results. Do this by training the neuron with several different training examples. At each step calculate the error in the output of the neuron, and backpropagate the gradients. The step of calculating the output of a neuron is called forward propagation while the calculation of gradients is called back propagation.Below is the implementation : Python3 # Python program to implement a# single neuron neural network # import all necessary librariesfrom numpy import exp, array, random, dot, tanh # Class to create a neural# network with single neuronclass NeuralNetwork(): def __init__(self): # Using seed to make sure it'll # generate same weights in every run random.seed(1) # 3x1 Weight matrix self.weight_matrix = 2 * random.random((3, 1)) - 1 # tanh as activation function def tanh(self, x): return tanh(x) # derivative of tanh function. # Needed to calculate the gradients. def tanh_derivative(self, x): return 1.0 - tanh(x) ** 2 # forward propagation def forward_propagation(self, inputs): return self.tanh(dot(inputs, self.weight_matrix)) # training the neural network. def train(self, train_inputs, train_outputs, num_train_iterations): # Number of iterations we want to # perform for this set of input. for iteration in range(num_train_iterations): output = self.forward_propagation(train_inputs) # Calculate the error in the output. error = train_outputs - output # multiply the error by input and then # by gradient of tanh function to calculate # the adjustment needs to be made in weights adjustment = dot(train_inputs.T, error * self.tanh_derivative(output)) # Adjust the weight matrix self.weight_matrix += adjustment # Driver Codeif __name__ == "__main__": neural_network = NeuralNetwork() print ('Random weights at the start of training') print (neural_network.weight_matrix) train_inputs = array([[0, 0, 1], [1, 1, 1], [1, 0, 1], [0, 1, 1]]) train_outputs = array([[0, 1, 1, 0]]).T neural_network.train(train_inputs, train_outputs, 10000) print ('New weights after training') print (neural_network.weight_matrix) # Test the neural network with a new situation. print ("Testing network on new examples ->") print (neural_network.forward_propagation(array([1, 0, 0]))) Output : Random weights at the start of training [[-0.16595599] [ 0.44064899] [-0.99977125]] New weights after training [[5.39428067] [0.19482422] [0.34317086]] Testing network on new examples -> [0.99995873] Akanksha_Rai adnanirshad158 23620uday2021 Neural Network Advanced Computer Subject Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n06 Oct, 2021" }, { "code": null, "e": 577, "s": 52, "text": "Neural networks are the core of deep learning, a field that has practical applications in many different areas. Today neural networks are used for image classification, speech recognition, object detection, etc. Now, Let’s try to understand the basic unit behind all these states of art techniques.A single neuron transforms given input into some output. Depending on the given input and weights assigned to each input, decide whether the neuron fired or not. Let’s assume the neuron has 3 input connections and one output. " }, { "code": null, "e": 1075, "s": 577, "text": "We will be using tanh activation function in a given example.The end goal is to find the optimal set of weights for this neuron that produces correct results. Do this by training the neuron with several different training examples. At each step calculate the error in the output of the neuron, and backpropagate the gradients. The step of calculating the output of a neuron is called forward propagation while the calculation of gradients is called back propagation.Below is the implementation : " }, { "code": null, "e": 1083, "s": 1075, "text": "Python3" }, { "code": "# Python program to implement a# single neuron neural network # import all necessary librariesfrom numpy import exp, array, random, dot, tanh # Class to create a neural# network with single neuronclass NeuralNetwork(): def __init__(self): # Using seed to make sure it'll # generate same weights in every run random.seed(1) # 3x1 Weight matrix self.weight_matrix = 2 * random.random((3, 1)) - 1 # tanh as activation function def tanh(self, x): return tanh(x) # derivative of tanh function. # Needed to calculate the gradients. def tanh_derivative(self, x): return 1.0 - tanh(x) ** 2 # forward propagation def forward_propagation(self, inputs): return self.tanh(dot(inputs, self.weight_matrix)) # training the neural network. def train(self, train_inputs, train_outputs, num_train_iterations): # Number of iterations we want to # perform for this set of input. for iteration in range(num_train_iterations): output = self.forward_propagation(train_inputs) # Calculate the error in the output. error = train_outputs - output # multiply the error by input and then # by gradient of tanh function to calculate # the adjustment needs to be made in weights adjustment = dot(train_inputs.T, error * self.tanh_derivative(output)) # Adjust the weight matrix self.weight_matrix += adjustment # Driver Codeif __name__ == \"__main__\": neural_network = NeuralNetwork() print ('Random weights at the start of training') print (neural_network.weight_matrix) train_inputs = array([[0, 0, 1], [1, 1, 1], [1, 0, 1], [0, 1, 1]]) train_outputs = array([[0, 1, 1, 0]]).T neural_network.train(train_inputs, train_outputs, 10000) print ('New weights after training') print (neural_network.weight_matrix) # Test the neural network with a new situation. print (\"Testing network on new examples ->\") print (neural_network.forward_propagation(array([1, 0, 0])))", "e": 3320, "s": 1083, "text": null }, { "code": null, "e": 3331, "s": 3320, "text": "Output : " }, { "code": null, "e": 3537, "s": 3331, "text": "Random weights at the start of training\n[[-0.16595599]\n [ 0.44064899]\n [-0.99977125]]\n\nNew weights after training\n[[5.39428067]\n [0.19482422]\n [0.34317086]]\n\nTesting network on new examples ->\n[0.99995873]" }, { "code": null, "e": 3552, "s": 3539, "text": "Akanksha_Rai" }, { "code": null, "e": 3567, "s": 3552, "text": "adnanirshad158" }, { "code": null, "e": 3581, "s": 3567, "text": "23620uday2021" }, { "code": null, "e": 3596, "s": 3581, "text": "Neural Network" }, { "code": null, "e": 3622, "s": 3596, "text": "Advanced Computer Subject" }, { "code": null, "e": 3629, "s": 3622, "text": "Python" } ]
How to declare a module in TypeScript ?
04 Oct, 2021 A module is a piece of code that can be called or used in another code. There is nothing new about modules in Typescript. The concept of the module was introduced by JavaScript with ECMAScript 2015 release. Typescript is just re-using this feature. Will the code not work without Modules? Of course, it will. The code will still work. But there are major drawbacks with the code that is not modularized. Let’s say we created a very basic chatting application that can either send or receive text messages. Initially, we have added our entire code in just 2-3 files and the application is working great. Later we decided to add a feature to record and send audio messages also. For this, we again added more code into the same files and the application is still doing great. Later we decided to add features like share images or share videos or maybe some large documents as well and we kept on dumping code into the same files or maybe 1 or 2 extra files. Now there is a problem. Here are few issues that we can foresee: Our app will start becoming slow (or super slow at one point).Frequent crashing of the application causing potential loss of dataCode base will become spaghetti (impossible to maintain)Bug fixing or debugging is another big issueNightmare for the testing team Our app will start becoming slow (or super slow at one point). Frequent crashing of the application causing potential loss of data Code base will become spaghetti (impossible to maintain) Bug fixing or debugging is another big issue Nightmare for the testing team All the above problems (and more) can be solved if we just make our code more modular. Development efforts without using module: Let’s mimic a scenario. We want to buy some fruits. Maybe Apple, Kiwi, and Strawberry. We’ll create 3 separate classes for all 3. Since all 3 are fruits so they share some common features like name, color, and quantity. So we’ll create one more class (as a data type) with one method. Let’s create classes one by one. 1. Creating Apple class: Right-click into project folder and click ‘New file’. Call it apple.ts. First we will define Fruit class here to be used as data type for apple and In the same file We will define class for Apple also: Javascript class Fruit { // Properties that every fruits have name: string; color: string; quantity: number; // To initialize the values constructor(name, color, quantity) { // Initialize values using this operator } myCart() { // A simple placeholder text console.log("I have " + this.quantity + " " + this.color + " " + this.name + " in my cart"); }} class Apple { // Initialize Fruits class with values fruits: Fruits = new Fruits(..., ..., ...); constructor() { // call method to see everything is correct this.fruits.myCart(); }} // initialize apple class and call// its constructor automaticallyvar obj: Apple = new Apple(); We will do the same procedure for Kiwi class 2. Creating Kiwi class: Right-click into project folder and click ‘New file’. Call it kiwi.ts. First we will define Fruit class here to be used as data type for kiwi and In the same file we will define class for Kiwi also: Javascript class Fruit { // Properties that every fruits have name: string; color: string; quantity: number; // Initialize the values constructor(name, color, quantity) { // Initialize values using this operator } myCart() { // A simple placeholder text console.log("I have " + this.quantity + " " + this.color + " " + this.name + " in my cart"); }} class Kiwi { // Initialize Fruits class with values fruits: Fruits = new Fruits(..., ..., ...); constructor() { // Call method to see everything is correct this.fruits.myCart(); }} // Initialize kiwi class and// call its constructor automaticallyvar obj: Kiwi = new Kiwi(); 3. Creating Strawberry class: Right-click into the project folder and click ‘New file’. Call it strawberry.ts. First we will define Fruit class here to be used as the data type for strawberry and In the same file we will define class for Strawberry also: Javascript class Fruit { // Properties that every fruits have name: string; color: string; quantity: number; // Initialize the values constructor(name, color, quantity) { // Initialize values using this operator } myCart() { // A simple placeholder text console.log("I have " + this.quantity + " " + this.color + " " + this.name + " in my cart"); }} class Strawberry { // Initialize Fruits class with values fruits: Fruits = new Fruits(..., ..., ...); constructor() { // Call method to see everything is correct this.fruits.myCart(); }} // Initialize strawberry class and// call its constructor automaticallyvar obj: Strawberry = new Strawberry(); Reduced development efforts using modular approach: There is a major flaw in the above approach. Yes, you are right. Redefining the same Fruits class, again and again, is painfully stupid. That’s where the module comes into the picture. What if we keep Fruits class in one file and call it one module and then just call that class/module wherever required. This will save a considerable amount of time and effort of developer. Let’s do that quickly. Step 1: Create a new file called Fruits.ts Step 2: Remove Fruits class definition from all 3 classes Step 3: Paste it at only one location i.e. file Fruits.ts Javascript export class Fruit { // Properties that every fruits have name: string; color: string; quantity: number; // Initialize the values constructor(name, color, quantity) { // Initialize values using this operator } myCart() { // A simple placeholder text console.log("I have " + this.quantity + " " + this.color + " " + this.name + " in my cart"); }} console.log("Hello world!"); Notice that we are using the export keyword in the first place. Export keyword actually makes it possible for our class (or interface) to be used somewhere else in the project. In parallel, we use Import statement in the module that wants to use the exported module. Also notice that we have added one console log statement at the end of the file. It’s not required, but we want to tell you an important fact later in this article itself. For now, you can just ignore it and assume it is not there. Now when we have our module ready. We can just call it in our classes. Technically we call it ‘importing‘ and we use a keyword called ‘import‘. Syntax: import {classname} from './location'; Let’s import the same quickly: Filename: Apple.ts Javascript import { Fruits } from './main'; class Apple { fruits: Fruits = new Fruits('apples', 'green', 5); constructor() { this.fruits.myCart(); }}var obj: Apple = new Apple(); Filename: Kiwi.ts Javascript import { Fruits } from './main';class Kiwi { fruits: Fruits = new Fruits('kiwi', 'golden', 2); constructor() { this.fruits.myCart(); }}var obj: Kiwi = new Kiwi(); Filename: Strawberry.ts Javascript import { Fruits } from './main';class Strawberry { fruits: Fruits = new Fruits('strawberries', 'red', 5); constructor() { this.fruits.myCart(); }}var obj: Strawberry = new Strawberry(); See how clean it looks. It’s easy to understand and easy to maintain now. That’s the whole idea behind the modular approach. Some Left over points: We have added one console statement at the last. There is the reason for that. Let me first show you the output. Output See every time we run the files, we are getting a class-specific output but also we are getting “Hello world!” The reason is that it doesn’t belong to the exported class. Then why it was called. The reason is whenever we import a module, the entire module is once executed as one simple program and every line inside the file will get executed no matter it is inside the export class braces or not. So be careful what you put in there. In an expert’s opinion, there should be no stray line of code. Use them in some method or just remove those statements if they are not required. Summary: So, the module is nothing but a concept or approach where a piece of code is kept separated and exported explicitly so that other pieces of code can import it. We use export keywords to make a class available publicly and we use import to use that exported module. How to execute the code: First we will run: tsc apple.ts Then we will run: node apple.js This is so because not all browsers understand Typescript like they understand JavaScript. So the Typescript first has to be compiled into JavaScript that’s why we use node command for that. We can also club the two commands together using the AND operator: For Linux: tsc apple.ts && node apple.js For windows I can use pipe operator: tsc apple.ts | node apple.js Similarly, I can run Kiwi and Strawberry classes. Final output: One last note: This is the professional way to write the code and is globally followed. So, tomorrow if you are writing the code or reviewing someone else’s code please pay special attention to the code modularity. This will make your life easier. arorakashish0911 JavaScript-Questions Picked TypeScript 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": "\n04 Oct, 2021" }, { "code": null, "e": 277, "s": 28, "text": "A module is a piece of code that can be called or used in another code. There is nothing new about modules in Typescript. The concept of the module was introduced by JavaScript with ECMAScript 2015 release. Typescript is just re-using this feature." }, { "code": null, "e": 317, "s": 277, "text": "Will the code not work without Modules?" }, { "code": null, "e": 432, "s": 317, "text": "Of course, it will. The code will still work. But there are major drawbacks with the code that is not modularized." }, { "code": null, "e": 1049, "s": 432, "text": "Let’s say we created a very basic chatting application that can either send or receive text messages. Initially, we have added our entire code in just 2-3 files and the application is working great. Later we decided to add a feature to record and send audio messages also. For this, we again added more code into the same files and the application is still doing great. Later we decided to add features like share images or share videos or maybe some large documents as well and we kept on dumping code into the same files or maybe 1 or 2 extra files. Now there is a problem. Here are few issues that we can foresee:" }, { "code": null, "e": 1309, "s": 1049, "text": "Our app will start becoming slow (or super slow at one point).Frequent crashing of the application causing potential loss of dataCode base will become spaghetti (impossible to maintain)Bug fixing or debugging is another big issueNightmare for the testing team" }, { "code": null, "e": 1372, "s": 1309, "text": "Our app will start becoming slow (or super slow at one point)." }, { "code": null, "e": 1440, "s": 1372, "text": "Frequent crashing of the application causing potential loss of data" }, { "code": null, "e": 1497, "s": 1440, "text": "Code base will become spaghetti (impossible to maintain)" }, { "code": null, "e": 1542, "s": 1497, "text": "Bug fixing or debugging is another big issue" }, { "code": null, "e": 1573, "s": 1542, "text": "Nightmare for the testing team" }, { "code": null, "e": 1660, "s": 1573, "text": "All the above problems (and more) can be solved if we just make our code more modular." }, { "code": null, "e": 2020, "s": 1660, "text": "Development efforts without using module: Let’s mimic a scenario. We want to buy some fruits. Maybe Apple, Kiwi, and Strawberry. We’ll create 3 separate classes for all 3. Since all 3 are fruits so they share some common features like name, color, and quantity. So we’ll create one more class (as a data type) with one method. Let’s create classes one by one." }, { "code": null, "e": 2247, "s": 2020, "text": "1. Creating Apple class: Right-click into project folder and click ‘New file’. Call it apple.ts. First we will define Fruit class here to be used as data type for apple and In the same file We will define class for Apple also:" }, { "code": null, "e": 2258, "s": 2247, "text": "Javascript" }, { "code": "class Fruit { // Properties that every fruits have name: string; color: string; quantity: number; // To initialize the values constructor(name, color, quantity) { // Initialize values using this operator } myCart() { // A simple placeholder text console.log(\"I have \" + this.quantity + \" \" + this.color + \" \" + this.name + \" in my cart\"); }} class Apple { // Initialize Fruits class with values fruits: Fruits = new Fruits(..., ..., ...); constructor() { // call method to see everything is correct this.fruits.myCart(); }} // initialize apple class and call// its constructor automaticallyvar obj: Apple = new Apple();", "e": 2925, "s": 2258, "text": null }, { "code": null, "e": 2971, "s": 2925, "text": " We will do the same procedure for Kiwi class" }, { "code": null, "e": 3194, "s": 2971, "text": "2. Creating Kiwi class: Right-click into project folder and click ‘New file’. Call it kiwi.ts. First we will define Fruit class here to be used as data type for kiwi and In the same file we will define class for Kiwi also:" }, { "code": null, "e": 3205, "s": 3194, "text": "Javascript" }, { "code": "class Fruit { // Properties that every fruits have name: string; color: string; quantity: number; // Initialize the values constructor(name, color, quantity) { // Initialize values using this operator } myCart() { // A simple placeholder text console.log(\"I have \" + this.quantity + \" \" + this.color + \" \" + this.name + \" in my cart\"); }} class Kiwi { // Initialize Fruits class with values fruits: Fruits = new Fruits(..., ..., ...); constructor() { // Call method to see everything is correct this.fruits.myCart(); }} // Initialize kiwi class and// call its constructor automaticallyvar obj: Kiwi = new Kiwi();", "e": 3869, "s": 3205, "text": null }, { "code": null, "e": 4125, "s": 3869, "text": " 3. Creating Strawberry class: Right-click into the project folder and click ‘New file’. Call it strawberry.ts. First we will define Fruit class here to be used as the data type for strawberry and In the same file we will define class for Strawberry also:" }, { "code": null, "e": 4136, "s": 4125, "text": "Javascript" }, { "code": "class Fruit { // Properties that every fruits have name: string; color: string; quantity: number; // Initialize the values constructor(name, color, quantity) { // Initialize values using this operator } myCart() { // A simple placeholder text console.log(\"I have \" + this.quantity + \" \" + this.color + \" \" + this.name + \" in my cart\"); }} class Strawberry { // Initialize Fruits class with values fruits: Fruits = new Fruits(..., ..., ...); constructor() { // Call method to see everything is correct this.fruits.myCart(); }} // Initialize strawberry class and// call its constructor automaticallyvar obj: Strawberry = new Strawberry();", "e": 4833, "s": 4136, "text": null }, { "code": null, "e": 5284, "s": 4833, "text": " Reduced development efforts using modular approach: There is a major flaw in the above approach. Yes, you are right. Redefining the same Fruits class, again and again, is painfully stupid. That’s where the module comes into the picture. What if we keep Fruits class in one file and call it one module and then just call that class/module wherever required. This will save a considerable amount of time and effort of developer. Let’s do that quickly." }, { "code": null, "e": 5327, "s": 5284, "text": "Step 1: Create a new file called Fruits.ts" }, { "code": null, "e": 5385, "s": 5327, "text": "Step 2: Remove Fruits class definition from all 3 classes" }, { "code": null, "e": 5443, "s": 5385, "text": "Step 3: Paste it at only one location i.e. file Fruits.ts" }, { "code": null, "e": 5454, "s": 5443, "text": "Javascript" }, { "code": "export class Fruit { // Properties that every fruits have name: string; color: string; quantity: number; // Initialize the values constructor(name, color, quantity) { // Initialize values using this operator } myCart() { // A simple placeholder text console.log(\"I have \" + this.quantity + \" \" + this.color + \" \" + this.name + \" in my cart\"); }} console.log(\"Hello world!\");", "e": 5867, "s": 5454, "text": null }, { "code": null, "e": 6135, "s": 5867, "text": " Notice that we are using the export keyword in the first place. Export keyword actually makes it possible for our class (or interface) to be used somewhere else in the project. In parallel, we use Import statement in the module that wants to use the exported module." }, { "code": null, "e": 6367, "s": 6135, "text": "Also notice that we have added one console log statement at the end of the file. It’s not required, but we want to tell you an important fact later in this article itself. For now, you can just ignore it and assume it is not there." }, { "code": null, "e": 6511, "s": 6367, "text": "Now when we have our module ready. We can just call it in our classes. Technically we call it ‘importing‘ and we use a keyword called ‘import‘." }, { "code": null, "e": 6519, "s": 6511, "text": "Syntax:" }, { "code": null, "e": 6557, "s": 6519, "text": "import {classname} from './location';" }, { "code": null, "e": 6588, "s": 6557, "text": "Let’s import the same quickly:" }, { "code": null, "e": 6607, "s": 6588, "text": "Filename: Apple.ts" }, { "code": null, "e": 6618, "s": 6607, "text": "Javascript" }, { "code": "import { Fruits } from './main'; class Apple { fruits: Fruits = new Fruits('apples', 'green', 5); constructor() { this.fruits.myCart(); }}var obj: Apple = new Apple();", "e": 6794, "s": 6618, "text": null }, { "code": null, "e": 6813, "s": 6794, "text": " Filename: Kiwi.ts" }, { "code": null, "e": 6824, "s": 6813, "text": "Javascript" }, { "code": "import { Fruits } from './main';class Kiwi { fruits: Fruits = new Fruits('kiwi', 'golden', 2); constructor() { this.fruits.myCart(); }}var obj: Kiwi = new Kiwi();", "e": 6995, "s": 6824, "text": null }, { "code": null, "e": 7020, "s": 6995, "text": " Filename: Strawberry.ts" }, { "code": null, "e": 7031, "s": 7020, "text": "Javascript" }, { "code": "import { Fruits } from './main';class Strawberry { fruits: Fruits = new Fruits('strawberries', 'red', 5); constructor() { this.fruits.myCart(); }}var obj: Strawberry = new Strawberry();", "e": 7225, "s": 7031, "text": null }, { "code": null, "e": 7351, "s": 7225, "text": " See how clean it looks. It’s easy to understand and easy to maintain now. That’s the whole idea behind the modular approach." }, { "code": null, "e": 7488, "s": 7351, "text": "Some Left over points: We have added one console statement at the last. There is the reason for that. Let me first show you the output. " }, { "code": null, "e": 7495, "s": 7488, "text": "Output" }, { "code": null, "e": 7606, "s": 7495, "text": "See every time we run the files, we are getting a class-specific output but also we are getting “Hello world!”" }, { "code": null, "e": 8076, "s": 7606, "text": "The reason is that it doesn’t belong to the exported class. Then why it was called. The reason is whenever we import a module, the entire module is once executed as one simple program and every line inside the file will get executed no matter it is inside the export class braces or not. So be careful what you put in there. In an expert’s opinion, there should be no stray line of code. Use them in some method or just remove those statements if they are not required." }, { "code": null, "e": 8350, "s": 8076, "text": "Summary: So, the module is nothing but a concept or approach where a piece of code is kept separated and exported explicitly so that other pieces of code can import it. We use export keywords to make a class available publicly and we use import to use that exported module." }, { "code": null, "e": 8375, "s": 8350, "text": "How to execute the code:" }, { "code": null, "e": 8394, "s": 8375, "text": "First we will run:" }, { "code": null, "e": 8407, "s": 8394, "text": "tsc apple.ts" }, { "code": null, "e": 8425, "s": 8407, "text": "Then we will run:" }, { "code": null, "e": 8439, "s": 8425, "text": "node apple.js" }, { "code": null, "e": 8697, "s": 8439, "text": "This is so because not all browsers understand Typescript like they understand JavaScript. So the Typescript first has to be compiled into JavaScript that’s why we use node command for that. We can also club the two commands together using the AND operator:" }, { "code": null, "e": 8708, "s": 8697, "text": "For Linux:" }, { "code": null, "e": 8738, "s": 8708, "text": "tsc apple.ts && node apple.js" }, { "code": null, "e": 8775, "s": 8738, "text": "For windows I can use pipe operator:" }, { "code": null, "e": 8804, "s": 8775, "text": "tsc apple.ts | node apple.js" }, { "code": null, "e": 8854, "s": 8804, "text": "Similarly, I can run Kiwi and Strawberry classes." }, { "code": null, "e": 8868, "s": 8854, "text": "Final output:" }, { "code": null, "e": 8883, "s": 8868, "text": "One last note:" }, { "code": null, "e": 9116, "s": 8883, "text": "This is the professional way to write the code and is globally followed. So, tomorrow if you are writing the code or reviewing someone else’s code please pay special attention to the code modularity. This will make your life easier." }, { "code": null, "e": 9135, "s": 9118, "text": "arorakashish0911" }, { "code": null, "e": 9156, "s": 9135, "text": "JavaScript-Questions" }, { "code": null, "e": 9163, "s": 9156, "text": "Picked" }, { "code": null, "e": 9174, "s": 9163, "text": "TypeScript" }, { "code": null, "e": 9185, "s": 9174, "text": "JavaScript" }, { "code": null, "e": 9202, "s": 9185, "text": "Web Technologies" } ]
Erlang - Macros
Macros are generally used for inline code replacements. In Erlang, macros are defined via the following statements. -define(Constant, Replacement). -define(Func(Var1, Var2,.., Var), Replacement). Following is an example of macros using the first syntax − -module(helloworld). -export([start/0]). -define(a,1). start() -> io:fwrite("~w",[?a]). From the above program you can see that the macro gets expanded by using the ‘?’ symbol. The constant gets replaced in place by the value defined in the macro. The output of the above program will be − 1 An example of a macro using the function class is as follows − -module(helloworld). -export([start/0]). -define(macro1(X,Y),{X+Y}). start() -> io:fwrite("~w",[?macro1(1,2)]). The output of the above program will be − {3} The following additional statements are available for macros − undef(Macro) − Undefines the macro; after this you cannot call the macro. undef(Macro) − Undefines the macro; after this you cannot call the macro. ifdef(Macro) − Evaluates the following lines only if the Macro has been defined. ifdef(Macro) − Evaluates the following lines only if the Macro has been defined. ifndef(Macro) − Evaluates the following lines only if Macro is undefined. ifndef(Macro) − Evaluates the following lines only if Macro is undefined. else − Allowed after an ifdef or ifndef statement. If the condition was false, the statements following else are evaluated. else − Allowed after an ifdef or ifndef statement. If the condition was false, the statements following else are evaluated. endif − Marks the end of an ifdef or ifndef statement. endif − Marks the end of an ifdef or ifndef statement. When using the above statements, it should be used in the proper way as shown in the following program. -ifdef(<FlagName>). -define(...). -else. -define(...). -endif. Print Add Notes Bookmark this page
[ { "code": null, "e": 2417, "s": 2301, "text": "Macros are generally used for inline code replacements. In Erlang, macros are defined via the following statements." }, { "code": null, "e": 2449, "s": 2417, "text": "-define(Constant, Replacement)." }, { "code": null, "e": 2497, "s": 2449, "text": "-define(Func(Var1, Var2,.., Var), Replacement)." }, { "code": null, "e": 2556, "s": 2497, "text": "Following is an example of macros using the first syntax −" }, { "code": null, "e": 2652, "s": 2556, "text": "-module(helloworld). \n-export([start/0]). \n-define(a,1). \n\nstart() -> \n io:fwrite(\"~w\",[?a])." }, { "code": null, "e": 2812, "s": 2652, "text": "From the above program you can see that the macro gets expanded by using the ‘?’ symbol. The constant gets replaced in place by the value defined in the macro." }, { "code": null, "e": 2854, "s": 2812, "text": "The output of the above program will be −" }, { "code": null, "e": 2857, "s": 2854, "text": "1\n" }, { "code": null, "e": 2920, "s": 2857, "text": "An example of a macro using the function class is as follows −" }, { "code": null, "e": 3039, "s": 2920, "text": "-module(helloworld). \n-export([start/0]). \n-define(macro1(X,Y),{X+Y}). \n\nstart() ->\n io:fwrite(\"~w\",[?macro1(1,2)])." }, { "code": null, "e": 3081, "s": 3039, "text": "The output of the above program will be −" }, { "code": null, "e": 3086, "s": 3081, "text": "{3}\n" }, { "code": null, "e": 3149, "s": 3086, "text": "The following additional statements are available for macros −" }, { "code": null, "e": 3223, "s": 3149, "text": "undef(Macro) − Undefines the macro; after this you cannot call the macro." }, { "code": null, "e": 3297, "s": 3223, "text": "undef(Macro) − Undefines the macro; after this you cannot call the macro." }, { "code": null, "e": 3378, "s": 3297, "text": "ifdef(Macro) − Evaluates the following lines only if the Macro has been defined." }, { "code": null, "e": 3459, "s": 3378, "text": "ifdef(Macro) − Evaluates the following lines only if the Macro has been defined." }, { "code": null, "e": 3533, "s": 3459, "text": "ifndef(Macro) − Evaluates the following lines only if Macro is undefined." }, { "code": null, "e": 3607, "s": 3533, "text": "ifndef(Macro) − Evaluates the following lines only if Macro is undefined." }, { "code": null, "e": 3731, "s": 3607, "text": "else − Allowed after an ifdef or ifndef statement. If the condition was false, the statements following else are evaluated." }, { "code": null, "e": 3855, "s": 3731, "text": "else − Allowed after an ifdef or ifndef statement. If the condition was false, the statements following else are evaluated." }, { "code": null, "e": 3910, "s": 3855, "text": "endif − Marks the end of an ifdef or ifndef statement." }, { "code": null, "e": 3965, "s": 3910, "text": "endif − Marks the end of an ifdef or ifndef statement." }, { "code": null, "e": 4069, "s": 3965, "text": "When using the above statements, it should be used in the proper way as shown in the following program." }, { "code": null, "e": 4134, "s": 4069, "text": "-ifdef(<FlagName>).\n\n-define(...).\n-else.\n-define(...).\n-endif.\n" }, { "code": null, "e": 4141, "s": 4134, "text": " Print" }, { "code": null, "e": 4152, "s": 4141, "text": " Add Notes" } ]
Largest element in the array that is repeated exactly k times
11 May, 2021 Given an array of integers and an integer ‘k’, the task is to find the largest element from the array that is repeated exactly ‘k’ times.Examples: Input: arr = {1, 1, 2, 3, 3, 4, 5, 5, 6, 6, 6}, k = 2 Output: 5 The elements that exactly occur 2 times are 1, 3 and 5 And, the largest element among them is 5. Input: arr = {1, 2, 3, 4, 5, 6}, k = 2 Output: No such element There isn't any element in the array that occurs exactly 2 times. A simple approach: Sort the array. Start traversing the array from the end (as we’re interested in the largest element that satisfies the condition) and count the frequencies of each element by comparing the element with it’s neighbour elements. The first element from the right that occurs exactly ‘k’ times is the answer. If no element is found that occurs exactly ‘k’ times then print ‘No such element’. Below is the implementation of the above approach: C++ Java Python 3 C# PHP Javascript // C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Function that finds the largest// element which is repeated 'k' timesvoid solve(int arr[], int n, int k){ // sort the array sort(arr, arr + n); // if the value of 'k' is 1 and the // largest appears only once in the array if (k == 1 && arr[n - 2] != arr[n - 1]) { cout << arr[n - 1] << endl; return; } // counter to count // the repeated elements int count = 1; for (int i = n - 2; i >= 0; i--) { // check if the element at index 'i' // is equal to the element at index 'i+1' // then increase the count if (arr[i] == arr[i + 1]) count++; // else set the count to 1 // to start counting the frequency // of the new number else count = 1; // if the count is equal to k // and the previous element // is not equal to this element if (count == k && (i == 0 || (arr[i - 1] != arr[i]))) { cout << arr[i] << endl; return; } } // if there is no such element cout << "No such element" << endl;} // Driver codeint main(){ int arr[] = { 1, 1, 2, 3, 3, 4, 5, 5, 6, 6, 6 }; int k = 2; int n = sizeof(arr) / sizeof(int); // find the largest element // that is repeated K times solve(arr, n, k); return 0;} // Java implementation of the above approach import java.util.Arrays ; public class GFG { // Function that finds the largest // element which is repeated 'k' times static void solve(int arr[], int n, int k) { // sort the array Arrays.sort(arr); // if the value of 'k' is 1 and the // largest appears only once in the array if (k == 1 && arr[n - 2] != arr[n - 1]) { System.out.println(arr[n - 1]); return; } // counter to count // the repeated elements int count = 1; for (int i = n - 2; i >= 0; i--) { // check if the element at index 'i' // is equal to the element at index 'i+1' // then increase the count if (arr[i] == arr[i + 1]) count++; // else set the count to 1 // to start counting the frequency // of the new number else count = 1; // if the count is equal to k // and the previous element // is not equal to this element if (count == k && (i == 0 || (arr[i - 1] != arr[i]))) { System.out.println(arr[i]); return; } } // if there is no such element System.out.println("No such element"); } // Driver code public static void main(String args[]) { int arr[] = { 1, 1, 2, 3, 3, 4, 5, 5, 6, 6, 6 }; int k = 2; int n = arr.length; // find the largest element // that is repeated K times solve(arr, n, k); } // This code is contributed by ANKITRAI1} # Python 3 implementation of the approach # Function that finds the largest# element which is repeated 'k' timesdef solve(arr, n, k): # sort the array arr.sort() # if the value of 'k' is 1 and the # largest appears only once in the array if (k == 1 and arr[n - 2] != arr[n - 1]): print( arr[n - 1] ) return # counter to count # the repeated elements count = 1 for i in range(n - 2, -1, -1) : # check if the element at index 'i' # is equal to the element at index 'i+1' # then increase the count if (arr[i] == arr[i + 1]): count += 1 # else set the count to 1 # to start counting the frequency # of the new number else: count = 1 # if the count is equal to k # and the previous element # is not equal to this element if (count == k and (i == 0 or (arr[i - 1] != arr[i]))): print(arr[i]) return # if there is no such element print("No such element") # Driver codeif __name__ == "__main__": arr = [ 1, 1, 2, 3, 3, 4, 5, 5, 6, 6, 6 ] k = 2 n = len(arr) # find the largest element # that is repeated K times solve(arr, n, k) # This code is contributed# by ChitraNayal // C# implementation of the above approachusing System; class GFG{// Function that finds the largest// element which is repeated 'k' timesstatic void solve(int []arr, int n, int k){ // sort the array Array.Sort(arr); // if the value of 'k' is 1 and the // largest appears only once in the array if (k == 1 && arr[n - 2] != arr[n - 1]) { Console.WriteLine(arr[n - 1]); return; } // counter to count // the repeated elements int count = 1; for (int i = n - 2; i >= 0; i--) { // check if the element at index 'i' // is equal to the element at index 'i+1' // then increase the count if (arr[i] == arr[i + 1]) count++; // else set the count to 1 // to start counting the frequency // of the new number else count = 1; // if the count is equal to k // and the previous element // is not equal to this element if (count == k && (i == 0 || (arr[i - 1] != arr[i]))) { Console.WriteLine(arr[i]); return; } } // if there is no such element Console.WriteLine("No such element");} // Driver codestatic public void Main (){ int []arr = { 1, 1, 2, 3, 3, 4, 5, 5, 6, 6, 6 }; int k = 2; int n = arr.Length; // find the largest element // that is repeated K times solve(arr, n, k);}} // This code is contributed// by Sach_Code <?php// PHP implementation of the approach // Function that finds the largest// element which is repeated 'k' timesfunction solve(&$arr, $n, $k){ // sort the array sort($arr); // if the value of 'k' is 1 and the // largest appears only once in the array if ($k == 1 && $arr[$n - 2] != $arr[$n - 1]) { echo $arr[$n - 1] ; echo ("\n"); return; } // counter to count // the repeated elements $count = 1; for ($i = $n - 2; $i >= 0; $i--) { // check if the element at index 'i' // is equal to the element at index 'i+1' // then increase the count if ($arr[$i] == $arr[$i + 1]) $count++; // else set the count to 1 // to start counting the frequency // of the new number else $count = 1; // if the count is equal to k // and the previous element // is not equal to this element if ($count == $k && ($i == 0 || ($arr[$i - 1] != $arr[$i]))) { echo ($arr[$i]); echo ("\n"); return; } } // if there is no such element echo ("No such element"); echo ("\n");} // Driver code$arr = array(1, 1, 2, 3, 3, 4, 5, 5, 6, 6, 6 );$k = 2;$n = sizeof($arr); // find the largest element// that is repeated K timessolve($arr, $n, $k); // This code is contributed// by Shivi_Aggarwal?> <script> // Javascript implementation of the approach // Function that finds the largest// element which is repeated 'k' timesfunction solve(arr, n, k){ // sort the array arr.sort((a,b)=> a-b) // if the value of 'k' is 1 and the // largest appears only once in the array if (k == 1 && arr[n - 2] != arr[n - 1]) { cout << arr[n - 1] << endl; return; } // counter to count // the repeated elements var count = 1; for (var i = n - 2; i >= 0; i--) { // check if the element at index 'i' // is equal to the element at index 'i+1' // then increase the count if (arr[i] == arr[i + 1]) count++; // else set the count to 1 // to start counting the frequency // of the new number else count = 1; // if the count is equal to k // and the previous element // is not equal to this element if (count == k && (i == 0 || (arr[i - 1] != arr[i]))) { document.write( arr[i] + "<br>"); return; } } // if there is no such element document.write( "No such element" );} // Driver codevar arr = [ 1, 1, 2, 3, 3, 4, 5, 5, 6, 6, 6 ];var k = 2;var n = arr.length;// find the largest element// that is repeated K timessolve(arr, n, k); </script> 5 Time Complexity: O(N*log(N))Efficient approach: Create a map and store the frequency of each element in the map. Then, traverse the array and find out the largest element that has frequency equal to ‘k’. If found, print the number Else, print ‘No such element’. Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ implementation of above approach#include <bits/stdc++.h>using namespace std; // Function that finds the largest// element that occurs exactly 'k' timesvoid solve(int arr[], int n, int k){ // store the frequency // of each element unordered_map<int, int> m; for (int i = 0; i < n; i++) { m[arr[i]]++; } // to store the maximum element int max = INT_MIN; for (int i = 0; i < n; i++) { // if current element has frequency 'k' // and current maximum hasn't been set if (m[arr[i]] == k && max == INT_MIN) { // set the current maximum max = arr[i]; } // if current element has // frequency 'k' and it is // greater than the current maximum else if (m[arr[i]] == k && max < arr[i]) { // change the current maximum max = arr[i]; } } // if there is no element // with frequency 'k' if (max == INT_MIN) cout << "No such element" << endl; // print the largest element // with frequency 'k' else cout << max << endl;} // Driver codeint main(){ int arr[] = { 1, 1, 2, 3, 3, 4, 5, 5, 6, 6, 6 }; int k = 4; int n = sizeof(arr) / sizeof(int); // find the largest element // that is repeated K times solve(arr, n, k); return 0;} // Java implementation of above approachimport java.util.HashMap;import java.util.Map; class GfG{ // Function that finds the largest // element that occurs exactly 'k' times static void solve(int arr[], int n, int k) { // store the frequency of each element HashMap<Integer, Integer> m = new HashMap<>(); for (int i = 0; i < n; i++) { if (!m.containsKey(arr[i])) m.put(arr[i], 0); m.put(arr[i], m.get(arr[i]) + 1); } // to store the maximum element int max = Integer.MIN_VALUE; for (int i = 0; i < n; i++) { // If current element has frequency 'k' // and current maximum hasn't been set if (m.get(arr[i]) == k && max == Integer.MIN_VALUE) { // set the current maximum max = arr[i]; } // if current element has // frequency 'k' and it is // greater than the current maximum else if (m.get(arr[i]) == k && max < arr[i]) { // change the current maximum max = arr[i]; } } // if there is no element // with frequency 'k' if (max == Integer.MIN_VALUE) System.out.println("No such element"); // print the largest element // with frequency 'k' else System.out.println(max); } // Driver code public static void main(String []args) { int arr[] = { 1, 1, 2, 3, 3, 4, 5, 5, 6, 6, 6 }; int k = 4; int n = arr.length; // find the largest element // that is repeated K times solve(arr, n, k); }} // This code is contributed by Rituraj Jain # Python implementation of above approachimport sys # Function that finds the largest# element that occurs exactly 'k' timesdef solve(arr, n, k): # store the frequency # of each element m = {}; for i in range(0, n - 1): if(arr[i] in m.keys()): m[arr[i]] += 1; else: m[arr[i]] = 1; i += 1; # to store the maximum element max = sys.maxsize; for i in range(0, n - 1): # if current element has frequency 'k' # and current maximum hasn't been set if (m[arr[i]] == k and max == sys.maxsize): # set the current maximum max = arr[i]; # if current element has # frequency 'k' and it is # greater than the current maximum elif (m[arr[i]] == k and max < arr[i]): # change the current maximum max = arr[i]; i += 1 # if there is no element # with frequency 'k' if (max == sys.maxsize): print("No such element"); # print the largest element # with frequency 'k' else: print(max); # Driver codearr = [ 1, 1, 2, 3, 3, 4, 5, 5, 6, 6, 6 ]k = 4;n = len(arr) # find the largest element# that is repeated K timessolve(arr, n, k) # This code is contributed# by Shivi_Aggarwal // C# Implementation of the above approachusing System;using System.Collections.Generic; class GfG{ // Function that finds the largest // element that occurs exactly 'k' times static void solve(int []arr, int n, int k) { // store the frequency of each element Dictionary<int,int> m = new Dictionary<int,int>(); for (int i = 0 ; i < n; i++) { if(m.ContainsKey(arr[i])) { var val = m[arr[i]]; m.Remove(arr[i]); m.Add(arr[i], val + 1); } else { m.Add(arr[i], 1); } } // to store the maximum element int max = int.MinValue; for (int i = 0; i < n; i++) { // If current element has frequency 'k' // and current maximum hasn't been set if (m[arr[i]] == k && max ==int.MinValue) { // set the current maximum max = arr[i]; } // if current element has // frequency 'k' and it is // greater than the current maximum else if (m[arr[i]] == k && max < arr[i]) { // change the current maximum max = arr[i]; } } // if there is no element // with frequency 'k' if (max == int.MinValue) Console.WriteLine("No such element"); // print the largest element // with frequency 'k' else Console.WriteLine(max); } // Driver code public static void Main(String []args) { int []arr = { 1, 1, 2, 3, 3, 4, 5, 5, 6, 6, 6 }; int k = 4; int n = arr.Length; // find the largest element // that is repeated K times solve(arr, n, k); }} // This code contributed by Rajput-Ji <script> // Javascript implementation of above approach // Function that finds the largest// element that occurs exactly 'k' timesfunction solve(arr, n, k){ // store the frequency // of each element var m = new Map(); for (var i = 0; i < n; i++) { m.set(arr[i], m.get(arr[i])+1); } // to store the maximum element var max = -1000000000; for (var i = 0; i < n; i++) { // if current element has frequency 'k' // and current maximum hasn't been set if (m.get(arr[i]) == k && max == -1000000000) { // set the current maximum max = arr[i]; } // if current element has // frequency 'k' and it is // greater than the current maximum else if (m.get(arr[i]) == k && max < arr[i]) { // change the current maximum max = arr[i]; } } // if there is no element // with frequency 'k' if (max == -1000000000) document.write( "No such element"); // print the largest element // with frequency 'k' else document.write( max);} // Driver codevar arr = [ 1, 1, 2, 3, 3, 4, 5, 5, 6, 6, 6 ];var k = 4;var n = arr.length;// find the largest element// that is repeated K timessolve(arr, n, k); </script> No such element Time Complexity: O(N) Shivi_Aggarwal ankthon Sach_Code ukasp rituraj_jain Akanksha_Rai Rajput-Ji itsok rutvik_56 cpp-unordered_map Arrays Competitive Programming Hash Searching Sorting Arrays Searching Hash Sorting Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Introduction to Data Structures Window Sliding Technique Search, insert and delete in an unsorted array What is Data Structure: Types, Classifications and Applications Chocolate Distribution Problem Competitive Programming - A Complete Guide Practice for cracking any coding interview Arrow operator -> in C/C++ with Examples Modulo 10^9+7 (1000000007) Prefix Sum Array - Implementation and Applications in Competitive Programming
[ { "code": null, "e": 52, "s": 24, "text": "\n11 May, 2021" }, { "code": null, "e": 201, "s": 52, "text": "Given an array of integers and an integer ‘k’, the task is to find the largest element from the array that is repeated exactly ‘k’ times.Examples: " }, { "code": null, "e": 493, "s": 201, "text": "Input: arr = {1, 1, 2, 3, 3, 4, 5, 5, 6, 6, 6}, k = 2\nOutput: 5\nThe elements that exactly occur 2 times are 1, 3 and 5\nAnd, the largest element among them is 5.\n\nInput: arr = {1, 2, 3, 4, 5, 6}, k = 2\nOutput: No such element\nThere isn't any element in the array \nthat occurs exactly 2 times." }, { "code": null, "e": 516, "s": 495, "text": "A simple approach: " }, { "code": null, "e": 532, "s": 516, "text": "Sort the array." }, { "code": null, "e": 743, "s": 532, "text": "Start traversing the array from the end (as we’re interested in the largest element that satisfies the condition) and count the frequencies of each element by comparing the element with it’s neighbour elements." }, { "code": null, "e": 821, "s": 743, "text": "The first element from the right that occurs exactly ‘k’ times is the answer." }, { "code": null, "e": 904, "s": 821, "text": "If no element is found that occurs exactly ‘k’ times then print ‘No such element’." }, { "code": null, "e": 957, "s": 904, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 961, "s": 957, "text": "C++" }, { "code": null, "e": 966, "s": 961, "text": "Java" }, { "code": null, "e": 975, "s": 966, "text": "Python 3" }, { "code": null, "e": 978, "s": 975, "text": "C#" }, { "code": null, "e": 982, "s": 978, "text": "PHP" }, { "code": null, "e": 993, "s": 982, "text": "Javascript" }, { "code": "// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Function that finds the largest// element which is repeated 'k' timesvoid solve(int arr[], int n, int k){ // sort the array sort(arr, arr + n); // if the value of 'k' is 1 and the // largest appears only once in the array if (k == 1 && arr[n - 2] != arr[n - 1]) { cout << arr[n - 1] << endl; return; } // counter to count // the repeated elements int count = 1; for (int i = n - 2; i >= 0; i--) { // check if the element at index 'i' // is equal to the element at index 'i+1' // then increase the count if (arr[i] == arr[i + 1]) count++; // else set the count to 1 // to start counting the frequency // of the new number else count = 1; // if the count is equal to k // and the previous element // is not equal to this element if (count == k && (i == 0 || (arr[i - 1] != arr[i]))) { cout << arr[i] << endl; return; } } // if there is no such element cout << \"No such element\" << endl;} // Driver codeint main(){ int arr[] = { 1, 1, 2, 3, 3, 4, 5, 5, 6, 6, 6 }; int k = 2; int n = sizeof(arr) / sizeof(int); // find the largest element // that is repeated K times solve(arr, n, k); return 0;}", "e": 2389, "s": 993, "text": null }, { "code": "// Java implementation of the above approach import java.util.Arrays ; public class GFG { // Function that finds the largest // element which is repeated 'k' times static void solve(int arr[], int n, int k) { // sort the array Arrays.sort(arr); // if the value of 'k' is 1 and the // largest appears only once in the array if (k == 1 && arr[n - 2] != arr[n - 1]) { System.out.println(arr[n - 1]); return; } // counter to count // the repeated elements int count = 1; for (int i = n - 2; i >= 0; i--) { // check if the element at index 'i' // is equal to the element at index 'i+1' // then increase the count if (arr[i] == arr[i + 1]) count++; // else set the count to 1 // to start counting the frequency // of the new number else count = 1; // if the count is equal to k // and the previous element // is not equal to this element if (count == k && (i == 0 || (arr[i - 1] != arr[i]))) { System.out.println(arr[i]); return; } } // if there is no such element System.out.println(\"No such element\"); } // Driver code public static void main(String args[]) { int arr[] = { 1, 1, 2, 3, 3, 4, 5, 5, 6, 6, 6 }; int k = 2; int n = arr.length; // find the largest element // that is repeated K times solve(arr, n, k); } // This code is contributed by ANKITRAI1}", "e": 4143, "s": 2389, "text": null }, { "code": "# Python 3 implementation of the approach # Function that finds the largest# element which is repeated 'k' timesdef solve(arr, n, k): # sort the array arr.sort() # if the value of 'k' is 1 and the # largest appears only once in the array if (k == 1 and arr[n - 2] != arr[n - 1]): print( arr[n - 1] ) return # counter to count # the repeated elements count = 1 for i in range(n - 2, -1, -1) : # check if the element at index 'i' # is equal to the element at index 'i+1' # then increase the count if (arr[i] == arr[i + 1]): count += 1 # else set the count to 1 # to start counting the frequency # of the new number else: count = 1 # if the count is equal to k # and the previous element # is not equal to this element if (count == k and (i == 0 or (arr[i - 1] != arr[i]))): print(arr[i]) return # if there is no such element print(\"No such element\") # Driver codeif __name__ == \"__main__\": arr = [ 1, 1, 2, 3, 3, 4, 5, 5, 6, 6, 6 ] k = 2 n = len(arr) # find the largest element # that is repeated K times solve(arr, n, k) # This code is contributed# by ChitraNayal", "e": 5434, "s": 4143, "text": null }, { "code": "// C# implementation of the above approachusing System; class GFG{// Function that finds the largest// element which is repeated 'k' timesstatic void solve(int []arr, int n, int k){ // sort the array Array.Sort(arr); // if the value of 'k' is 1 and the // largest appears only once in the array if (k == 1 && arr[n - 2] != arr[n - 1]) { Console.WriteLine(arr[n - 1]); return; } // counter to count // the repeated elements int count = 1; for (int i = n - 2; i >= 0; i--) { // check if the element at index 'i' // is equal to the element at index 'i+1' // then increase the count if (arr[i] == arr[i + 1]) count++; // else set the count to 1 // to start counting the frequency // of the new number else count = 1; // if the count is equal to k // and the previous element // is not equal to this element if (count == k && (i == 0 || (arr[i - 1] != arr[i]))) { Console.WriteLine(arr[i]); return; } } // if there is no such element Console.WriteLine(\"No such element\");} // Driver codestatic public void Main (){ int []arr = { 1, 1, 2, 3, 3, 4, 5, 5, 6, 6, 6 }; int k = 2; int n = arr.Length; // find the largest element // that is repeated K times solve(arr, n, k);}} // This code is contributed// by Sach_Code", "e": 6929, "s": 5434, "text": null }, { "code": "<?php// PHP implementation of the approach // Function that finds the largest// element which is repeated 'k' timesfunction solve(&$arr, $n, $k){ // sort the array sort($arr); // if the value of 'k' is 1 and the // largest appears only once in the array if ($k == 1 && $arr[$n - 2] != $arr[$n - 1]) { echo $arr[$n - 1] ; echo (\"\\n\"); return; } // counter to count // the repeated elements $count = 1; for ($i = $n - 2; $i >= 0; $i--) { // check if the element at index 'i' // is equal to the element at index 'i+1' // then increase the count if ($arr[$i] == $arr[$i + 1]) $count++; // else set the count to 1 // to start counting the frequency // of the new number else $count = 1; // if the count is equal to k // and the previous element // is not equal to this element if ($count == $k && ($i == 0 || ($arr[$i - 1] != $arr[$i]))) { echo ($arr[$i]); echo (\"\\n\"); return; } } // if there is no such element echo (\"No such element\"); echo (\"\\n\");} // Driver code$arr = array(1, 1, 2, 3, 3, 4, 5, 5, 6, 6, 6 );$k = 2;$n = sizeof($arr); // find the largest element// that is repeated K timessolve($arr, $n, $k); // This code is contributed// by Shivi_Aggarwal?>", "e": 8340, "s": 6929, "text": null }, { "code": "<script> // Javascript implementation of the approach // Function that finds the largest// element which is repeated 'k' timesfunction solve(arr, n, k){ // sort the array arr.sort((a,b)=> a-b) // if the value of 'k' is 1 and the // largest appears only once in the array if (k == 1 && arr[n - 2] != arr[n - 1]) { cout << arr[n - 1] << endl; return; } // counter to count // the repeated elements var count = 1; for (var i = n - 2; i >= 0; i--) { // check if the element at index 'i' // is equal to the element at index 'i+1' // then increase the count if (arr[i] == arr[i + 1]) count++; // else set the count to 1 // to start counting the frequency // of the new number else count = 1; // if the count is equal to k // and the previous element // is not equal to this element if (count == k && (i == 0 || (arr[i - 1] != arr[i]))) { document.write( arr[i] + \"<br>\"); return; } } // if there is no such element document.write( \"No such element\" );} // Driver codevar arr = [ 1, 1, 2, 3, 3, 4, 5, 5, 6, 6, 6 ];var k = 2;var n = arr.length;// find the largest element// that is repeated K timessolve(arr, n, k); </script>", "e": 9654, "s": 8340, "text": null }, { "code": null, "e": 9656, "s": 9654, "text": "5" }, { "code": null, "e": 9708, "s": 9658, "text": "Time Complexity: O(N*log(N))Efficient approach: " }, { "code": null, "e": 9773, "s": 9708, "text": "Create a map and store the frequency of each element in the map." }, { "code": null, "e": 9864, "s": 9773, "text": "Then, traverse the array and find out the largest element that has frequency equal to ‘k’." }, { "code": null, "e": 9891, "s": 9864, "text": "If found, print the number" }, { "code": null, "e": 9922, "s": 9891, "text": "Else, print ‘No such element’." }, { "code": null, "e": 9975, "s": 9922, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 9979, "s": 9975, "text": "C++" }, { "code": null, "e": 9984, "s": 9979, "text": "Java" }, { "code": null, "e": 9992, "s": 9984, "text": "Python3" }, { "code": null, "e": 9995, "s": 9992, "text": "C#" }, { "code": null, "e": 10006, "s": 9995, "text": "Javascript" }, { "code": "// C++ implementation of above approach#include <bits/stdc++.h>using namespace std; // Function that finds the largest// element that occurs exactly 'k' timesvoid solve(int arr[], int n, int k){ // store the frequency // of each element unordered_map<int, int> m; for (int i = 0; i < n; i++) { m[arr[i]]++; } // to store the maximum element int max = INT_MIN; for (int i = 0; i < n; i++) { // if current element has frequency 'k' // and current maximum hasn't been set if (m[arr[i]] == k && max == INT_MIN) { // set the current maximum max = arr[i]; } // if current element has // frequency 'k' and it is // greater than the current maximum else if (m[arr[i]] == k && max < arr[i]) { // change the current maximum max = arr[i]; } } // if there is no element // with frequency 'k' if (max == INT_MIN) cout << \"No such element\" << endl; // print the largest element // with frequency 'k' else cout << max << endl;} // Driver codeint main(){ int arr[] = { 1, 1, 2, 3, 3, 4, 5, 5, 6, 6, 6 }; int k = 4; int n = sizeof(arr) / sizeof(int); // find the largest element // that is repeated K times solve(arr, n, k); return 0;}", "e": 11329, "s": 10006, "text": null }, { "code": "// Java implementation of above approachimport java.util.HashMap;import java.util.Map; class GfG{ // Function that finds the largest // element that occurs exactly 'k' times static void solve(int arr[], int n, int k) { // store the frequency of each element HashMap<Integer, Integer> m = new HashMap<>(); for (int i = 0; i < n; i++) { if (!m.containsKey(arr[i])) m.put(arr[i], 0); m.put(arr[i], m.get(arr[i]) + 1); } // to store the maximum element int max = Integer.MIN_VALUE; for (int i = 0; i < n; i++) { // If current element has frequency 'k' // and current maximum hasn't been set if (m.get(arr[i]) == k && max == Integer.MIN_VALUE) { // set the current maximum max = arr[i]; } // if current element has // frequency 'k' and it is // greater than the current maximum else if (m.get(arr[i]) == k && max < arr[i]) { // change the current maximum max = arr[i]; } } // if there is no element // with frequency 'k' if (max == Integer.MIN_VALUE) System.out.println(\"No such element\"); // print the largest element // with frequency 'k' else System.out.println(max); } // Driver code public static void main(String []args) { int arr[] = { 1, 1, 2, 3, 3, 4, 5, 5, 6, 6, 6 }; int k = 4; int n = arr.length; // find the largest element // that is repeated K times solve(arr, n, k); }} // This code is contributed by Rituraj Jain", "e": 13131, "s": 11329, "text": null }, { "code": "# Python implementation of above approachimport sys # Function that finds the largest# element that occurs exactly 'k' timesdef solve(arr, n, k): # store the frequency # of each element m = {}; for i in range(0, n - 1): if(arr[i] in m.keys()): m[arr[i]] += 1; else: m[arr[i]] = 1; i += 1; # to store the maximum element max = sys.maxsize; for i in range(0, n - 1): # if current element has frequency 'k' # and current maximum hasn't been set if (m[arr[i]] == k and max == sys.maxsize): # set the current maximum max = arr[i]; # if current element has # frequency 'k' and it is # greater than the current maximum elif (m[arr[i]] == k and max < arr[i]): # change the current maximum max = arr[i]; i += 1 # if there is no element # with frequency 'k' if (max == sys.maxsize): print(\"No such element\"); # print the largest element # with frequency 'k' else: print(max); # Driver codearr = [ 1, 1, 2, 3, 3, 4, 5, 5, 6, 6, 6 ]k = 4;n = len(arr) # find the largest element# that is repeated K timessolve(arr, n, k) # This code is contributed# by Shivi_Aggarwal", "e": 14436, "s": 13131, "text": null }, { "code": "// C# Implementation of the above approachusing System;using System.Collections.Generic; class GfG{ // Function that finds the largest // element that occurs exactly 'k' times static void solve(int []arr, int n, int k) { // store the frequency of each element Dictionary<int,int> m = new Dictionary<int,int>(); for (int i = 0 ; i < n; i++) { if(m.ContainsKey(arr[i])) { var val = m[arr[i]]; m.Remove(arr[i]); m.Add(arr[i], val + 1); } else { m.Add(arr[i], 1); } } // to store the maximum element int max = int.MinValue; for (int i = 0; i < n; i++) { // If current element has frequency 'k' // and current maximum hasn't been set if (m[arr[i]] == k && max ==int.MinValue) { // set the current maximum max = arr[i]; } // if current element has // frequency 'k' and it is // greater than the current maximum else if (m[arr[i]] == k && max < arr[i]) { // change the current maximum max = arr[i]; } } // if there is no element // with frequency 'k' if (max == int.MinValue) Console.WriteLine(\"No such element\"); // print the largest element // with frequency 'k' else Console.WriteLine(max); } // Driver code public static void Main(String []args) { int []arr = { 1, 1, 2, 3, 3, 4, 5, 5, 6, 6, 6 }; int k = 4; int n = arr.Length; // find the largest element // that is repeated K times solve(arr, n, k); }} // This code contributed by Rajput-Ji", "e": 16342, "s": 14436, "text": null }, { "code": "<script> // Javascript implementation of above approach // Function that finds the largest// element that occurs exactly 'k' timesfunction solve(arr, n, k){ // store the frequency // of each element var m = new Map(); for (var i = 0; i < n; i++) { m.set(arr[i], m.get(arr[i])+1); } // to store the maximum element var max = -1000000000; for (var i = 0; i < n; i++) { // if current element has frequency 'k' // and current maximum hasn't been set if (m.get(arr[i]) == k && max == -1000000000) { // set the current maximum max = arr[i]; } // if current element has // frequency 'k' and it is // greater than the current maximum else if (m.get(arr[i]) == k && max < arr[i]) { // change the current maximum max = arr[i]; } } // if there is no element // with frequency 'k' if (max == -1000000000) document.write( \"No such element\"); // print the largest element // with frequency 'k' else document.write( max);} // Driver codevar arr = [ 1, 1, 2, 3, 3, 4, 5, 5, 6, 6, 6 ];var k = 4;var n = arr.length;// find the largest element// that is repeated K timessolve(arr, n, k); </script>", "e": 17602, "s": 16342, "text": null }, { "code": null, "e": 17618, "s": 17602, "text": "No such element" }, { "code": null, "e": 17643, "s": 17620, "text": "Time Complexity: O(N) " }, { "code": null, "e": 17658, "s": 17643, "text": "Shivi_Aggarwal" }, { "code": null, "e": 17666, "s": 17658, "text": "ankthon" }, { "code": null, "e": 17676, "s": 17666, "text": "Sach_Code" }, { "code": null, "e": 17682, "s": 17676, "text": "ukasp" }, { "code": null, "e": 17695, "s": 17682, "text": "rituraj_jain" }, { "code": null, "e": 17708, "s": 17695, "text": "Akanksha_Rai" }, { "code": null, "e": 17718, "s": 17708, "text": "Rajput-Ji" }, { "code": null, "e": 17724, "s": 17718, "text": "itsok" }, { "code": null, "e": 17734, "s": 17724, "text": "rutvik_56" }, { "code": null, "e": 17752, "s": 17734, "text": "cpp-unordered_map" }, { "code": null, "e": 17759, "s": 17752, "text": "Arrays" }, { "code": null, "e": 17783, "s": 17759, "text": "Competitive Programming" }, { "code": null, "e": 17788, "s": 17783, "text": "Hash" }, { "code": null, "e": 17798, "s": 17788, "text": "Searching" }, { "code": null, "e": 17806, "s": 17798, "text": "Sorting" }, { "code": null, "e": 17813, "s": 17806, "text": "Arrays" }, { "code": null, "e": 17823, "s": 17813, "text": "Searching" }, { "code": null, "e": 17828, "s": 17823, "text": "Hash" }, { "code": null, "e": 17836, "s": 17828, "text": "Sorting" }, { "code": null, "e": 17934, "s": 17836, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 17966, "s": 17934, "text": "Introduction to Data Structures" }, { "code": null, "e": 17991, "s": 17966, "text": "Window Sliding Technique" }, { "code": null, "e": 18038, "s": 17991, "text": "Search, insert and delete in an unsorted array" }, { "code": null, "e": 18102, "s": 18038, "text": "What is Data Structure: Types, Classifications and Applications" }, { "code": null, "e": 18133, "s": 18102, "text": "Chocolate Distribution Problem" }, { "code": null, "e": 18176, "s": 18133, "text": "Competitive Programming - A Complete Guide" }, { "code": null, "e": 18219, "s": 18176, "text": "Practice for cracking any coding interview" }, { "code": null, "e": 18260, "s": 18219, "text": "Arrow operator -> in C/C++ with Examples" }, { "code": null, "e": 18287, "s": 18260, "text": "Modulo 10^9+7 (1000000007)" } ]
Spot the difference between two images using Python
24 Feb, 2021 In this article, we will discuss how to spot differences between two given images using python. In order to perform this task, we will be using the ImageChops.difference() method in Pillow module. Syntax: ImageChops.difference(image1, image2) Parameters: image1 first image image2 second image Return Value: It returns an Image. Step 1: So, today we will be building this magical tool using python and that too with only 8 lines of code. But, before that, we have to install the pillow package of python using this command pip install pillow Step 2: Now, after installing this we have to get two images. Make sure that these two images are in the same folder where you’ve kept this python program or else you’ve to provide the path of these images. Step 3: Call the ImageChops.difference() method with the two images as parameters. Step 4: Generate the difference between the two images using the show() method. Input: Python3 # import modulefrom PIL import Image, ImageChops # assign imagesimg1 = Image.open("1img.jpg")img2 = Image.open("2img.jpg") # finding differencediff = ImageChops.difference(img1, img2) # showing the differencediff.show() Output: Notice that the output image contains mostly black parts, but some portions of this image are colored. Those colored portions are the spotted differences between the two input images. In this case, the output image shows a total of 6 major differences. Python-pil 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": 28, "s": 0, "text": "\n24 Feb, 2021" }, { "code": null, "e": 225, "s": 28, "text": "In this article, we will discuss how to spot differences between two given images using python. In order to perform this task, we will be using the ImageChops.difference() method in Pillow module." }, { "code": null, "e": 271, "s": 225, "text": "Syntax: ImageChops.difference(image1, image2)" }, { "code": null, "e": 283, "s": 271, "text": "Parameters:" }, { "code": null, "e": 302, "s": 283, "text": "image1 first image" }, { "code": null, "e": 322, "s": 302, "text": "image2 second image" }, { "code": null, "e": 357, "s": 322, "text": "Return Value: It returns an Image." }, { "code": null, "e": 551, "s": 357, "text": "Step 1: So, today we will be building this magical tool using python and that too with only 8 lines of code. But, before that, we have to install the pillow package of python using this command" }, { "code": null, "e": 570, "s": 551, "text": "pip install pillow" }, { "code": null, "e": 777, "s": 570, "text": "Step 2: Now, after installing this we have to get two images. Make sure that these two images are in the same folder where you’ve kept this python program or else you’ve to provide the path of these images." }, { "code": null, "e": 860, "s": 777, "text": "Step 3: Call the ImageChops.difference() method with the two images as parameters." }, { "code": null, "e": 940, "s": 860, "text": "Step 4: Generate the difference between the two images using the show() method." }, { "code": null, "e": 947, "s": 940, "text": "Input:" }, { "code": null, "e": 955, "s": 947, "text": "Python3" }, { "code": "# import modulefrom PIL import Image, ImageChops # assign imagesimg1 = Image.open(\"1img.jpg\")img2 = Image.open(\"2img.jpg\") # finding differencediff = ImageChops.difference(img1, img2) # showing the differencediff.show()", "e": 1178, "s": 955, "text": null }, { "code": null, "e": 1186, "s": 1178, "text": "Output:" }, { "code": null, "e": 1440, "s": 1186, "text": "Notice that the output image contains mostly black parts, but some portions of this image are colored. Those colored portions are the spotted differences between the two input images. In this case, the output image shows a total of 6 major differences. " }, { "code": null, "e": 1451, "s": 1440, "text": "Python-pil" }, { "code": null, "e": 1475, "s": 1451, "text": "Technical Scripter 2020" }, { "code": null, "e": 1482, "s": 1475, "text": "Python" }, { "code": null, "e": 1501, "s": 1482, "text": "Technical Scripter" } ]
Split the array into equal sum parts according to given conditions
03 Aug, 2021 Given an integer array arr[], the task is to check if the input array can be split in two sub-arrays such that: Sum of both the sub-arrays is equal. All the elements which are divisible by 5 should be in the same group. All the elements which are divisible by 3 (but not divisible by 5) should be in the other group. Elements which are neither divisible by 5 nor by 3 can be put in any group. If possible then print Yes else print No.Examples: Input: arr[] = {1, 2} Output: No The elements cannot be divided in groups such that there sum is equal.Input: arr[] = {1, 4, 3} Output: Yes {1, 3} and {4} are the groups satisfying the given condition. Approach: We can use a recursive approach by keeping left sum and right sum to maintain two different groups. Left sum is for multiples of 5 and right sum is for multiples of 3 (which are not multiples of 5) and the elements which are neither divisible by 5 nor by 3 can lie in any group satisfying the equal sum rule (include them in left sum and right sum one by one).Below is the implementation of the above approach: C++ Java Python3 C# PHP Javascript // C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Recursive function that returns true if the array// can be divided into two sub-arrays// satisfying the given conditionbool helper(int* arr, int n, int start, int lsum, int rsum){ // If reached the end if (start == n) return lsum == rsum; // If divisible by 5 then add to the left sum if (arr[start] % 5 == 0) lsum += arr[start]; // If divisible by 3 but not by 5 // then add to the right sum else if (arr[start] % 3 == 0) rsum += arr[start]; // Else it can be added to any of the sub-arrays else // Try adding in both the sub-arrays (one by one) // and check whether the condition satisfies return helper(arr, n, start + 1, lsum + arr[start], rsum) || helper(arr, n, start + 1, lsum, rsum + arr[start]); // For cases when element is multiple of 3 or 5. return helper(arr, n, start + 1, lsum, rsum);} // Function to start the recursive callsbool splitArray(int* arr, int n){ // Initially start, lsum and rsum will all be 0 return helper(arr, n, 0, 0, 0);} // Driver codeint main(){ int arr[] = { 1, 4, 3 }; int n = sizeof(arr) / sizeof(arr[0]); if (splitArray(arr, n)) cout << "Yes"; else cout << "No"; return 0;} // Java implementation of the approachclass Solution{ // Recursive function that returns true if the array// can be divided into two sub-arrays// satisfying the given conditionstatic boolean helper(int arr[], int n, int start, int lsum, int rsum){ // If reached the end if (start == n) return lsum == rsum; // If divisible by 5 then add to the left sum if (arr[start] % 5 == 0) lsum += arr[start]; // If divisible by 3 but not by 5 // then add to the right sum else if (arr[start] % 3 == 0) rsum += arr[start]; // Else it can be added to any of the sub-arrays else // Try adding in both the sub-arrays (one by one) // and check whether the condition satisfies return helper(arr, n, start + 1, lsum + arr[start], rsum) || helper(arr, n, start + 1, lsum, rsum + arr[start]); // For cases when element is multiple of 3 or 5. return helper(arr, n, start + 1, lsum, rsum);} // Function to start the recursive callsstatic boolean splitArray(int arr[], int n){ // Initially start, lsum and rsum will all be 0 return helper(arr, n, 0, 0, 0);} // Driver codepublic static void main(String args[]){ int arr[] = { 1, 4, 3 }; int n = arr.length; if (splitArray(arr, n)) System.out.println( "Yes"); else System.out.println( "No");}} // This code is contributed by Arnab Kundu # Python 3 implementation of the approach # Recursive function that returns true if# the array can be divided into two sub-arrays# satisfying the given conditiondef helper(arr, n, start, lsum, rsum): # If reached the end if (start == n): return lsum == rsum # If divisible by 5 then add # to the left sum if (arr[start] % 5 == 0): lsum += arr[start] # If divisible by 3 but not by 5 # then add to the right sum elif (arr[start] % 3 == 0): rsum += arr[start] # Else it can be added to any of # the sub-arrays else: # Try adding in both the sub-arrays # (one by one) and check whether # the condition satisfies return (helper(arr, n, start + 1, lsum + arr[start], rsum) or helper(arr, n, start + 1, lsum, rsum + arr[start])); # For cases when element is multiple of 3 or 5. return helper(arr, n, start + 1, lsum, rsum) # Function to start the recursive callsdef splitArray(arr, n): # Initially start, lsum and rsum # will all be 0 return helper(arr, n, 0, 0, 0) # Driver codeif __name__ == "__main__": arr = [ 1, 4, 3 ] n = len(arr) if (splitArray(arr, n)): print("Yes") else: print("No") # This code is contributed by ita_c // C# implementation of the approachusing System; class GFG{ // Recursive function that returns true if the array // can be divided into two sub-arrays // satisfying the given condition static bool helper(int []arr, int n, int start, int lsum, int rsum) { // If reached the end if (start == n) return lsum == rsum; // If divisible by 5 then add to the left sum if (arr[start] % 5 == 0) lsum += arr[start]; // If divisible by 3 but not by 5 // then add to the right sum else if (arr[start] % 3 == 0) rsum += arr[start]; // Else it can be added to any of the sub-arrays else // Try adding in both the sub-arrays (one by one) // and check whether the condition satisfies return helper(arr, n, start + 1, lsum + arr[start], rsum) || helper(arr, n, start + 1, lsum, rsum + arr[start]); // For cases when element is multiple of 3 or 5. return helper(arr, n, start + 1, lsum, rsum); } // Function to start the recursive calls static bool splitArray(int []arr, int n) { // Initially start, lsum and rsum will all be 0 return helper(arr, n, 0, 0, 0); } // Driver code public static void Main() { int []arr = { 1, 4, 3 }; int n = arr.Length; if (splitArray(arr, n)) Console.WriteLine( "Yes"); else Console.WriteLine( "No"); }} // This code is contributed by Ryuga <?php// PHP implementation of the approach // Recursive function that returns true// if the array can be divided into two// sub-arrays satisfying the given conditionfunction helper(&$arr, $n, $start, $lsum, $rsum){ // If reached the end if ($start == $n) return $lsum == $rsum; // If divisible by 5 then // add to the left sum if ($arr[$start] % 5 == 0) $lsum += $arr[$start]; // If divisible by 3 but not by 5 // then add to the right sum else if ($arr[$start] % 3 == 0) $rsum += $arr[$start]; // Else it can be added to any // of the sub-arrays else // Try adding in both the sub-arrays (one by one) // and check whether the condition satisfies return helper($arr, $n, $start + 1, $lsum + $arr[$start], $rsum) || helper($arr, $n, $start + 1, $lsum, $rsum + $arr[$start]); // For cases when element is // multiple of 3 or 5. return helper($arr, $n, $start + 1, $lsum, $rsum);} // Function to start the recursive callsfunction splitArray($arr, $n){ // Initially start, lsum and r // sum will all be 0 return helper($arr, $n, 0, 0, 0);} // Driver code$arr = array( 1, 4, 3 );$n = count($arr); if (splitArray($arr, $n)) print("Yes");else print("No"); // This code is contributed by mits?> <script> //js implementation of the approach // Recursive function that returns true if the array// can be divided into two sub-arrays// satisfying the given conditionfunction helper( arr, n, start, lsum, rsum){ // If reached the end if (start == n) return lsum == rsum; // If divisible by 5 then add to the left sum if (arr[start] % 5 == 0) lsum += arr[start]; // If divisible by 3 but not by 5 // then add to the right sum else if (arr[start] % 3 == 0) rsum += arr[start]; // Else it can be added to any of the sub-arrays else // Try adding in both the sub-arrays (one by one) // and check whether the condition satisfies return helper(arr, n, start + 1, lsum + arr[start], rsum) || helper(arr, n, start + 1, lsum, rsum + arr[start]); // For cases when element is multiple of 3 or 5. return helper(arr, n, start + 1, lsum, rsum);} // Function to start the recursive callsfunction splitArray(arr, n){ // Initially start, lsum and rsum will all be 0 return helper(arr, n, 0, 0, 0);} // Driver codelet arr = [1, 4, 3 ];let n =arr.length;if (splitArray(arr, n)) document.write( "Yes");else document.write( "No"); </script> Yes Time Complexity: O(2 ^ N)Auxiliary Space: O(N) andrew1234 ankthon ukasp Mithun Kumar rohan07 pankajsharmagfg subset Algorithms Arrays Recursion Arrays Recursion subset Algorithms Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n03 Aug, 2021" }, { "code": null, "e": 168, "s": 54, "text": "Given an integer array arr[], the task is to check if the input array can be split in two sub-arrays such that: " }, { "code": null, "e": 205, "s": 168, "text": "Sum of both the sub-arrays is equal." }, { "code": null, "e": 276, "s": 205, "text": "All the elements which are divisible by 5 should be in the same group." }, { "code": null, "e": 373, "s": 276, "text": "All the elements which are divisible by 3 (but not divisible by 5) should be in the other group." }, { "code": null, "e": 449, "s": 373, "text": "Elements which are neither divisible by 5 nor by 3 can be put in any group." }, { "code": null, "e": 502, "s": 449, "text": "If possible then print Yes else print No.Examples: " }, { "code": null, "e": 706, "s": 502, "text": "Input: arr[] = {1, 2} Output: No The elements cannot be divided in groups such that there sum is equal.Input: arr[] = {1, 4, 3} Output: Yes {1, 3} and {4} are the groups satisfying the given condition. " }, { "code": null, "e": 1131, "s": 708, "text": "Approach: We can use a recursive approach by keeping left sum and right sum to maintain two different groups. Left sum is for multiples of 5 and right sum is for multiples of 3 (which are not multiples of 5) and the elements which are neither divisible by 5 nor by 3 can lie in any group satisfying the equal sum rule (include them in left sum and right sum one by one).Below is the implementation of the above approach: " }, { "code": null, "e": 1135, "s": 1131, "text": "C++" }, { "code": null, "e": 1140, "s": 1135, "text": "Java" }, { "code": null, "e": 1148, "s": 1140, "text": "Python3" }, { "code": null, "e": 1151, "s": 1148, "text": "C#" }, { "code": null, "e": 1155, "s": 1151, "text": "PHP" }, { "code": null, "e": 1166, "s": 1155, "text": "Javascript" }, { "code": "// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Recursive function that returns true if the array// can be divided into two sub-arrays// satisfying the given conditionbool helper(int* arr, int n, int start, int lsum, int rsum){ // If reached the end if (start == n) return lsum == rsum; // If divisible by 5 then add to the left sum if (arr[start] % 5 == 0) lsum += arr[start]; // If divisible by 3 but not by 5 // then add to the right sum else if (arr[start] % 3 == 0) rsum += arr[start]; // Else it can be added to any of the sub-arrays else // Try adding in both the sub-arrays (one by one) // and check whether the condition satisfies return helper(arr, n, start + 1, lsum + arr[start], rsum) || helper(arr, n, start + 1, lsum, rsum + arr[start]); // For cases when element is multiple of 3 or 5. return helper(arr, n, start + 1, lsum, rsum);} // Function to start the recursive callsbool splitArray(int* arr, int n){ // Initially start, lsum and rsum will all be 0 return helper(arr, n, 0, 0, 0);} // Driver codeint main(){ int arr[] = { 1, 4, 3 }; int n = sizeof(arr) / sizeof(arr[0]); if (splitArray(arr, n)) cout << \"Yes\"; else cout << \"No\"; return 0;}", "e": 2493, "s": 1166, "text": null }, { "code": "// Java implementation of the approachclass Solution{ // Recursive function that returns true if the array// can be divided into two sub-arrays// satisfying the given conditionstatic boolean helper(int arr[], int n, int start, int lsum, int rsum){ // If reached the end if (start == n) return lsum == rsum; // If divisible by 5 then add to the left sum if (arr[start] % 5 == 0) lsum += arr[start]; // If divisible by 3 but not by 5 // then add to the right sum else if (arr[start] % 3 == 0) rsum += arr[start]; // Else it can be added to any of the sub-arrays else // Try adding in both the sub-arrays (one by one) // and check whether the condition satisfies return helper(arr, n, start + 1, lsum + arr[start], rsum) || helper(arr, n, start + 1, lsum, rsum + arr[start]); // For cases when element is multiple of 3 or 5. return helper(arr, n, start + 1, lsum, rsum);} // Function to start the recursive callsstatic boolean splitArray(int arr[], int n){ // Initially start, lsum and rsum will all be 0 return helper(arr, n, 0, 0, 0);} // Driver codepublic static void main(String args[]){ int arr[] = { 1, 4, 3 }; int n = arr.length; if (splitArray(arr, n)) System.out.println( \"Yes\"); else System.out.println( \"No\");}} // This code is contributed by Arnab Kundu", "e": 3896, "s": 2493, "text": null }, { "code": "# Python 3 implementation of the approach # Recursive function that returns true if# the array can be divided into two sub-arrays# satisfying the given conditiondef helper(arr, n, start, lsum, rsum): # If reached the end if (start == n): return lsum == rsum # If divisible by 5 then add # to the left sum if (arr[start] % 5 == 0): lsum += arr[start] # If divisible by 3 but not by 5 # then add to the right sum elif (arr[start] % 3 == 0): rsum += arr[start] # Else it can be added to any of # the sub-arrays else: # Try adding in both the sub-arrays # (one by one) and check whether # the condition satisfies return (helper(arr, n, start + 1, lsum + arr[start], rsum) or helper(arr, n, start + 1, lsum, rsum + arr[start])); # For cases when element is multiple of 3 or 5. return helper(arr, n, start + 1, lsum, rsum) # Function to start the recursive callsdef splitArray(arr, n): # Initially start, lsum and rsum # will all be 0 return helper(arr, n, 0, 0, 0) # Driver codeif __name__ == \"__main__\": arr = [ 1, 4, 3 ] n = len(arr) if (splitArray(arr, n)): print(\"Yes\") else: print(\"No\") # This code is contributed by ita_c", "e": 5204, "s": 3896, "text": null }, { "code": "// C# implementation of the approachusing System; class GFG{ // Recursive function that returns true if the array // can be divided into two sub-arrays // satisfying the given condition static bool helper(int []arr, int n, int start, int lsum, int rsum) { // If reached the end if (start == n) return lsum == rsum; // If divisible by 5 then add to the left sum if (arr[start] % 5 == 0) lsum += arr[start]; // If divisible by 3 but not by 5 // then add to the right sum else if (arr[start] % 3 == 0) rsum += arr[start]; // Else it can be added to any of the sub-arrays else // Try adding in both the sub-arrays (one by one) // and check whether the condition satisfies return helper(arr, n, start + 1, lsum + arr[start], rsum) || helper(arr, n, start + 1, lsum, rsum + arr[start]); // For cases when element is multiple of 3 or 5. return helper(arr, n, start + 1, lsum, rsum); } // Function to start the recursive calls static bool splitArray(int []arr, int n) { // Initially start, lsum and rsum will all be 0 return helper(arr, n, 0, 0, 0); } // Driver code public static void Main() { int []arr = { 1, 4, 3 }; int n = arr.Length; if (splitArray(arr, n)) Console.WriteLine( \"Yes\"); else Console.WriteLine( \"No\"); }} // This code is contributed by Ryuga", "e": 6787, "s": 5204, "text": null }, { "code": "<?php// PHP implementation of the approach // Recursive function that returns true// if the array can be divided into two// sub-arrays satisfying the given conditionfunction helper(&$arr, $n, $start, $lsum, $rsum){ // If reached the end if ($start == $n) return $lsum == $rsum; // If divisible by 5 then // add to the left sum if ($arr[$start] % 5 == 0) $lsum += $arr[$start]; // If divisible by 3 but not by 5 // then add to the right sum else if ($arr[$start] % 3 == 0) $rsum += $arr[$start]; // Else it can be added to any // of the sub-arrays else // Try adding in both the sub-arrays (one by one) // and check whether the condition satisfies return helper($arr, $n, $start + 1, $lsum + $arr[$start], $rsum) || helper($arr, $n, $start + 1, $lsum, $rsum + $arr[$start]); // For cases when element is // multiple of 3 or 5. return helper($arr, $n, $start + 1, $lsum, $rsum);} // Function to start the recursive callsfunction splitArray($arr, $n){ // Initially start, lsum and r // sum will all be 0 return helper($arr, $n, 0, 0, 0);} // Driver code$arr = array( 1, 4, 3 );$n = count($arr); if (splitArray($arr, $n)) print(\"Yes\");else print(\"No\"); // This code is contributed by mits?>", "e": 8177, "s": 6787, "text": null }, { "code": "<script> //js implementation of the approach // Recursive function that returns true if the array// can be divided into two sub-arrays// satisfying the given conditionfunction helper( arr, n, start, lsum, rsum){ // If reached the end if (start == n) return lsum == rsum; // If divisible by 5 then add to the left sum if (arr[start] % 5 == 0) lsum += arr[start]; // If divisible by 3 but not by 5 // then add to the right sum else if (arr[start] % 3 == 0) rsum += arr[start]; // Else it can be added to any of the sub-arrays else // Try adding in both the sub-arrays (one by one) // and check whether the condition satisfies return helper(arr, n, start + 1, lsum + arr[start], rsum) || helper(arr, n, start + 1, lsum, rsum + arr[start]); // For cases when element is multiple of 3 or 5. return helper(arr, n, start + 1, lsum, rsum);} // Function to start the recursive callsfunction splitArray(arr, n){ // Initially start, lsum and rsum will all be 0 return helper(arr, n, 0, 0, 0);} // Driver codelet arr = [1, 4, 3 ];let n =arr.length;if (splitArray(arr, n)) document.write( \"Yes\");else document.write( \"No\"); </script>", "e": 9401, "s": 8177, "text": null }, { "code": null, "e": 9405, "s": 9401, "text": "Yes" }, { "code": null, "e": 9454, "s": 9407, "text": "Time Complexity: O(2 ^ N)Auxiliary Space: O(N)" }, { "code": null, "e": 9465, "s": 9454, "text": "andrew1234" }, { "code": null, "e": 9473, "s": 9465, "text": "ankthon" }, { "code": null, "e": 9479, "s": 9473, "text": "ukasp" }, { "code": null, "e": 9492, "s": 9479, "text": "Mithun Kumar" }, { "code": null, "e": 9500, "s": 9492, "text": "rohan07" }, { "code": null, "e": 9516, "s": 9500, "text": "pankajsharmagfg" }, { "code": null, "e": 9523, "s": 9516, "text": "subset" }, { "code": null, "e": 9534, "s": 9523, "text": "Algorithms" }, { "code": null, "e": 9541, "s": 9534, "text": "Arrays" }, { "code": null, "e": 9551, "s": 9541, "text": "Recursion" }, { "code": null, "e": 9558, "s": 9551, "text": "Arrays" }, { "code": null, "e": 9568, "s": 9558, "text": "Recursion" }, { "code": null, "e": 9575, "s": 9568, "text": "subset" }, { "code": null, "e": 9586, "s": 9575, "text": "Algorithms" } ]
React.js (Introduction and Working)
14 Jun, 2022 Introduction to ReactJS: Let us understand this with a practical example. Let’s say one of your friends posted a photograph on Facebook. Now you go and like the image and then you started checking out the comments too. Now while you are browsing over comments you see that the likes count has increased by 100, since you liked the picture, even without reloading the page. This magical count change is because of ReactJS. React is a declarative, efficient, and flexible JavaScript library for building user interfaces. ‘V’ denotes the view in MVC. ReactJS is an open-source, component-based front end library responsible only for the view layer of the application. It is maintained by Facebook.React uses a declarative paradigm that makes it easier to reason about your application and aims to be both efficient and flexible. It designs simple views for each state in your application, and React will efficiently update and render just the right component when your data changes. The declarative view makes your code more predictable and easier to debug.A React application is made of multiple components, each responsible for rendering a small, reusable piece of HTML. Components can be nested within other components to allow complex applications to be built out of simple building blocks. A component may also maintain an internal state – for example, a TabList component may store a variable corresponding to the currently open tab. Note: React is not a framework. It is just a library developed by Facebook to solve some problems that we were facing earlier.Prerequisites: Download Node packages with their latest version. Example: Create a new React project by using the command below: npx create-react-app myapp Filename App.js: Now change the App.js file with the given below code: javascript import React,{ Component } from 'react'; class App extends Component { render() { return ( <div> <h1>Hello, Learner.Welcome to GeeksforGeeks.</h1> </div> ); }} export default App; Output: How does it work: While building client-side apps, a team of Facebook developers realized that the DOM is slow (The Document Object Model (DOM) is an application programming interface (API) for HTML and XML documents. It defines the logical structure of documents and the way a document is accessed and manipulated.). So, to make it faster, React implements a virtual DOM that is basically a DOM tree representation in JavaScript. So when it needs to read or write to the DOM, it will use the virtual representation of it. Then the virtual DOM will try to find the most efficient way to update the browser’s DOM.Unlike browser DOM elements, React elements are plain objects and are cheap to create. React DOM takes care of updating the DOM to match the React elements. The reason for this is that JavaScript is very fast and it’s worth keeping a DOM tree in it to speed up its manipulation.Although React was conceived to be used in the browser, because of its design it can also be used in the server with Node.js. immukul shubhamyadav4 ghoshsuman0129 katheejabeevi ReactJS Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to fetch data from an API in ReactJS ? How to redirect to another page in ReactJS ? Axios in React: A Guide for Beginners ReactJS setState() How to pass data from one component to other component in ReactJS ? Installation of Node.js on Linux Top 10 Projects For Beginners To Practice HTML and CSS Skills Difference between var, let and const keywords in JavaScript How to insert spaces/tabs in text using HTML/CSS? How to fetch data from an API in ReactJS ?
[ { "code": null, "e": 53, "s": 25, "text": "\n14 Jun, 2022" }, { "code": null, "e": 127, "s": 53, "text": "Introduction to ReactJS: Let us understand this with a practical example." }, { "code": null, "e": 1490, "s": 127, "text": "Let’s say one of your friends posted a photograph on Facebook. Now you go and like the image and then you started checking out the comments too. Now while you are browsing over comments you see that the likes count has increased by 100, since you liked the picture, even without reloading the page. This magical count change is because of ReactJS. React is a declarative, efficient, and flexible JavaScript library for building user interfaces. ‘V’ denotes the view in MVC. ReactJS is an open-source, component-based front end library responsible only for the view layer of the application. It is maintained by Facebook.React uses a declarative paradigm that makes it easier to reason about your application and aims to be both efficient and flexible. It designs simple views for each state in your application, and React will efficiently update and render just the right component when your data changes. The declarative view makes your code more predictable and easier to debug.A React application is made of multiple components, each responsible for rendering a small, reusable piece of HTML. Components can be nested within other components to allow complex applications to be built out of simple building blocks. A component may also maintain an internal state – for example, a TabList component may store a variable corresponding to the currently open tab." }, { "code": null, "e": 1681, "s": 1490, "text": "Note: React is not a framework. It is just a library developed by Facebook to solve some problems that we were facing earlier.Prerequisites: Download Node packages with their latest version." }, { "code": null, "e": 1745, "s": 1681, "text": "Example: Create a new React project by using the command below:" }, { "code": null, "e": 1772, "s": 1745, "text": "npx create-react-app myapp" }, { "code": null, "e": 1843, "s": 1772, "text": "Filename App.js: Now change the App.js file with the given below code:" }, { "code": null, "e": 1854, "s": 1843, "text": "javascript" }, { "code": "import React,{ Component } from 'react'; class App extends Component { render() { return ( <div> <h1>Hello, Learner.Welcome to GeeksforGeeks.</h1> </div> ); }} export default App;", "e": 2072, "s": 1854, "text": null }, { "code": null, "e": 2081, "s": 2072, "text": "Output: " }, { "code": null, "e": 3099, "s": 2081, "text": "How does it work: While building client-side apps, a team of Facebook developers realized that the DOM is slow (The Document Object Model (DOM) is an application programming interface (API) for HTML and XML documents. It defines the logical structure of documents and the way a document is accessed and manipulated.). So, to make it faster, React implements a virtual DOM that is basically a DOM tree representation in JavaScript. So when it needs to read or write to the DOM, it will use the virtual representation of it. Then the virtual DOM will try to find the most efficient way to update the browser’s DOM.Unlike browser DOM elements, React elements are plain objects and are cheap to create. React DOM takes care of updating the DOM to match the React elements. The reason for this is that JavaScript is very fast and it’s worth keeping a DOM tree in it to speed up its manipulation.Although React was conceived to be used in the browser, because of its design it can also be used in the server with Node.js. " }, { "code": null, "e": 3109, "s": 3101, "text": "immukul" }, { "code": null, "e": 3123, "s": 3109, "text": "shubhamyadav4" }, { "code": null, "e": 3138, "s": 3123, "text": "ghoshsuman0129" }, { "code": null, "e": 3152, "s": 3138, "text": "katheejabeevi" }, { "code": null, "e": 3160, "s": 3152, "text": "ReactJS" }, { "code": null, "e": 3177, "s": 3160, "text": "Web Technologies" }, { "code": null, "e": 3275, "s": 3177, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3318, "s": 3275, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 3363, "s": 3318, "text": "How to redirect to another page in ReactJS ?" }, { "code": null, "e": 3401, "s": 3363, "text": "Axios in React: A Guide for Beginners" }, { "code": null, "e": 3420, "s": 3401, "text": "ReactJS setState()" }, { "code": null, "e": 3488, "s": 3420, "text": "How to pass data from one component to other component in ReactJS ?" }, { "code": null, "e": 3521, "s": 3488, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 3583, "s": 3521, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 3644, "s": 3583, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 3694, "s": 3644, "text": "How to insert spaces/tabs in text using HTML/CSS?" } ]
How to Create a Toggle Switch in React as a Reusable Component ?
14 Jul, 2021 In this article, we’re going to create a Toggle Switch in React as a reusable component. The Toggle Switch Component will be a small reusable component that will be able to reuse in future projects. We’ll develop a simple demo toggle-switch-react app that uses this custom toggle switch component. We’ll use common HTML tags with some styling to create this reusable component. You can also create a switch using Material UI- link. Creating React Application: Step 1: Create a React application using the following command:npx create-react-app toggle-switch Step 1: Create a React application using the following command: npx create-react-app toggle-switch Step 2: After creating your project folder i.e. toggle-switch, move to it using the following command:cd toggle-switch Step 2: After creating your project folder i.e. toggle-switch, move to it using the following command: cd toggle-switch Project Structure: It will look like the following: Example: App.js import React, { Component } from "react";import ToggleSwitch from "./components/ToggleSwitch"; class App extends Component { render() { return ( <React.Fragment> <ToggleSwitch label="Notifications" /> <ToggleSwitch label="Subscribe" /> </React.Fragment> ); }}export default App; ToggleSwitch.js import React from "react";import "./ToggleSwitch.css"; const ToggleSwitch = ({ label }) => { return ( <div className="container"> {label}{" "} <div className="toggle-switch"> <input type="checkbox" className="checkbox" name={label} id={label} /> <label className="label" htmlFor={label}> <span className="inner" /> <span className="switch" /> </label> </div> </div> );}; export default ToggleSwitch; ToggleSwitch.css .container { text-align: center;}.toggle-switch { position: relative; width: 75px; display: inline-block; text-align: left; top: 8px;}.checkbox { display: none;}.label { display: block; overflow: hidden; cursor: pointer; border: 0 solid #bbb; border-radius: 20px;}.inner { display: block; width: 200%; margin-left: -100%; transition: margin 0.3s ease-in 0s;}.inner:before,.inner:after { float: left; width: 50%; height: 36px; padding: 0; line-height: 36px; color: #fff; font-weight: bold; box-sizing: border-box;}.inner:before { content: "YES"; padding-left: 10px; background-color: #060; color: #fff;}.inner:after { content: "NO"; padding-right: 10px; background-color: #bbb; color: #fff; text-align: right;}.switch { display: block; width: 24px; margin: 5px; background: #fff; position: absolute; top: 0; bottom: 0; right: 40px; border: 0 solid #bbb; border-radius: 20px; transition: all 0.3s ease-in 0s;}.checkbox:checked + .label .inner { margin-left: 0;}.checkbox:checked + .label .switch { right: 0px;} Step to Run Application: Run the application using the following command from the root directory of the project: npm start Output: Now open your browser and go to http://localhost:3000/, you will see the following output: Picked React-Questions ReactJS Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Axios in React: A Guide for Beginners ReactJS setState() How to pass data from one component to other component in ReactJS ? Re-rendering Components in ReactJS ReactJS defaultProps Installation of Node.js on Linux Top 10 Projects For Beginners To Practice HTML and CSS Skills Difference between var, let and const keywords in JavaScript How to insert spaces/tabs in text using HTML/CSS? Differences between Functional Components and Class Components in React
[ { "code": null, "e": 54, "s": 26, "text": "\n14 Jul, 2021" }, { "code": null, "e": 486, "s": 54, "text": "In this article, we’re going to create a Toggle Switch in React as a reusable component. The Toggle Switch Component will be a small reusable component that will be able to reuse in future projects. We’ll develop a simple demo toggle-switch-react app that uses this custom toggle switch component. We’ll use common HTML tags with some styling to create this reusable component. You can also create a switch using Material UI- link." }, { "code": null, "e": 514, "s": 486, "text": "Creating React Application:" }, { "code": null, "e": 612, "s": 514, "text": "Step 1: Create a React application using the following command:npx create-react-app toggle-switch" }, { "code": null, "e": 676, "s": 612, "text": "Step 1: Create a React application using the following command:" }, { "code": null, "e": 711, "s": 676, "text": "npx create-react-app toggle-switch" }, { "code": null, "e": 830, "s": 711, "text": "Step 2: After creating your project folder i.e. toggle-switch, move to it using the following command:cd toggle-switch" }, { "code": null, "e": 933, "s": 830, "text": "Step 2: After creating your project folder i.e. toggle-switch, move to it using the following command:" }, { "code": null, "e": 950, "s": 933, "text": "cd toggle-switch" }, { "code": null, "e": 1004, "s": 952, "text": "Project Structure: It will look like the following:" }, { "code": null, "e": 1013, "s": 1004, "text": "Example:" }, { "code": null, "e": 1020, "s": 1013, "text": "App.js" }, { "code": "import React, { Component } from \"react\";import ToggleSwitch from \"./components/ToggleSwitch\"; class App extends Component { render() { return ( <React.Fragment> <ToggleSwitch label=\"Notifications\" /> <ToggleSwitch label=\"Subscribe\" /> </React.Fragment> ); }}export default App;", "e": 1332, "s": 1020, "text": null }, { "code": null, "e": 1348, "s": 1332, "text": "ToggleSwitch.js" }, { "code": "import React from \"react\";import \"./ToggleSwitch.css\"; const ToggleSwitch = ({ label }) => { return ( <div className=\"container\"> {label}{\" \"} <div className=\"toggle-switch\"> <input type=\"checkbox\" className=\"checkbox\" name={label} id={label} /> <label className=\"label\" htmlFor={label}> <span className=\"inner\" /> <span className=\"switch\" /> </label> </div> </div> );}; export default ToggleSwitch;", "e": 1827, "s": 1348, "text": null }, { "code": null, "e": 1844, "s": 1827, "text": "ToggleSwitch.css" }, { "code": ".container { text-align: center;}.toggle-switch { position: relative; width: 75px; display: inline-block; text-align: left; top: 8px;}.checkbox { display: none;}.label { display: block; overflow: hidden; cursor: pointer; border: 0 solid #bbb; border-radius: 20px;}.inner { display: block; width: 200%; margin-left: -100%; transition: margin 0.3s ease-in 0s;}.inner:before,.inner:after { float: left; width: 50%; height: 36px; padding: 0; line-height: 36px; color: #fff; font-weight: bold; box-sizing: border-box;}.inner:before { content: \"YES\"; padding-left: 10px; background-color: #060; color: #fff;}.inner:after { content: \"NO\"; padding-right: 10px; background-color: #bbb; color: #fff; text-align: right;}.switch { display: block; width: 24px; margin: 5px; background: #fff; position: absolute; top: 0; bottom: 0; right: 40px; border: 0 solid #bbb; border-radius: 20px; transition: all 0.3s ease-in 0s;}.checkbox:checked + .label .inner { margin-left: 0;}.checkbox:checked + .label .switch { right: 0px;}", "e": 2899, "s": 1844, "text": null }, { "code": null, "e": 3012, "s": 2899, "text": "Step to Run Application: Run the application using the following command from the root directory of the project:" }, { "code": null, "e": 3022, "s": 3012, "text": "npm start" }, { "code": null, "e": 3121, "s": 3022, "text": "Output: Now open your browser and go to http://localhost:3000/, you will see the following output:" }, { "code": null, "e": 3128, "s": 3121, "text": "Picked" }, { "code": null, "e": 3144, "s": 3128, "text": "React-Questions" }, { "code": null, "e": 3152, "s": 3144, "text": "ReactJS" }, { "code": null, "e": 3169, "s": 3152, "text": "Web Technologies" }, { "code": null, "e": 3267, "s": 3169, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3305, "s": 3267, "text": "Axios in React: A Guide for Beginners" }, { "code": null, "e": 3324, "s": 3305, "text": "ReactJS setState()" }, { "code": null, "e": 3392, "s": 3324, "text": "How to pass data from one component to other component in ReactJS ?" }, { "code": null, "e": 3427, "s": 3392, "text": "Re-rendering Components in ReactJS" }, { "code": null, "e": 3448, "s": 3427, "text": "ReactJS defaultProps" }, { "code": null, "e": 3481, "s": 3448, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 3543, "s": 3481, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 3604, "s": 3543, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 3654, "s": 3604, "text": "How to insert spaces/tabs in text using HTML/CSS?" } ]
Kth smallest element in a row-wise and column-wise sorted 2D array | Set 1
05 Jul, 2022 Given an n x n matrix, where every row and column is sorted in non-decreasing order. Find the kth smallest element in the given 2D array.Example, Input:k = 3 and array = 10, 20, 30, 40 15, 25, 35, 45 24, 29, 37, 48 32, 33, 39, 50 Output: 20 Explanation: The 3rd smallest element is 20 Input:k = 7 and array = 10, 20, 30, 40 15, 25, 35, 45 24, 29, 37, 48 32, 33, 39, 50 Output: 30 Explanation: The 7th smallest element is 30 Approach: So the idea is to find the kth minimum element. Each row and each column is sorted. So it can be thought as C sorted lists and the lists have to be merged into a single list, the kth element of the list has to be found out. So the approach is similar, the only difference is when the kth element is found the loop ends.Algorithm: The idea is to use min heap. Create a Min-Heap to store the elementsTraverse the first row from start to end and build a min heap of elements from first row. A heap entry also stores row number and column number.Now Run a loop k times to extract min element from heap in each iterationGet minimum element (or root) from Min-Heap.Find row number and column number of the minimum element.Replace root with the next element from same column and min-heapify the root.Print the last extracted element, which is the kth minimum element The idea is to use min heap. Create a Min-Heap to store the elements Traverse the first row from start to end and build a min heap of elements from first row. A heap entry also stores row number and column number. Now Run a loop k times to extract min element from heap in each iteration Get minimum element (or root) from Min-Heap. Find row number and column number of the minimum element. Replace root with the next element from same column and min-heapify the root. Print the last extracted element, which is the kth minimum element Implementation: C++ Java Python3 C# Javascript // kth largest element in a 2d array sorted row-wise and// column-wise#include <bits/stdc++.h>using namespace std; // A structure to store entry of heap. The entry contains// value from 2D array, row and column numbers of the valuestruct HeapNode { int val; // value to be stored int r; // Row number of value in 2D array int c; // Column number of value in 2D array}; // A utility function to minheapify the node harr[i] of a// heap stored in harr[]void minHeapify(HeapNode harr[], int i, int heap_size){ int l = i * 2 + 1; int r = i * 2 + 2; if(l < heap_size&& r<heap_size && harr[l].val < harr[i].val && harr[r].val < harr[i].val){ HeapNode temp=harr[r]; harr[r]=harr[i]; harr[i]=harr[l]; harr[l]=temp; minHeapify(harr ,l,heap_size); minHeapify(harr ,r,heap_size); } if (l < heap_size && harr[l].val < harr[i].val){ HeapNode temp=harr[i]; harr[i]=harr[l]; harr[l]=temp; minHeapify(harr ,l,heap_size); }} // This function returns kth// smallest element in a 2D array// mat[][]int kthSmallest(int mat[4][4], int n, int k){ // k must be greater than 0 and smaller than n*n if (k < 0 || k >= n * n) return INT_MAX; // Create a min heap of elements from first row of 2D // array HeapNode harr[n]; for (int i = 0; i < n; i++) harr[i] = { mat[0][i], 0, i }; HeapNode hr; for (int i = 0; i < k; i++) { // Get current heap root hr = harr[0]; // Get next value from column of root's value. If // the value stored at root was last value in its // column, then assign INFINITE as next value int nextval = (hr.r < (n - 1)) ? mat[hr.r + 1][hr.c]: INT_MAX; // Update heap root with next value harr[0] = { nextval, (hr.r) + 1, hr.c }; // Heapify root minHeapify(harr, 0, n); } // Return the value at last extracted root return hr.val;} // driver program to test above functionint main(){ int mat[4][4] = { { 10, 20, 30, 40 }, { 15, 25, 35, 45 }, { 25, 29, 37, 48 }, { 32, 33, 39, 50 }, }; cout << "7th smallest element is " << kthSmallest(mat, 4, 7); return 0;} // this code is contributed by Rishabh Chauhan // Java program for kth largest element in a 2d// array sorted row-wise and column-wiseclass GFG{ // A structure to store entry of heap.// The entry contains value from 2D array,// row and column numbers of the valuestatic class HeapNode{ // Value to be stored int val; // Row number of value in 2D array int r; // Column number of value in 2D array int c; HeapNode(int val, int r, int c) { this.val = val; this.c = c; this.r = r; }} // A utility function to minheapify the node// harr[i] of a heap stored in harr[]static void minHeapify(HeapNode harr[], int i, int heap_size){ int l = 2 * i + 1; int r = 2 * i + 2; int min = i; if(l < heap_size&& r<heap_size && harr[l].val < harr[i].val && harr[r].val < harr[i].val){ HeapNode temp=harr[r]; harr[r]=harr[i]; harr[i]=harr[l]; harr[l]=temp; minHeapify(harr ,l,heap_size); minHeapify(harr ,r,heap_size); } if (l < heap_size && harr[l].val < harr[i].val){ HeapNode temp=harr[i]; harr[i]=harr[l]; harr[l]=temp; minHeapify(harr ,l,heap_size); }} // This function returns kth smallest// element in a 2D array mat[][]public static int kthSmallest(int[][] mat,int n, int k){ // k must be greater than 0 and // smaller than n*n if (k < 0 && k >= n * n) return Integer.MAX_VALUE; // Create a min heap of elements // from first row of 2D array HeapNode harr[] = new HeapNode[n]; for(int i = 0; i < n; i++) { harr[i] = new HeapNode(mat[0][i], 0, i); } HeapNode hr = new HeapNode(0, 0, 0); for(int i = 1; i <= k; i++) { // Get current heap root hr = harr[0]; // Get next value from column of root's // value. If the value stored at root was // last value in its column, then assign // INFINITE as next value int nextVal = hr.r < n - 1 ? mat[hr.r + 1][hr.c] : Integer.MAX_VALUE; // Update heap root with next value harr[0] = new HeapNode(nextVal, hr.r + 1, hr.c); // Heapify root minHeapify(harr, 0, n); } // Return the value at last extracted root return hr.val;} // Driver codepublic static void main(String args[]){ int mat[][] = { { 10, 20, 30, 40 }, { 15, 25, 35, 45 }, { 25, 29, 37, 48 }, { 32, 33, 39, 50 } }; int res = kthSmallest(mat, 4, 7); System.out.print("7th smallest element is "+ res);}} // This code is contributed by Rishabh Chauhan # Program for kth largest element in a 2d array# sorted row-wise and column-wisefrom sys import maxsize # A structure to store an entry of heap.# The entry contains a value from 2D array,# row and column numbers of the valueclass HeapNode: def __init__(self, val, r, c): self.val = val # value to be stored self.r = r # Row number of value in 2D array self.c = c # Column number of value in 2D array # A utility function to minheapify the node harr[i]# of a heap stored in harr[]def minHeapify(harr, i, heap_size): l = i * 2 + 1 r = i * 2 + 2 if(l < heap_size and r<heap_size and harr[l].val < harr[i].val and harr[r].val < harr[i].val): temp= HeapNode(0,0,0) temp=harr[r] harr[r]=harr[i] harr[i]=harr[l] harr[l]=temp minHeapify(harr ,l,heap_size) minHeapify(harr ,r,heap_size) if (l < heap_size and harr[l].val < harr[i].val): temp= HeapNode(0,0,0) temp=harr[i] harr[i]=harr[l] harr[l]=temp minHeapify(harr ,l,heap_size) # This function returns kth smallest element# in a 2D array mat[][]def kthSmallest(mat, n, k): # k must be greater than 0 and smaller than n*n if k < 0 or k > n * n: return maxsize # Create a min heap of elements from # first row of 2D array harr = [0] * n for i in range(n): harr[i] = HeapNode(mat[0][i], 0, i) hr = HeapNode(0, 0, 0) for i in range(k): # Get current heap root hr = harr[0] # Get next value from column of root's value. # If the value stored at root was last value # in its column, then assign INFINITE as next value nextval = mat[hr.r + 1][hr.c] if (hr.r < n - 1) else maxsize # Update heap root with next value harr[0] = HeapNode(nextval, hr.r + 1, hr.c) # Heapify root minHeapify(harr, 0, n) # Return the value at last extracted root return hr.val # Driver Codeif __name__ == "__main__": mat = [[10, 20, 30, 40], [15, 25, 35, 45], [25, 29, 37, 48], [32, 33, 39, 50]] print("7th smallest element is", kthSmallest(mat, 4, 7)) # This code is contributed by Rishabh Chauhan // C# program for kth largest element in a 2d// array sorted row-wise and column-wiseusing System; class GFG{ // A structure to store entry of heap.// The entry contains value from 2D array,// row and column numbers of the valueclass HeapNode{ // Value to be stored public int val; // Row number of value in 2D array public int r; // Column number of value in 2D array public int c; public HeapNode(int val, int r, int c) { this.val = val; this.c = c; this.r = r; }} // A utility function to minheapify the node// harr[i] of a heap stored in harr[]static void minHeapify(HeapNode []harr, int i, int heap_size){ int l = 2 * i + 1; int r = 2 * i + 2; if(l < heap_size && r < heap_size && harr[l].val < harr[i].val && harr[r].val < harr[i].val){ HeapNode temp = new HeapNode(0, 0, 0); temp=harr[r]; harr[r]=harr[i]; harr[i]=harr[l]; harr[l]=temp; minHeapify(harr ,l,heap_size); minHeapify(harr ,r,heap_size); } if (l < heap_size && harr[l].val < harr[i].val){ HeapNode temp = new HeapNode(0, 0, 0); temp = harr[i]; harr[i]=harr[l]; harr[l]=temp; minHeapify(harr ,l,heap_size); }} // This function returns kth smallest// element in a 2D array [,]matpublic static int kthSmallest(int[,] mat,int n, int k){ // k must be greater than 0 and // smaller than n*n if (k < 0 || k > n * n) { return int.MaxValue; } // Create a min heap of elements // from first row of 2D array HeapNode []harr = new HeapNode[n]; for(int i = 0; i < n; i++) { harr[i] = new HeapNode(mat[0, i], 0, i); } HeapNode hr = new HeapNode(0, 0, 0); for(int i = 0; i < k; i++) { // Get current heap root hr = harr[0]; // Get next value from column of root's // value. If the value stored at root was // last value in its column, then assign // INFINITE as next value int nextVal = hr.r < n - 1 ? mat[hr.r + 1, hr.c] : int.MaxValue; // Update heap root with next value harr[0] = new HeapNode(nextVal, hr.r + 1, hr.c); // Heapify root minHeapify(harr, 0, n); } // Return the value at last // extracted root return hr.val;} // Driver codepublic static void Main(String []args){ int [,]mat = { { 10, 20, 30, 40 }, { 15, 25, 35, 45 }, { 25, 29, 37, 48 }, { 32, 33, 39, 50 } }; int res = kthSmallest(mat, 4, 7); Console.Write("7th smallest element is " + res);}} // This code is contributed by Rishabh Chauhan <script>// Javascript program for kth largest element in a 2d// array sorted row-wise and column-wise // A structure to store entry of heap.// The entry contains value from 2D array,// row and column numbers of the valueclass HeapNode{ constructor(val,r,c) { this.val = val; this.c = c; this.r = r; }} // A utility function to minheapify the node// harr[i] of a heap stored in harr[]function minHeapify(harr,i,heap_size){ let l = 2 * i + 1; let r = 2 * i + 2; let min = i; if(l < heap_size&& r<heap_size && harr[l].val < harr[i].val && harr[r].val < harr[i].val){ let temp=harr[r]; harr[r]=harr[i]; harr[i]=harr[l]; harr[l]=temp; minHeapify(harr ,l,heap_size); minHeapify(harr ,r,heap_size); } if (l < heap_size && harr[l].val < harr[i].val){ let temp=harr[i]; harr[i]=harr[l]; harr[l]=temp; minHeapify(harr ,l,heap_size); }} // This function returns kth smallest// element in a 2D array mat[][]function kthSmallest(mat,n,k){ // k must be greater than 0 and // smaller than n*n if (k < 0 && k >= n * n) return Number.MAX_VALUE; // Create a min heap of elements // from first row of 2D array let harr = new Array(n); for(let i = 0; i < n; i++) { harr[i] = new HeapNode(mat[0][i], 0, i); } let hr = new HeapNode(0, 0, 0); for(let i = 1; i <= k; i++) { // Get current heap root hr = harr[0]; // Get next value from column of root's // value. If the value stored at root was // last value in its column, then assign // INFINITE as next value let nextVal = hr.r < n - 1 ? mat[hr.r + 1][hr.c] : Number.MAX_VALUE; // Update heap root with next value harr[0] = new HeapNode(nextVal, hr.r + 1, hr.c); // Heapify root minHeapify(harr, 0, n); } // Return the value at last extracted root return hr.val;} // Driver codelet mat=[[ 10, 20, 30, 40 ], [ 15, 25, 35, 45 ], [ 25, 29, 37, 48 ], [ 32, 33, 39, 50 ]];let res = kthSmallest(mat, 4, 7);document.write("7th smallest element is "+ res); // This code is contributed by avanitrachhadiya2155</script> 7th smallest element is 30 The codes above are contributed by RISHABH CHAUHAN.Complexity Analysis: Time Complexity: The above solution involves following steps. Building a min-heap which takes O(n) timeHeapify k times which takes O(k Logn) time. Building a min-heap which takes O(n) timeHeapify k times which takes O(k Logn) time. Building a min-heap which takes O(n) time Heapify k times which takes O(k Logn) time. Auxiliary Space: O(R), where R is the length of a row, as the Min-Heap stores one row at a time. The above code can be optimized to build a heap of size k when k is smaller than n. In that case, the kth smallest element must be in first k rows and k columns. We will soon be publishing more efficient algorithms for finding the kth smallest element. This article is compiled by Ravi Gupta. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above Using inbuilt priority_queue : By using a comparator, we can carry out custom comparison in priority_queue. We will use priority_queue<pair<int,int>> for this. Implementation : C++ // kth largest element in a 2d array sorted row-wise and// column-wise#include<bits/stdc++.h>using namespace std; int kthSmallest(int mat[4][4], int n, int k){ // USING LAMBDA FUNCTION // [=] IN LAMBDA FUNCTION IS FOR CAPTURING VARIABLES WHICH // ARE OUT OF SCOPE i.e. mat[r] // NOW, IT'LL COMPARE ELEMENTS OF HEAP BY ELEMENTS AT mat[first][second] // Capturing the value of mat by reference to prevent copying auto cmp = [&](pair<int,int> a,pair<int,int> b){ return mat[a.first][a.second] > mat[b.first][b.second]; }; //DECLARING priority_queue AND PUSHING FIRST ROW IN IT priority_queue<pair<int,int>,vector<pair<int,int>>,decltype(cmp)> pq(cmp); for(int i=0; i<n; i++){ pq.push({i,0}); } //RUNNING LOOP FOR (k-1) TIMES for(int i=1; i<k; i++){ auto p = pq.top(); pq.pop(); //AFTER POPPING, WE'LL PUSH NEXT ELEMENT OF THE ROW IN THE HEAP if(p.second+1 < n) pq.push({p.first,p.second + 1}); } // ON THE k'th ITERATION, pq.top() will be our answer. return mat[pq.top().first][pq.top().second];} // driver program to test above functionint main(){ int mat[4][4] = { { 10, 20, 30, 40 }, { 15, 25, 35, 45 }, { 25, 29, 37, 48 }, { 32, 33, 39, 50 }, }; cout << "7th smallest element is " << kthSmallest(mat, 4, 7); return 0;} 7th smallest element is 30 Time Complexity: O(n log n) Auxiliary Space: O(n) This approach uses binary search to iterate over possible solutions. We know that answer >= mat[0][0]answer <= mat[N-1][N-1] answer >= mat[0][0] answer <= mat[N-1][N-1] So we do a binary search on this range and in each iteration determine the no of elements greater than or equal to our current middle element. The elements greater than or equal to current element can be found in O( n logn ) time using binary search. C++ Java Python3 C# Javascript #include <bits/stdc++.h>using namespace std; // This returns count of elements in matrix less than of equal to numint getElementsGreaterThanOrEqual(int num, int n, int mat[4][4]) { int ans = 0; for (int i = 0; i < n; i++) { // if num is less than the first element then no more element in matrix // further are less than or equal to num if (mat[i][0] > num) { return ans; } // if num is greater than last element, it is greater than all elements // in that row if (mat[i][n - 1] <= num) { ans += n; continue; } // This contain the col index of last element in matrix less than of equal // to num int greaterThan = 0; for (int jump = n / 2; jump >= 1; jump /= 2) { while (greaterThan + jump < n && mat[i][greaterThan + jump] <= num) { greaterThan += jump; } } ans += greaterThan + 1; } return ans;} // returns kth smallest index in the matrixint kthSmallest(int mat[4][4], int n, int k) { // We know the answer lies between the first and the last element // So do a binary search on answer based on the number of elements // our current element is greater than the elements in the matrix int l = mat[0][0], r = mat[n - 1][n - 1]; while (l <= r) { int mid = l + (r - l) / 2; int greaterThanOrEqualMid = getElementsGreaterThanOrEqual(mid, n, mat); if (greaterThanOrEqualMid >= k) r = mid - 1; else l = mid + 1; } return l;} int main() { int n = 4; int mat[4][4] = { {10, 20, 30, 40}, {15, 25, 35, 45}, {25, 29, 37, 48}, {32, 33, 39, 50}, }; cout << "7th smallest element is " << kthSmallest(mat, 4, 7); return 0;} class GFG { // This returns count of elements in // matrix less than of equal to num static int getElementsGreaterThanOrEqual(int num, int n, int mat[][]) { int ans = 0; for (int i = 0; i < n; i++) { // if num is less than the first element // then no more element in matrix // further are less than or equal to num if (mat[i][0] > num) { return ans; } // if num is greater than last element, // it is greater than all elements // in that row if (mat[i][n - 1] <= num) { ans += n; continue; } // This contain the col index of last element // in matrix less than of equal // to num int greaterThan = 0; for (int jump = n / 2; jump >= 1; jump /= 2) { while (greaterThan + jump < n && mat[i][greaterThan + jump] <= num) { greaterThan += jump; } } ans += greaterThan + 1; } return ans; } // returns kth smallest index in the matrix static int kthSmallest(int mat[][], int n, int k) { // We know the answer lies between the first and the last element // So do a binary search on answer based on the number of elements // our current element is greater than the elements in the matrix int l = mat[0][0], r = mat[n - 1][n - 1]; while (l <= r) { int mid = l + (r - l) / 2; int greaterThanOrEqualMid = getElementsGreaterThanOrEqual(mid, n, mat); if (greaterThanOrEqualMid >= k) r = mid - 1; else l = mid + 1; } return l; } public static void main(String args[]) { int mat[][] = { { 10, 20, 30, 40 }, { 15, 25, 35, 45 }, { 25, 29, 37, 48 }, { 32, 33, 39, 50 }, }; System.out.println("7th smallest element is " + kthSmallest(mat, 4, 7)); } } // This code is contributed by gfgking. # This returns count of elements in matrix# less than of equal to numdef getElementsGreaterThanOrEqual(num,n,mat): ans = 0 for i in range(n): # if num is less than the first element # then no more element in matrix # further are less than or equal to num if (mat[i][0] > num): return ans # if num is greater than last element, # it is greater than all elements # in that row if (mat[i][n - 1] <= num): ans += n continue # This contain the col index of last element # in matrix less than of equal # to num greaterThan = 0 jump = n // 2 while(jump >= 1): while (greaterThan + jump < n and mat[i][greaterThan + jump] <= num): greaterThan += jump jump //= 2 ans += greaterThan + 1 return ans # returns kth smallest index in the matrixdef kthSmallest(mat, n, k): # We know the answer lies between # the first and the last element # So do a binary search on answer # based on the number of elements # our current element is greater than # the elements in the matrix l,r = mat[0][0],mat[n - 1][n - 1] while (l <= r): mid = l + (r - l) // 2 greaterThanOrEqualMid = getElementsGreaterThanOrEqual(mid, n, mat) if (greaterThanOrEqualMid >= k): r = mid - 1 else: l = mid + 1 return l # driver coden = 4mat = [[10, 20, 30, 40],[15, 25, 35, 45],[25, 29, 37, 48],[32, 33, 39, 50]]print(f"7th smallest element is {kthSmallest(mat, 4, 7)}") # This code is contributed by shinjanpatra using System; public class GFG{ // This returns count of elements in // matrix less than of equal to num static int getElementsGreaterThanOrEqual(int num, int n, int [,]mat) { int ans = 0; for (int i = 0; i < n; i++) { // if num is less than the first element // then no more element in matrix // further are less than or equal to num if (mat[i,0] > num) { return ans; } // if num is greater than last element, // it is greater than all elements // in that row if (mat[i,n - 1] <= num) { ans += n; continue; } // This contain the col index of last element // in matrix less than of equal // to num int greaterThan = 0; for (int jump = n / 2; jump >= 1; jump /= 2) { while (greaterThan + jump < n && mat[i,greaterThan + jump] <= num) { greaterThan += jump; } } ans += greaterThan + 1; } return ans; } // returns kth smallest index in the matrix static int kthSmallest(int [,]mat, int n, int k) { // We know the answer lies between the first and the last element // So do a binary search on answer based on the number of elements // our current element is greater than the elements in the matrix int l = mat[0,0], r = mat[n - 1,n - 1]; while (l <= r) { int mid = l + (r - l) / 2; int greaterThanOrEqualMid = getElementsGreaterThanOrEqual(mid, n, mat); if (greaterThanOrEqualMid >= k) r = mid - 1; else l = mid + 1; } return l; } public static void Main(String []args) { int [,]mat = { { 10, 20, 30, 40 }, { 15, 25, 35, 45 }, { 25, 29, 37, 48 }, { 32, 33, 39, 50 }, }; Console.WriteLine("7th smallest element is " + kthSmallest(mat, 4, 7)); } } // This code is contributed by 29AjayKumar <script> // This returns count of elements in matrix // less than of equal to num function getElementsGreaterThanOrEqual(num,n,mat) { let ans = 0 for (let i = 0; i < n; i++) { // if num is less than the first element // then no more element in matrix // further are less than or equal to num if (mat[i][0] > num) { return ans; } // if num is greater than last element, // it is greater than all elements // in that row if (mat[i][n - 1] <= num) { ans += n; continue; } // This contain the col index of last element // in matrix less than of equal // to num let greaterThan = 0; for (let jump = n / 2; jump >= 1; jump /= 2) { while (greaterThan + jump < n && mat[i][greaterThan + jump] <= num) { greaterThan += jump; } } ans += greaterThan + 1; } return ans; } // returns kth smallest index in the matrix function kthSmallest(mat,n,k) { // We know the answer lies between // the first and the last element // So do a binary search on answer // based on the number of elements // our current element is greater than // the elements in the matrix let l = mat[0][0], r = mat[n - 1][n - 1]; while (l <= r) { let mid = l + parseInt((r - l) / 2, 10); let greaterThanOrEqualMid = getElementsGreaterThanOrEqual(mid, n, mat); if (greaterThanOrEqualMid >= k) r = mid - 1; else l = mid + 1; } return l; } let n = 4; let mat = [ [10, 20, 30, 40], [15, 25, 35, 45], [25, 29, 37, 48], [32, 33, 39, 50], ]; document.write("7th smallest element is " + kthSmallest(mat, 4, 7)); </script> Output: 7th smallest element is 30 Complexity Analysis Time Complexity : O( y * n*logn) Where y = log( abs(Mat[0][0] - Mat[n-1][n-1]) ) We call the getElementsGreaterThanOrEqual function log ( abs(Mat[0][0] – Mat[n-1][n-1]) ) timesTime complexity of getElementsGreaterThanOrEqual is O(n logn) since there we do binary search n times. We call the getElementsGreaterThanOrEqual function log ( abs(Mat[0][0] – Mat[n-1][n-1]) ) times Time complexity of getElementsGreaterThanOrEqual is O(n logn) since there we do binary search n times. Auxiliary Space: O(1) USING ARRAY: We will make a new array and will copy all the contents of matrix in this array. After that we will sort that array and find kth smallest element. This will be so easier. C++ Java Python3 C# Javascript // C++ code to implement the approach#include <bits/stdc++.h>using namespace std; int kthSmallest(int mat[4][4], int n, int k){ int a[n*n]; int v = 0; for(int i = 0; i < n; i++) { for(int j = 0; j < n; j++) { a[v] = mat[i][j]; v++; } } sort(a, a + (n*n)); int result = a[k - 1]; return result;} // Driver codeint main(){ int mat[4][4] = { { 10, 20, 30, 40 }, { 15, 25, 35, 45 }, { 25, 29, 37, 48 }, { 32, 33, 39, 50 } }; int res = kthSmallest(mat, 4, 7); cout << "7th smallest element is " << res; return 0;} // This code is contributed by sanjoy_62. /*package whatever //do not write package name here */ import java.io.*;import java.util.*;class GFG { public static void main (String[] args) { int mat[][] = { { 10, 20, 30, 40 }, { 15, 25, 35, 45 }, { 25, 29, 37, 48 }, { 32, 33, 39, 50 } }; int res = kthSmallest(mat, 4, 7); System.out.print("7th smallest element is "+ res); } static int kthSmallest(int[][]mat,int n,int k) { int[] a=new int[n*n]; int v=0; for(int i=0;i<n;i++){ for(int j=0;j<n;j++){ a[v]=mat[i][j]; v++; } } Arrays.sort(a); int result=a[k-1]; return result; }} # Python program to implement above approachdef kthSmallest(mat, n, k): a = [0 for i in range(n*n)] v=0 for i in range(n): for j in range(n): a[v] = mat[i][j] v += 1 a.sort() result = a[k - 1] return result # driver program mat = [ [ 10, 20, 30, 40 ], [ 15, 25, 35, 45 ], [ 25, 29, 37, 48 ], [ 32, 33, 39, 50 ] ]res = kthSmallest(mat, 4, 7) print("7th smallest element is "+ str(res)) # This code is contributed by shinjanpatra /*package whatever //do not write package name here */using System;using System.Collections.Generic; public class GFG { public static void Main(String[] args) { int [,]mat = { { 10, 20, 30, 40 }, { 15, 25, 35, 45 }, { 25, 29, 37, 48 }, { 32, 33, 39, 50 } }; int res = kthSmallest(mat, 4, 7); Console.Write("7th smallest element is "+ res); } static int kthSmallest(int[,]mat, int n, int k) { int[] a = new int[n*n]; int v = 0; for(int i = 0; i < n; i++) { for(int j = 0; j < n; j++) { a[v] = mat[i, j]; v++; } } Array.Sort(a); int result = a[k - 1]; return result; }} // This code is contributed by 29AjayKumar <script> // JavaScript program to implement above approachfunction kthSmallest(mat, n, k){ let a = new Array(n*n) let v=0 for(let i = 0; i < n; i++) { for(let j = 0; j < n; j++) { a[v] = mat[i][j]; v++; } } a.sort(); let result = a[k - 1]; return result;} // driver program let mat = [ [ 10, 20, 30, 40 ], [ 15, 25, 35, 45 ], [ 25, 29, 37, 48 ], [ 32, 33, 39, 50 ] ]let res = kthSmallest(mat, 4, 7) document.write("7th smallest element is "+ res,"</br>") // This code is contributed by shinjanpatra </script> 7th smallest element is 30 Time Complexity: O(n2) Auxiliary Space: O(n2) Using Priority queue approach C++14 Java Python3 C# #include <bits/stdc++.h>using namespace std;int kthSmallest(vector<vector<int>>& matrix, int k) { //n = size of matrix int i,j,n=matrix.size(); //using built-in priority queue which acts as max Heap i.e. largest element will be on top //Kth smallest element can also be seen as largest element in a priority queue of size k //By this logic we pop elements from priority queue when its size becomes greater than k //thus top of priority queue is kth smallest element in matrix priority_queue<int> maxH; if(k==1) return matrix[0][0]; for(i=0;i<n;i++) { for(j=0;j<n;j++) { maxH.push(matrix[i][j]); if(maxH.size()>k) maxH.pop(); } } return maxH.top();}int main() { vector<vector<int>> matrix = {{1,5,9},{10,11,13},{12,13,15}}; int k = 8; cout << "8th smallest element is " << kthSmallest(matrix,k); return 0;} import java.util.*;public class Main { public static int kthSmallest(int[][] matrix, int k) { // n = size of matrix int i, j, n = matrix.length; // using built-in priority queue which acts as max // Heap i.e. largest element will be on top // Kth smallest element can also be seen as largest // element in a priority queue of size k By this // logic we pop elements from priority queue when // its size becomes greater than k thus top of // priority queue is kth smallest element in matrix PriorityQueue<Integer> maxH = new PriorityQueue<>( Collections.reverseOrder()); if (k == 1) return matrix[0][0]; for (i = 0; i < n; i++) { for (j = 0; j < n; j++) { maxH.add(matrix[i][j]); if (maxH.size() > k) maxH.poll(); } } return maxH.peek(); } public static void main(String[] args) { int[][] matrix = { { 1, 5, 9 }, { 10, 11, 13 }, { 12, 13, 15 } }; int k = 8; System.out.print("8th smallest element is " + kthSmallest(matrix, k)); }} // This code is contributed by tapeshdua420. import heapq def kthSmallest(matrix, k): # n = size of matrix n = len(matrix) # using built-in priority queue which acts as max Heap i.e. largest element will be on top # Kth smallest element can also be seen as largest element in a priority queue of size k # By this logic we pop elements from priority queue when its size becomes greater than k # thus top of priority queue is kth smallest element in matrix maxH = [] for i in range(n): for j in range(n): heapq.heappush(maxH, -matrix[i][j]) if len(maxH) > k: heapq.heappop(maxH) return -maxH[0] matrix = [[1, 5, 9], [10, 11, 13], [12, 13, 15]]k = 8print("8th smallest element is", kthSmallest(matrix, k)) # This code is comtributed by Tapesh (tapeshdua420) using System;using System.Collections.Generic; public class GFG { public static int kthSmallest(int[,] matrix, int k) { // n = size of matrix int i, j, n = matrix.GetLength(0); // using built-in priority queue which acts as max // Heap i.e. largest element will be on top // Kth smallest element can also be seen as largest // element in a priority queue of size k By this // logic we pop elements from priority queue when // its size becomes greater than k thus top of // priority queue is kth smallest element in matrix List<int> maxH = new List<int>(); if (k == 1) return matrix[0,0]; for (i = 0; i < n; i++) { for (j = 0; j < n; j++) { maxH.Add(matrix[i,j]); if (maxH.Count > k){ maxH.Sort((a, b) => b.CompareTo(a)); maxH.RemoveAt(0); } } } maxH.Sort((a, b) => b.CompareTo(a)); return maxH[0]; } public static void Main(String[] args) { int[,] matrix = { { 1, 5, 9 }, { 10, 11, 13 }, { 12, 13, 15 } }; int k = 8; Console.Write("8th smallest element is " + kthSmallest(matrix, k)); }} // This code is contributed by shikhasingrajput 8th smallest element is 13 Time Complexity: O(n2) Auxiliary Space: O(n) This article is contributed by Aarti_Rathi. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above sanjeev2552 andrew1234 Akanksha_Rai nikhil kumar sharma amit143katiyar adankitdutta akscodebay himankgoel12 mohitawachar sinhadiptiprakash drsmolderrishabhchauhan avanitrachhadiya2155 vaibhavrabadiya117 kumaratishek22 ayushh2023 29AjayKumar gfgking simmytarika5 shinjanpatra aj_00_11 sanjoy_62 sanchita0500 tapeshdua420 codewithrathi shikhasingrajput Accolite Amazon Order-Statistics Heap Matrix Searching Accolite Amazon Searching Matrix Heap Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. HeapSort Introduction to Data Structures Binary Heap Huffman Coding | Greedy Algo-3 Sliding Window Maximum (Maximum of all subarrays of size k) Rat in a Maze | Backtracking-2 Find the longest path in a matrix with given constraints Matrix Chain Multiplication | DP-8 Print a given matrix in spiral form Program to find largest element in an array
[ { "code": null, "e": 52, "s": 24, "text": "\n05 Jul, 2022" }, { "code": null, "e": 199, "s": 52, "text": "Given an n x n matrix, where every row and column is sorted in non-decreasing order. Find the kth smallest element in the given 2D array.Example, " }, { "code": null, "e": 546, "s": 199, "text": "Input:k = 3 and array =\n 10, 20, 30, 40\n 15, 25, 35, 45\n 24, 29, 37, 48\n 32, 33, 39, 50 \nOutput: 20\nExplanation: The 3rd smallest element is 20 \n\nInput:k = 7 and array =\n 10, 20, 30, 40\n 15, 25, 35, 45\n 24, 29, 37, 48\n 32, 33, 39, 50 \nOutput: 30\n\nExplanation: The 7th smallest element is 30" }, { "code": null, "e": 886, "s": 546, "text": "Approach: So the idea is to find the kth minimum element. Each row and each column is sorted. So it can be thought as C sorted lists and the lists have to be merged into a single list, the kth element of the list has to be found out. So the approach is similar, the only difference is when the kth element is found the loop ends.Algorithm:" }, { "code": null, "e": 1416, "s": 886, "text": "The idea is to use min heap. Create a Min-Heap to store the elementsTraverse the first row from start to end and build a min heap of elements from first row. A heap entry also stores row number and column number.Now Run a loop k times to extract min element from heap in each iterationGet minimum element (or root) from Min-Heap.Find row number and column number of the minimum element.Replace root with the next element from same column and min-heapify the root.Print the last extracted element, which is the kth minimum element" }, { "code": null, "e": 1485, "s": 1416, "text": "The idea is to use min heap. Create a Min-Heap to store the elements" }, { "code": null, "e": 1630, "s": 1485, "text": "Traverse the first row from start to end and build a min heap of elements from first row. A heap entry also stores row number and column number." }, { "code": null, "e": 1704, "s": 1630, "text": "Now Run a loop k times to extract min element from heap in each iteration" }, { "code": null, "e": 1749, "s": 1704, "text": "Get minimum element (or root) from Min-Heap." }, { "code": null, "e": 1807, "s": 1749, "text": "Find row number and column number of the minimum element." }, { "code": null, "e": 1885, "s": 1807, "text": "Replace root with the next element from same column and min-heapify the root." }, { "code": null, "e": 1952, "s": 1885, "text": "Print the last extracted element, which is the kth minimum element" }, { "code": null, "e": 1968, "s": 1952, "text": "Implementation:" }, { "code": null, "e": 1972, "s": 1968, "text": "C++" }, { "code": null, "e": 1977, "s": 1972, "text": "Java" }, { "code": null, "e": 1985, "s": 1977, "text": "Python3" }, { "code": null, "e": 1988, "s": 1985, "text": "C#" }, { "code": null, "e": 1999, "s": 1988, "text": "Javascript" }, { "code": "// kth largest element in a 2d array sorted row-wise and// column-wise#include <bits/stdc++.h>using namespace std; // A structure to store entry of heap. The entry contains// value from 2D array, row and column numbers of the valuestruct HeapNode { int val; // value to be stored int r; // Row number of value in 2D array int c; // Column number of value in 2D array}; // A utility function to minheapify the node harr[i] of a// heap stored in harr[]void minHeapify(HeapNode harr[], int i, int heap_size){ int l = i * 2 + 1; int r = i * 2 + 2; if(l < heap_size&& r<heap_size && harr[l].val < harr[i].val && harr[r].val < harr[i].val){ HeapNode temp=harr[r]; harr[r]=harr[i]; harr[i]=harr[l]; harr[l]=temp; minHeapify(harr ,l,heap_size); minHeapify(harr ,r,heap_size); } if (l < heap_size && harr[l].val < harr[i].val){ HeapNode temp=harr[i]; harr[i]=harr[l]; harr[l]=temp; minHeapify(harr ,l,heap_size); }} // This function returns kth// smallest element in a 2D array// mat[][]int kthSmallest(int mat[4][4], int n, int k){ // k must be greater than 0 and smaller than n*n if (k < 0 || k >= n * n) return INT_MAX; // Create a min heap of elements from first row of 2D // array HeapNode harr[n]; for (int i = 0; i < n; i++) harr[i] = { mat[0][i], 0, i }; HeapNode hr; for (int i = 0; i < k; i++) { // Get current heap root hr = harr[0]; // Get next value from column of root's value. If // the value stored at root was last value in its // column, then assign INFINITE as next value int nextval = (hr.r < (n - 1)) ? mat[hr.r + 1][hr.c]: INT_MAX; // Update heap root with next value harr[0] = { nextval, (hr.r) + 1, hr.c }; // Heapify root minHeapify(harr, 0, n); } // Return the value at last extracted root return hr.val;} // driver program to test above functionint main(){ int mat[4][4] = { { 10, 20, 30, 40 }, { 15, 25, 35, 45 }, { 25, 29, 37, 48 }, { 32, 33, 39, 50 }, }; cout << \"7th smallest element is \" << kthSmallest(mat, 4, 7); return 0;} // this code is contributed by Rishabh Chauhan", "e": 4328, "s": 1999, "text": null }, { "code": "// Java program for kth largest element in a 2d// array sorted row-wise and column-wiseclass GFG{ // A structure to store entry of heap.// The entry contains value from 2D array,// row and column numbers of the valuestatic class HeapNode{ // Value to be stored int val; // Row number of value in 2D array int r; // Column number of value in 2D array int c; HeapNode(int val, int r, int c) { this.val = val; this.c = c; this.r = r; }} // A utility function to minheapify the node// harr[i] of a heap stored in harr[]static void minHeapify(HeapNode harr[], int i, int heap_size){ int l = 2 * i + 1; int r = 2 * i + 2; int min = i; if(l < heap_size&& r<heap_size && harr[l].val < harr[i].val && harr[r].val < harr[i].val){ HeapNode temp=harr[r]; harr[r]=harr[i]; harr[i]=harr[l]; harr[l]=temp; minHeapify(harr ,l,heap_size); minHeapify(harr ,r,heap_size); } if (l < heap_size && harr[l].val < harr[i].val){ HeapNode temp=harr[i]; harr[i]=harr[l]; harr[l]=temp; minHeapify(harr ,l,heap_size); }} // This function returns kth smallest// element in a 2D array mat[][]public static int kthSmallest(int[][] mat,int n, int k){ // k must be greater than 0 and // smaller than n*n if (k < 0 && k >= n * n) return Integer.MAX_VALUE; // Create a min heap of elements // from first row of 2D array HeapNode harr[] = new HeapNode[n]; for(int i = 0; i < n; i++) { harr[i] = new HeapNode(mat[0][i], 0, i); } HeapNode hr = new HeapNode(0, 0, 0); for(int i = 1; i <= k; i++) { // Get current heap root hr = harr[0]; // Get next value from column of root's // value. If the value stored at root was // last value in its column, then assign // INFINITE as next value int nextVal = hr.r < n - 1 ? mat[hr.r + 1][hr.c] : Integer.MAX_VALUE; // Update heap root with next value harr[0] = new HeapNode(nextVal, hr.r + 1, hr.c); // Heapify root minHeapify(harr, 0, n); } // Return the value at last extracted root return hr.val;} // Driver codepublic static void main(String args[]){ int mat[][] = { { 10, 20, 30, 40 }, { 15, 25, 35, 45 }, { 25, 29, 37, 48 }, { 32, 33, 39, 50 } }; int res = kthSmallest(mat, 4, 7); System.out.print(\"7th smallest element is \"+ res);}} // This code is contributed by Rishabh Chauhan", "e": 7174, "s": 4328, "text": null }, { "code": "# Program for kth largest element in a 2d array# sorted row-wise and column-wisefrom sys import maxsize # A structure to store an entry of heap.# The entry contains a value from 2D array,# row and column numbers of the valueclass HeapNode: def __init__(self, val, r, c): self.val = val # value to be stored self.r = r # Row number of value in 2D array self.c = c # Column number of value in 2D array # A utility function to minheapify the node harr[i]# of a heap stored in harr[]def minHeapify(harr, i, heap_size): l = i * 2 + 1 r = i * 2 + 2 if(l < heap_size and r<heap_size and harr[l].val < harr[i].val and harr[r].val < harr[i].val): temp= HeapNode(0,0,0) temp=harr[r] harr[r]=harr[i] harr[i]=harr[l] harr[l]=temp minHeapify(harr ,l,heap_size) minHeapify(harr ,r,heap_size) if (l < heap_size and harr[l].val < harr[i].val): temp= HeapNode(0,0,0) temp=harr[i] harr[i]=harr[l] harr[l]=temp minHeapify(harr ,l,heap_size) # This function returns kth smallest element# in a 2D array mat[][]def kthSmallest(mat, n, k): # k must be greater than 0 and smaller than n*n if k < 0 or k > n * n: return maxsize # Create a min heap of elements from # first row of 2D array harr = [0] * n for i in range(n): harr[i] = HeapNode(mat[0][i], 0, i) hr = HeapNode(0, 0, 0) for i in range(k): # Get current heap root hr = harr[0] # Get next value from column of root's value. # If the value stored at root was last value # in its column, then assign INFINITE as next value nextval = mat[hr.r + 1][hr.c] if (hr.r < n - 1) else maxsize # Update heap root with next value harr[0] = HeapNode(nextval, hr.r + 1, hr.c) # Heapify root minHeapify(harr, 0, n) # Return the value at last extracted root return hr.val # Driver Codeif __name__ == \"__main__\": mat = [[10, 20, 30, 40], [15, 25, 35, 45], [25, 29, 37, 48], [32, 33, 39, 50]] print(\"7th smallest element is\", kthSmallest(mat, 4, 7)) # This code is contributed by Rishabh Chauhan", "e": 9354, "s": 7174, "text": null }, { "code": "// C# program for kth largest element in a 2d// array sorted row-wise and column-wiseusing System; class GFG{ // A structure to store entry of heap.// The entry contains value from 2D array,// row and column numbers of the valueclass HeapNode{ // Value to be stored public int val; // Row number of value in 2D array public int r; // Column number of value in 2D array public int c; public HeapNode(int val, int r, int c) { this.val = val; this.c = c; this.r = r; }} // A utility function to minheapify the node// harr[i] of a heap stored in harr[]static void minHeapify(HeapNode []harr, int i, int heap_size){ int l = 2 * i + 1; int r = 2 * i + 2; if(l < heap_size && r < heap_size && harr[l].val < harr[i].val && harr[r].val < harr[i].val){ HeapNode temp = new HeapNode(0, 0, 0); temp=harr[r]; harr[r]=harr[i]; harr[i]=harr[l]; harr[l]=temp; minHeapify(harr ,l,heap_size); minHeapify(harr ,r,heap_size); } if (l < heap_size && harr[l].val < harr[i].val){ HeapNode temp = new HeapNode(0, 0, 0); temp = harr[i]; harr[i]=harr[l]; harr[l]=temp; minHeapify(harr ,l,heap_size); }} // This function returns kth smallest// element in a 2D array [,]matpublic static int kthSmallest(int[,] mat,int n, int k){ // k must be greater than 0 and // smaller than n*n if (k < 0 || k > n * n) { return int.MaxValue; } // Create a min heap of elements // from first row of 2D array HeapNode []harr = new HeapNode[n]; for(int i = 0; i < n; i++) { harr[i] = new HeapNode(mat[0, i], 0, i); } HeapNode hr = new HeapNode(0, 0, 0); for(int i = 0; i < k; i++) { // Get current heap root hr = harr[0]; // Get next value from column of root's // value. If the value stored at root was // last value in its column, then assign // INFINITE as next value int nextVal = hr.r < n - 1 ? mat[hr.r + 1, hr.c] : int.MaxValue; // Update heap root with next value harr[0] = new HeapNode(nextVal, hr.r + 1, hr.c); // Heapify root minHeapify(harr, 0, n); } // Return the value at last // extracted root return hr.val;} // Driver codepublic static void Main(String []args){ int [,]mat = { { 10, 20, 30, 40 }, { 15, 25, 35, 45 }, { 25, 29, 37, 48 }, { 32, 33, 39, 50 } }; int res = kthSmallest(mat, 4, 7); Console.Write(\"7th smallest element is \" + res);}} // This code is contributed by Rishabh Chauhan", "e": 12238, "s": 9354, "text": null }, { "code": "<script>// Javascript program for kth largest element in a 2d// array sorted row-wise and column-wise // A structure to store entry of heap.// The entry contains value from 2D array,// row and column numbers of the valueclass HeapNode{ constructor(val,r,c) { this.val = val; this.c = c; this.r = r; }} // A utility function to minheapify the node// harr[i] of a heap stored in harr[]function minHeapify(harr,i,heap_size){ let l = 2 * i + 1; let r = 2 * i + 2; let min = i; if(l < heap_size&& r<heap_size && harr[l].val < harr[i].val && harr[r].val < harr[i].val){ let temp=harr[r]; harr[r]=harr[i]; harr[i]=harr[l]; harr[l]=temp; minHeapify(harr ,l,heap_size); minHeapify(harr ,r,heap_size); } if (l < heap_size && harr[l].val < harr[i].val){ let temp=harr[i]; harr[i]=harr[l]; harr[l]=temp; minHeapify(harr ,l,heap_size); }} // This function returns kth smallest// element in a 2D array mat[][]function kthSmallest(mat,n,k){ // k must be greater than 0 and // smaller than n*n if (k < 0 && k >= n * n) return Number.MAX_VALUE; // Create a min heap of elements // from first row of 2D array let harr = new Array(n); for(let i = 0; i < n; i++) { harr[i] = new HeapNode(mat[0][i], 0, i); } let hr = new HeapNode(0, 0, 0); for(let i = 1; i <= k; i++) { // Get current heap root hr = harr[0]; // Get next value from column of root's // value. If the value stored at root was // last value in its column, then assign // INFINITE as next value let nextVal = hr.r < n - 1 ? mat[hr.r + 1][hr.c] : Number.MAX_VALUE; // Update heap root with next value harr[0] = new HeapNode(nextVal, hr.r + 1, hr.c); // Heapify root minHeapify(harr, 0, n); } // Return the value at last extracted root return hr.val;} // Driver codelet mat=[[ 10, 20, 30, 40 ], [ 15, 25, 35, 45 ], [ 25, 29, 37, 48 ], [ 32, 33, 39, 50 ]];let res = kthSmallest(mat, 4, 7);document.write(\"7th smallest element is \"+ res); // This code is contributed by avanitrachhadiya2155</script>", "e": 14740, "s": 12238, "text": null }, { "code": null, "e": 14767, "s": 14740, "text": "7th smallest element is 30" }, { "code": null, "e": 14839, "s": 14767, "text": "The codes above are contributed by RISHABH CHAUHAN.Complexity Analysis:" }, { "code": null, "e": 14986, "s": 14839, "text": "Time Complexity: The above solution involves following steps. Building a min-heap which takes O(n) timeHeapify k times which takes O(k Logn) time." }, { "code": null, "e": 15071, "s": 14986, "text": "Building a min-heap which takes O(n) timeHeapify k times which takes O(k Logn) time." }, { "code": null, "e": 15113, "s": 15071, "text": "Building a min-heap which takes O(n) time" }, { "code": null, "e": 15157, "s": 15113, "text": "Heapify k times which takes O(k Logn) time." }, { "code": null, "e": 15254, "s": 15157, "text": "Auxiliary Space: O(R), where R is the length of a row, as the Min-Heap stores one row at a time." }, { "code": null, "e": 15672, "s": 15254, "text": "The above code can be optimized to build a heap of size k when k is smaller than n. In that case, the kth smallest element must be in first k rows and k columns. We will soon be publishing more efficient algorithms for finding the kth smallest element. This article is compiled by Ravi Gupta. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above " }, { "code": null, "e": 15703, "s": 15672, "text": "Using inbuilt priority_queue :" }, { "code": null, "e": 15832, "s": 15703, "text": "By using a comparator, we can carry out custom comparison in priority_queue. We will use priority_queue<pair<int,int>> for this." }, { "code": null, "e": 15851, "s": 15832, "text": " Implementation : " }, { "code": null, "e": 15855, "s": 15851, "text": "C++" }, { "code": "// kth largest element in a 2d array sorted row-wise and// column-wise#include<bits/stdc++.h>using namespace std; int kthSmallest(int mat[4][4], int n, int k){ // USING LAMBDA FUNCTION // [=] IN LAMBDA FUNCTION IS FOR CAPTURING VARIABLES WHICH // ARE OUT OF SCOPE i.e. mat[r] // NOW, IT'LL COMPARE ELEMENTS OF HEAP BY ELEMENTS AT mat[first][second] // Capturing the value of mat by reference to prevent copying auto cmp = [&](pair<int,int> a,pair<int,int> b){ return mat[a.first][a.second] > mat[b.first][b.second]; }; //DECLARING priority_queue AND PUSHING FIRST ROW IN IT priority_queue<pair<int,int>,vector<pair<int,int>>,decltype(cmp)> pq(cmp); for(int i=0; i<n; i++){ pq.push({i,0}); } //RUNNING LOOP FOR (k-1) TIMES for(int i=1; i<k; i++){ auto p = pq.top(); pq.pop(); //AFTER POPPING, WE'LL PUSH NEXT ELEMENT OF THE ROW IN THE HEAP if(p.second+1 < n) pq.push({p.first,p.second + 1}); } // ON THE k'th ITERATION, pq.top() will be our answer. return mat[pq.top().first][pq.top().second];} // driver program to test above functionint main(){ int mat[4][4] = { { 10, 20, 30, 40 }, { 15, 25, 35, 45 }, { 25, 29, 37, 48 }, { 32, 33, 39, 50 }, }; cout << \"7th smallest element is \" << kthSmallest(mat, 4, 7); return 0;}", "e": 17233, "s": 15855, "text": null }, { "code": null, "e": 17260, "s": 17233, "text": "7th smallest element is 30" }, { "code": null, "e": 17288, "s": 17260, "text": "Time Complexity: O(n log n)" }, { "code": null, "e": 17310, "s": 17288, "text": "Auxiliary Space: O(n)" }, { "code": null, "e": 17393, "s": 17310, "text": "This approach uses binary search to iterate over possible solutions. We know that " }, { "code": null, "e": 17436, "s": 17393, "text": "answer >= mat[0][0]answer <= mat[N-1][N-1]" }, { "code": null, "e": 17456, "s": 17436, "text": "answer >= mat[0][0]" }, { "code": null, "e": 17480, "s": 17456, "text": "answer <= mat[N-1][N-1]" }, { "code": null, "e": 17732, "s": 17480, "text": "So we do a binary search on this range and in each iteration determine the no of elements greater than or equal to our current middle element. The elements greater than or equal to current element can be found in O( n logn ) time using binary search." }, { "code": null, "e": 17736, "s": 17732, "text": "C++" }, { "code": null, "e": 17741, "s": 17736, "text": "Java" }, { "code": null, "e": 17749, "s": 17741, "text": "Python3" }, { "code": null, "e": 17752, "s": 17749, "text": "C#" }, { "code": null, "e": 17763, "s": 17752, "text": "Javascript" }, { "code": "#include <bits/stdc++.h>using namespace std; // This returns count of elements in matrix less than of equal to numint getElementsGreaterThanOrEqual(int num, int n, int mat[4][4]) { int ans = 0; for (int i = 0; i < n; i++) { // if num is less than the first element then no more element in matrix // further are less than or equal to num if (mat[i][0] > num) { return ans; } // if num is greater than last element, it is greater than all elements // in that row if (mat[i][n - 1] <= num) { ans += n; continue; } // This contain the col index of last element in matrix less than of equal // to num int greaterThan = 0; for (int jump = n / 2; jump >= 1; jump /= 2) { while (greaterThan + jump < n && mat[i][greaterThan + jump] <= num) { greaterThan += jump; } } ans += greaterThan + 1; } return ans;} // returns kth smallest index in the matrixint kthSmallest(int mat[4][4], int n, int k) { // We know the answer lies between the first and the last element // So do a binary search on answer based on the number of elements // our current element is greater than the elements in the matrix int l = mat[0][0], r = mat[n - 1][n - 1]; while (l <= r) { int mid = l + (r - l) / 2; int greaterThanOrEqualMid = getElementsGreaterThanOrEqual(mid, n, mat); if (greaterThanOrEqualMid >= k) r = mid - 1; else l = mid + 1; } return l;} int main() { int n = 4; int mat[4][4] = { {10, 20, 30, 40}, {15, 25, 35, 45}, {25, 29, 37, 48}, {32, 33, 39, 50}, }; cout << \"7th smallest element is \" << kthSmallest(mat, 4, 7); return 0;}", "e": 19591, "s": 17763, "text": null }, { "code": "class GFG { // This returns count of elements in // matrix less than of equal to num static int getElementsGreaterThanOrEqual(int num, int n, int mat[][]) { int ans = 0; for (int i = 0; i < n; i++) { // if num is less than the first element // then no more element in matrix // further are less than or equal to num if (mat[i][0] > num) { return ans; } // if num is greater than last element, // it is greater than all elements // in that row if (mat[i][n - 1] <= num) { ans += n; continue; } // This contain the col index of last element // in matrix less than of equal // to num int greaterThan = 0; for (int jump = n / 2; jump >= 1; jump /= 2) { while (greaterThan + jump < n && mat[i][greaterThan + jump] <= num) { greaterThan += jump; } } ans += greaterThan + 1; } return ans; } // returns kth smallest index in the matrix static int kthSmallest(int mat[][], int n, int k) { // We know the answer lies between the first and the last element // So do a binary search on answer based on the number of elements // our current element is greater than the elements in the matrix int l = mat[0][0], r = mat[n - 1][n - 1]; while (l <= r) { int mid = l + (r - l) / 2; int greaterThanOrEqualMid = getElementsGreaterThanOrEqual(mid, n, mat); if (greaterThanOrEqualMid >= k) r = mid - 1; else l = mid + 1; } return l; } public static void main(String args[]) { int mat[][] = { { 10, 20, 30, 40 }, { 15, 25, 35, 45 }, { 25, 29, 37, 48 }, { 32, 33, 39, 50 }, }; System.out.println(\"7th smallest element is \" + kthSmallest(mat, 4, 7)); } } // This code is contributed by gfgking.", "e": 21448, "s": 19591, "text": null }, { "code": "# This returns count of elements in matrix# less than of equal to numdef getElementsGreaterThanOrEqual(num,n,mat): ans = 0 for i in range(n): # if num is less than the first element # then no more element in matrix # further are less than or equal to num if (mat[i][0] > num): return ans # if num is greater than last element, # it is greater than all elements # in that row if (mat[i][n - 1] <= num): ans += n continue # This contain the col index of last element # in matrix less than of equal # to num greaterThan = 0 jump = n // 2 while(jump >= 1): while (greaterThan + jump < n and mat[i][greaterThan + jump] <= num): greaterThan += jump jump //= 2 ans += greaterThan + 1 return ans # returns kth smallest index in the matrixdef kthSmallest(mat, n, k): # We know the answer lies between # the first and the last element # So do a binary search on answer # based on the number of elements # our current element is greater than # the elements in the matrix l,r = mat[0][0],mat[n - 1][n - 1] while (l <= r): mid = l + (r - l) // 2 greaterThanOrEqualMid = getElementsGreaterThanOrEqual(mid, n, mat) if (greaterThanOrEqualMid >= k): r = mid - 1 else: l = mid + 1 return l # driver coden = 4mat = [[10, 20, 30, 40],[15, 25, 35, 45],[25, 29, 37, 48],[32, 33, 39, 50]]print(f\"7th smallest element is {kthSmallest(mat, 4, 7)}\") # This code is contributed by shinjanpatra", "e": 23111, "s": 21448, "text": null }, { "code": "using System; public class GFG{ // This returns count of elements in // matrix less than of equal to num static int getElementsGreaterThanOrEqual(int num, int n, int [,]mat) { int ans = 0; for (int i = 0; i < n; i++) { // if num is less than the first element // then no more element in matrix // further are less than or equal to num if (mat[i,0] > num) { return ans; } // if num is greater than last element, // it is greater than all elements // in that row if (mat[i,n - 1] <= num) { ans += n; continue; } // This contain the col index of last element // in matrix less than of equal // to num int greaterThan = 0; for (int jump = n / 2; jump >= 1; jump /= 2) { while (greaterThan + jump < n && mat[i,greaterThan + jump] <= num) { greaterThan += jump; } } ans += greaterThan + 1; } return ans; } // returns kth smallest index in the matrix static int kthSmallest(int [,]mat, int n, int k) { // We know the answer lies between the first and the last element // So do a binary search on answer based on the number of elements // our current element is greater than the elements in the matrix int l = mat[0,0], r = mat[n - 1,n - 1]; while (l <= r) { int mid = l + (r - l) / 2; int greaterThanOrEqualMid = getElementsGreaterThanOrEqual(mid, n, mat); if (greaterThanOrEqualMid >= k) r = mid - 1; else l = mid + 1; } return l; } public static void Main(String []args) { int [,]mat = { { 10, 20, 30, 40 }, { 15, 25, 35, 45 }, { 25, 29, 37, 48 }, { 32, 33, 39, 50 }, }; Console.WriteLine(\"7th smallest element is \" + kthSmallest(mat, 4, 7)); } } // This code is contributed by 29AjayKumar", "e": 24960, "s": 23111, "text": null }, { "code": "<script> // This returns count of elements in matrix // less than of equal to num function getElementsGreaterThanOrEqual(num,n,mat) { let ans = 0 for (let i = 0; i < n; i++) { // if num is less than the first element // then no more element in matrix // further are less than or equal to num if (mat[i][0] > num) { return ans; } // if num is greater than last element, // it is greater than all elements // in that row if (mat[i][n - 1] <= num) { ans += n; continue; } // This contain the col index of last element // in matrix less than of equal // to num let greaterThan = 0; for (let jump = n / 2; jump >= 1; jump /= 2) { while (greaterThan + jump < n && mat[i][greaterThan + jump] <= num) { greaterThan += jump; } } ans += greaterThan + 1; } return ans; } // returns kth smallest index in the matrix function kthSmallest(mat,n,k) { // We know the answer lies between // the first and the last element // So do a binary search on answer // based on the number of elements // our current element is greater than // the elements in the matrix let l = mat[0][0], r = mat[n - 1][n - 1]; while (l <= r) { let mid = l + parseInt((r - l) / 2, 10); let greaterThanOrEqualMid = getElementsGreaterThanOrEqual(mid, n, mat); if (greaterThanOrEqualMid >= k) r = mid - 1; else l = mid + 1; } return l; } let n = 4; let mat = [ [10, 20, 30, 40], [15, 25, 35, 45], [25, 29, 37, 48], [32, 33, 39, 50], ]; document.write(\"7th smallest element is \" + kthSmallest(mat, 4, 7)); </script>", "e": 26995, "s": 24960, "text": null }, { "code": null, "e": 27004, "s": 26995, "text": "Output: " }, { "code": null, "e": 27031, "s": 27004, "text": "7th smallest element is 30" }, { "code": null, "e": 27051, "s": 27031, "text": "Complexity Analysis" }, { "code": null, "e": 27084, "s": 27051, "text": "Time Complexity : O( y * n*logn)" }, { "code": null, "e": 27133, "s": 27084, "text": "Where y = log( abs(Mat[0][0] - Mat[n-1][n-1]) )" }, { "code": null, "e": 27333, "s": 27133, "text": "We call the getElementsGreaterThanOrEqual function log ( abs(Mat[0][0] – Mat[n-1][n-1]) ) timesTime complexity of getElementsGreaterThanOrEqual is O(n logn) since there we do binary search n times." }, { "code": null, "e": 27431, "s": 27333, "text": "We call the getElementsGreaterThanOrEqual function log ( abs(Mat[0][0] – Mat[n-1][n-1]) ) times" }, { "code": null, "e": 27534, "s": 27431, "text": "Time complexity of getElementsGreaterThanOrEqual is O(n logn) since there we do binary search n times." }, { "code": null, "e": 27556, "s": 27534, "text": "Auxiliary Space: O(1)" }, { "code": null, "e": 27569, "s": 27556, "text": "USING ARRAY:" }, { "code": null, "e": 27740, "s": 27569, "text": "We will make a new array and will copy all the contents of matrix in this array. After that we will sort that array and find kth smallest element. This will be so easier." }, { "code": null, "e": 27744, "s": 27740, "text": "C++" }, { "code": null, "e": 27749, "s": 27744, "text": "Java" }, { "code": null, "e": 27757, "s": 27749, "text": "Python3" }, { "code": null, "e": 27760, "s": 27757, "text": "C#" }, { "code": null, "e": 27771, "s": 27760, "text": "Javascript" }, { "code": "// C++ code to implement the approach#include <bits/stdc++.h>using namespace std; int kthSmallest(int mat[4][4], int n, int k){ int a[n*n]; int v = 0; for(int i = 0; i < n; i++) { for(int j = 0; j < n; j++) { a[v] = mat[i][j]; v++; } } sort(a, a + (n*n)); int result = a[k - 1]; return result;} // Driver codeint main(){ int mat[4][4] = { { 10, 20, 30, 40 }, { 15, 25, 35, 45 }, { 25, 29, 37, 48 }, { 32, 33, 39, 50 } }; int res = kthSmallest(mat, 4, 7); cout << \"7th smallest element is \" << res; return 0;} // This code is contributed by sanjoy_62.", "e": 28412, "s": 27771, "text": null }, { "code": "/*package whatever //do not write package name here */ import java.io.*;import java.util.*;class GFG { public static void main (String[] args) { int mat[][] = { { 10, 20, 30, 40 }, { 15, 25, 35, 45 }, { 25, 29, 37, 48 }, { 32, 33, 39, 50 } }; int res = kthSmallest(mat, 4, 7); System.out.print(\"7th smallest element is \"+ res); } static int kthSmallest(int[][]mat,int n,int k) { int[] a=new int[n*n]; int v=0; for(int i=0;i<n;i++){ for(int j=0;j<n;j++){ a[v]=mat[i][j]; v++; } } Arrays.sort(a); int result=a[k-1]; return result; }}", "e": 29165, "s": 28412, "text": null }, { "code": "# Python program to implement above approachdef kthSmallest(mat, n, k): a = [0 for i in range(n*n)] v=0 for i in range(n): for j in range(n): a[v] = mat[i][j] v += 1 a.sort() result = a[k - 1] return result # driver program mat = [ [ 10, 20, 30, 40 ], [ 15, 25, 35, 45 ], [ 25, 29, 37, 48 ], [ 32, 33, 39, 50 ] ]res = kthSmallest(mat, 4, 7) print(\"7th smallest element is \"+ str(res)) # This code is contributed by shinjanpatra", "e": 29716, "s": 29165, "text": null }, { "code": "/*package whatever //do not write package name here */using System;using System.Collections.Generic; public class GFG { public static void Main(String[] args) { int [,]mat = { { 10, 20, 30, 40 }, { 15, 25, 35, 45 }, { 25, 29, 37, 48 }, { 32, 33, 39, 50 } }; int res = kthSmallest(mat, 4, 7); Console.Write(\"7th smallest element is \"+ res); } static int kthSmallest(int[,]mat, int n, int k) { int[] a = new int[n*n]; int v = 0; for(int i = 0; i < n; i++) { for(int j = 0; j < n; j++) { a[v] = mat[i, j]; v++; } } Array.Sort(a); int result = a[k - 1]; return result; }} // This code is contributed by 29AjayKumar", "e": 30451, "s": 29716, "text": null }, { "code": "<script> // JavaScript program to implement above approachfunction kthSmallest(mat, n, k){ let a = new Array(n*n) let v=0 for(let i = 0; i < n; i++) { for(let j = 0; j < n; j++) { a[v] = mat[i][j]; v++; } } a.sort(); let result = a[k - 1]; return result;} // driver program let mat = [ [ 10, 20, 30, 40 ], [ 15, 25, 35, 45 ], [ 25, 29, 37, 48 ], [ 32, 33, 39, 50 ] ]let res = kthSmallest(mat, 4, 7) document.write(\"7th smallest element is \"+ res,\"</br>\") // This code is contributed by shinjanpatra </script>", "e": 31099, "s": 30451, "text": null }, { "code": null, "e": 31126, "s": 31099, "text": "7th smallest element is 30" }, { "code": null, "e": 31172, "s": 31126, "text": "Time Complexity: O(n2) Auxiliary Space: O(n2)" }, { "code": null, "e": 31202, "s": 31172, "text": "Using Priority queue approach" }, { "code": null, "e": 31208, "s": 31202, "text": "C++14" }, { "code": null, "e": 31213, "s": 31208, "text": "Java" }, { "code": null, "e": 31221, "s": 31213, "text": "Python3" }, { "code": null, "e": 31224, "s": 31221, "text": "C#" }, { "code": "#include <bits/stdc++.h>using namespace std;int kthSmallest(vector<vector<int>>& matrix, int k) { //n = size of matrix int i,j,n=matrix.size(); //using built-in priority queue which acts as max Heap i.e. largest element will be on top //Kth smallest element can also be seen as largest element in a priority queue of size k //By this logic we pop elements from priority queue when its size becomes greater than k //thus top of priority queue is kth smallest element in matrix priority_queue<int> maxH; if(k==1) return matrix[0][0]; for(i=0;i<n;i++) { for(j=0;j<n;j++) { maxH.push(matrix[i][j]); if(maxH.size()>k) maxH.pop(); } } return maxH.top();}int main() { vector<vector<int>> matrix = {{1,5,9},{10,11,13},{12,13,15}}; int k = 8; cout << \"8th smallest element is \" << kthSmallest(matrix,k); return 0;}", "e": 32098, "s": 31224, "text": null }, { "code": "import java.util.*;public class Main { public static int kthSmallest(int[][] matrix, int k) { // n = size of matrix int i, j, n = matrix.length; // using built-in priority queue which acts as max // Heap i.e. largest element will be on top // Kth smallest element can also be seen as largest // element in a priority queue of size k By this // logic we pop elements from priority queue when // its size becomes greater than k thus top of // priority queue is kth smallest element in matrix PriorityQueue<Integer> maxH = new PriorityQueue<>( Collections.reverseOrder()); if (k == 1) return matrix[0][0]; for (i = 0; i < n; i++) { for (j = 0; j < n; j++) { maxH.add(matrix[i][j]); if (maxH.size() > k) maxH.poll(); } } return maxH.peek(); } public static void main(String[] args) { int[][] matrix = { { 1, 5, 9 }, { 10, 11, 13 }, { 12, 13, 15 } }; int k = 8; System.out.print(\"8th smallest element is \" + kthSmallest(matrix, k)); }} // This code is contributed by tapeshdua420.", "e": 33245, "s": 32098, "text": null }, { "code": "import heapq def kthSmallest(matrix, k): # n = size of matrix n = len(matrix) # using built-in priority queue which acts as max Heap i.e. largest element will be on top # Kth smallest element can also be seen as largest element in a priority queue of size k # By this logic we pop elements from priority queue when its size becomes greater than k # thus top of priority queue is kth smallest element in matrix maxH = [] for i in range(n): for j in range(n): heapq.heappush(maxH, -matrix[i][j]) if len(maxH) > k: heapq.heappop(maxH) return -maxH[0] matrix = [[1, 5, 9], [10, 11, 13], [12, 13, 15]]k = 8print(\"8th smallest element is\", kthSmallest(matrix, k)) # This code is comtributed by Tapesh (tapeshdua420)", "e": 34030, "s": 33245, "text": null }, { "code": "using System;using System.Collections.Generic; public class GFG { public static int kthSmallest(int[,] matrix, int k) { // n = size of matrix int i, j, n = matrix.GetLength(0); // using built-in priority queue which acts as max // Heap i.e. largest element will be on top // Kth smallest element can also be seen as largest // element in a priority queue of size k By this // logic we pop elements from priority queue when // its size becomes greater than k thus top of // priority queue is kth smallest element in matrix List<int> maxH = new List<int>(); if (k == 1) return matrix[0,0]; for (i = 0; i < n; i++) { for (j = 0; j < n; j++) { maxH.Add(matrix[i,j]); if (maxH.Count > k){ maxH.Sort((a, b) => b.CompareTo(a)); maxH.RemoveAt(0); } } } maxH.Sort((a, b) => b.CompareTo(a)); return maxH[0]; } public static void Main(String[] args) { int[,] matrix = { { 1, 5, 9 }, { 10, 11, 13 }, { 12, 13, 15 } }; int k = 8; Console.Write(\"8th smallest element is \" + kthSmallest(matrix, k)); }} // This code is contributed by shikhasingrajput", "e": 35241, "s": 34030, "text": null }, { "code": null, "e": 35268, "s": 35241, "text": "8th smallest element is 13" }, { "code": null, "e": 35313, "s": 35268, "text": "Time Complexity: O(n2) Auxiliary Space: O(n)" }, { "code": null, "e": 35481, "s": 35313, "text": "This article is contributed by Aarti_Rathi. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above" }, { "code": null, "e": 35493, "s": 35481, "text": "sanjeev2552" }, { "code": null, "e": 35504, "s": 35493, "text": "andrew1234" }, { "code": null, "e": 35517, "s": 35504, "text": "Akanksha_Rai" }, { "code": null, "e": 35537, "s": 35517, "text": "nikhil kumar sharma" }, { "code": null, "e": 35552, "s": 35537, "text": "amit143katiyar" }, { "code": null, "e": 35565, "s": 35552, "text": "adankitdutta" }, { "code": null, "e": 35576, "s": 35565, "text": "akscodebay" }, { "code": null, "e": 35589, "s": 35576, "text": "himankgoel12" }, { "code": null, "e": 35602, "s": 35589, "text": "mohitawachar" }, { "code": null, "e": 35620, "s": 35602, "text": "sinhadiptiprakash" }, { "code": null, "e": 35644, "s": 35620, "text": "drsmolderrishabhchauhan" }, { "code": null, "e": 35665, "s": 35644, "text": "avanitrachhadiya2155" }, { "code": null, "e": 35684, "s": 35665, "text": "vaibhavrabadiya117" }, { "code": null, "e": 35699, "s": 35684, "text": "kumaratishek22" }, { "code": null, "e": 35710, "s": 35699, "text": "ayushh2023" }, { "code": null, "e": 35722, "s": 35710, "text": "29AjayKumar" }, { "code": null, "e": 35730, "s": 35722, "text": "gfgking" }, { "code": null, "e": 35743, "s": 35730, "text": "simmytarika5" }, { "code": null, "e": 35756, "s": 35743, "text": "shinjanpatra" }, { "code": null, "e": 35765, "s": 35756, "text": "aj_00_11" }, { "code": null, "e": 35775, "s": 35765, "text": "sanjoy_62" }, { "code": null, "e": 35788, "s": 35775, "text": "sanchita0500" }, { "code": null, "e": 35801, "s": 35788, "text": "tapeshdua420" }, { "code": null, "e": 35815, "s": 35801, "text": "codewithrathi" }, { "code": null, "e": 35832, "s": 35815, "text": "shikhasingrajput" }, { "code": null, "e": 35841, "s": 35832, "text": "Accolite" }, { "code": null, "e": 35848, "s": 35841, "text": "Amazon" }, { "code": null, "e": 35865, "s": 35848, "text": "Order-Statistics" }, { "code": null, "e": 35870, "s": 35865, "text": "Heap" }, { "code": null, "e": 35877, "s": 35870, "text": "Matrix" }, { "code": null, "e": 35887, "s": 35877, "text": "Searching" }, { "code": null, "e": 35896, "s": 35887, "text": "Accolite" }, { "code": null, "e": 35903, "s": 35896, "text": "Amazon" }, { "code": null, "e": 35913, "s": 35903, "text": "Searching" }, { "code": null, "e": 35920, "s": 35913, "text": "Matrix" }, { "code": null, "e": 35925, "s": 35920, "text": "Heap" }, { "code": null, "e": 36023, "s": 35925, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 36032, "s": 36023, "text": "HeapSort" }, { "code": null, "e": 36064, "s": 36032, "text": "Introduction to Data Structures" }, { "code": null, "e": 36076, "s": 36064, "text": "Binary Heap" }, { "code": null, "e": 36107, "s": 36076, "text": "Huffman Coding | Greedy Algo-3" }, { "code": null, "e": 36167, "s": 36107, "text": "Sliding Window Maximum (Maximum of all subarrays of size k)" }, { "code": null, "e": 36198, "s": 36167, "text": "Rat in a Maze | Backtracking-2" }, { "code": null, "e": 36255, "s": 36198, "text": "Find the longest path in a matrix with given constraints" }, { "code": null, "e": 36290, "s": 36255, "text": "Matrix Chain Multiplication | DP-8" }, { "code": null, "e": 36326, "s": 36290, "text": "Print a given matrix in spiral form" } ]
Sum of all parts of a square Matrix divided by its diagonals
22 Jun, 2021 Given a 2D matrix arr[][] of N*N dimensions, the task is to find the sum of elements of all four parts of the matrix divided by the diagonals without including the diagonal elements in any of the four parts.Example: Input: arr[][] = { {1, 2, 3}, {4, 5, 6}, {7, 8, 9} } Output: 2 4 6 8 Explanation: (1, 5, 9) and (3, 5, 7) are diagonals of arr[][] matrix. Therefore sum of parts are: Top = 2 Left = 4 Right = 6 Bottom = 8Input: arr[][] = { {1, 3, 1, 5}, {2, 2, 4, 1}, {5, 0, 2, 3}, { 1, 3, 3, 5} } Output: 4 7 4 6 Explanation: (1, 2, 2, 5) and (5, 4, 0, 1) are diagonals of arr[][] matrix. Therefore sum of parts are: Top = 3 + 1 = 4 Left = 2 + 5 = 7 Right = 1 + 3 = 4 Bottom = 3 + 3 = 6 Approach: As shown in the above figure, After the matrix of size NxN is divided by diagonals. We observe the following properties: If sum of index of row and column is less than N – 1 then, it belongs to either Top part or Left part. If column index is greater than row index it belongs to Top part.Else it belongs to Left part.Else it belongs to either Right part or Down part.If column index is greater than row index it belongs to Right part.Else it belongs to Down part. If sum of index of row and column is less than N – 1 then, it belongs to either Top part or Left part. If column index is greater than row index it belongs to Top part.Else it belongs to Left part. If column index is greater than row index it belongs to Top part. Else it belongs to Left part. Else it belongs to either Right part or Down part.If column index is greater than row index it belongs to Right part.Else it belongs to Down part. If column index is greater than row index it belongs to Right part. Else it belongs to Down part. 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 calculate the// sum of all parts of matrixvoid SumOfPartsOfMetrics(int* arr, int N){ // To store the sum of all four // parts of the diagonals int top, bottom, left, right; // Initialise respective sum // as zero top = bottom = right = left = 0; // Traversing the matrix for (int i = 0; i < N; i++) { for (int j = 0; j < N; j++) { // If i + j < N -1 // then it belongs to // top or left if (i + j < N - 1 && i != j) { // Belongs to top if (i < j) { top += (arr + i * N)[j]; } // Belongs to left else { left += (arr + i * N)[j]; } } // If i+j > N - 1 then // it belongs to right // or bottom else if (i + j > N - 1 && i != j) { // Belongs to right if (i > j) { bottom += (arr + i * N)[j]; } // Belongs to bottom else { right += (arr + i * N)[j]; } } } } cout << top << ' ' << left << ' ' << right << ' ' << bottom << endl;} // Driver Codeint main(){ int N = 4; int arr[N][N] = { { 1, 3, 1, 5 }, { 2, 2, 4, 1 }, { 5, 0, 2, 3 }, { 1, 3, 3, 5 } }; // Function call to find print // sum of al parts SumOfPartsOfMetrics((int*)arr, N); return 0;} // Java program for the above approachclass GFG { // Function to calculate the// sum of all parts of matrixstatic void SumOfPartsOfMetrics(int [][]arr, int N){ // To store the sum of all four // parts of the diagonals // Initialise respective sum // as zero int top = 0, bottom = 0; int left = 0, right = 0; // Traversing the matrix for(int i = 0; i < N; i++) { for(int j = 0; j < N; j++) { // If i + j < N -1 // then it belongs to // top or left if (i + j < N - 1 && i != j) { // Belongs to top if (i < j) { top += arr[i][j]; } // Belongs to left else { left += arr[i][j]; } } // If i+j > N - 1 then // it belongs to right // or bottom else if (i + j > N - 1 && i != j) { // Belongs to right if (i > j) { bottom += arr[i][j]; } // Belongs to bottom else { right += arr[i][j]; } } } } System.out.println(top + " " + left + " " + right + " " + bottom);} // Driver Codepublic static void main (String[] args){ int N = 4; int arr[][] = { { 1, 3, 1, 5 }, { 2, 2, 4, 1 }, { 5, 0, 2, 3 }, { 1, 3, 3, 5 } }; // Function call to find print // sum of al parts SumOfPartsOfMetrics(arr, N);}} // This code is contributed by AnkitRai01 # Python3 program for the above approach # Function to calculate the# sum of all parts of matrixdef SumOfPartsOfMetrics(arr, N): # To store the sum of all four # parts of the diagonals # Initialise respective sum # as zero top = bottom = right = left = 0; # Traversing the matrix for i in range(N): for j in range(N): # If i + j < N -1 # then it belongs to # top or left if (i + j < N - 1 and i != j): # Belongs to top if (i < j): top += arr[i][j]; # Belongs to left else: left += arr[i][j]; # If i+j > N - 1 then # it belongs to right # or bottom elif (i + j > N - 1 and i != j): # Belongs to right if (i > j): bottom += arr[i][j]; # Belongs to bottom else: right += arr[i][j]; print(top, left, right, bottom); # Driver Codeif __name__ == "__main__": N = 4; arr = [ [ 1, 3, 1, 5 ], [ 2, 2, 4, 1 ], [ 5, 0, 2, 3 ], [ 1, 3, 3, 5 ] ]; # Function call to find print # sum of al parts SumOfPartsOfMetrics(arr, N); # This code is contributed by AnkitRai01 // C# program for the above approachusing System; class GFG { // Function to calculate the// sum of all parts of matrixstatic void SumOfPartsOfMetrics(int [,]arr, int N){ // To store the sum of all four // parts of the diagonals // Initialise respective sum // as zero int top = 0, bottom = 0; int left = 0, right = 0; // Traversing the matrix for(int i = 0; i < N; i++) { for(int j = 0; j < N; j++) { // If i + j < N -1 // then it belongs to // top or left if (i + j < N - 1 && i != j) { // Belongs to top if (i < j) { top += arr[i, j]; } // Belongs to left else { left += arr[i, j]; } } // If i+j > N - 1 then // it belongs to right // or bottom else if (i + j > N - 1 && i != j) { // Belongs to right if (i > j) { bottom += arr[i, j]; } // Belongs to bottom else { right += arr[i, j]; } } } } Console.WriteLine(top + " " + left + " " + right + " " + bottom);} // Driver Codepublic static void Main (string[] args){ int N = 4; int [,]arr = { { 1, 3, 1, 5 }, { 2, 2, 4, 1 }, { 5, 0, 2, 3 }, { 1, 3, 3, 5 } }; // Function call to find print // sum of al parts SumOfPartsOfMetrics(arr, N);}} // This code is contributed by AnkitRai01 <script>// Javascript program for the above approach // Function to calculate the// sum of all parts of matrixfunction SumOfPartsOfMetrics(arr, N){ // To store the sum of all four // parts of the diagonals let top, bottom, left, right; // Initialise respective sum // as zero top = bottom = right = left = 0; // Traversing the matrix for (let i = 0; i < N; i++) { for (let j = 0; j < N; j++) { // If i + j < N -1 // then it belongs to // top or left if (i + j < N - 1 && i != j) { // Belongs to top if (i < j) { top += arr[i][j]; } // Belongs to left else { left += arr[i][j]; } } // If i+j > N - 1 then // it belongs to right // or bottom else if (i + j > N - 1 && i != j) { // Belongs to right if (i > j) { bottom += arr[i][j]; } // Belongs to bottom else { right += arr[i][j]; } } } } document.write(top + ' ' + left + ' ' + right + ' ' + bottom + "<br>");} // Driver Code let N = 4; let arr = [ [ 1, 3, 1, 5 ], [ 2, 2, 4, 1 ], [ 5, 0, 2, 3 ], [ 1, 3, 3, 5 ] ]; // Function call to find print // sum of al parts SumOfPartsOfMetrics(arr, N); // This code is contributed by rishavmahato348.</script> 4 7 4 6 Time Complexity: O(N2) ankthon rishavmahato348 adnanirshad158 Competitive Programming Matrix Matrix Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n22 Jun, 2021" }, { "code": null, "e": 246, "s": 28, "text": "Given a 2D matrix arr[][] of N*N dimensions, the task is to find the sum of elements of all four parts of the matrix divided by the diagonals without including the diagonal elements in any of the four parts.Example: " }, { "code": null, "e": 719, "s": 246, "text": "Input: arr[][] = { {1, 2, 3}, {4, 5, 6}, {7, 8, 9} } Output: 2 4 6 8 Explanation: (1, 5, 9) and (3, 5, 7) are diagonals of arr[][] matrix. Therefore sum of parts are: Top = 2 Left = 4 Right = 6 Bottom = 8Input: arr[][] = { {1, 3, 1, 5}, {2, 2, 4, 1}, {5, 0, 2, 3}, { 1, 3, 3, 5} } Output: 4 7 4 6 Explanation: (1, 2, 2, 5) and (5, 4, 0, 1) are diagonals of arr[][] matrix. Therefore sum of parts are: Top = 3 + 1 = 4 Left = 2 + 5 = 7 Right = 1 + 3 = 4 Bottom = 3 + 3 = 6 " }, { "code": null, "e": 733, "s": 721, "text": "Approach: " }, { "code": null, "e": 856, "s": 733, "text": "As shown in the above figure, After the matrix of size NxN is divided by diagonals. We observe the following properties: " }, { "code": null, "e": 1200, "s": 856, "text": "If sum of index of row and column is less than N – 1 then, it belongs to either Top part or Left part. If column index is greater than row index it belongs to Top part.Else it belongs to Left part.Else it belongs to either Right part or Down part.If column index is greater than row index it belongs to Right part.Else it belongs to Down part." }, { "code": null, "e": 1398, "s": 1200, "text": "If sum of index of row and column is less than N – 1 then, it belongs to either Top part or Left part. If column index is greater than row index it belongs to Top part.Else it belongs to Left part." }, { "code": null, "e": 1464, "s": 1398, "text": "If column index is greater than row index it belongs to Top part." }, { "code": null, "e": 1494, "s": 1464, "text": "Else it belongs to Left part." }, { "code": null, "e": 1641, "s": 1494, "text": "Else it belongs to either Right part or Down part.If column index is greater than row index it belongs to Right part.Else it belongs to Down part." }, { "code": null, "e": 1709, "s": 1641, "text": "If column index is greater than row index it belongs to Right part." }, { "code": null, "e": 1739, "s": 1709, "text": "Else it belongs to Down part." }, { "code": null, "e": 1792, "s": 1739, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 1796, "s": 1792, "text": "C++" }, { "code": null, "e": 1801, "s": 1796, "text": "Java" }, { "code": null, "e": 1809, "s": 1801, "text": "Python3" }, { "code": null, "e": 1812, "s": 1809, "text": "C#" }, { "code": null, "e": 1823, "s": 1812, "text": "Javascript" }, { "code": "// C++ program for the above approach#include \"bits/stdc++.h\"using namespace std; // Function to calculate the// sum of all parts of matrixvoid SumOfPartsOfMetrics(int* arr, int N){ // To store the sum of all four // parts of the diagonals int top, bottom, left, right; // Initialise respective sum // as zero top = bottom = right = left = 0; // Traversing the matrix for (int i = 0; i < N; i++) { for (int j = 0; j < N; j++) { // If i + j < N -1 // then it belongs to // top or left if (i + j < N - 1 && i != j) { // Belongs to top if (i < j) { top += (arr + i * N)[j]; } // Belongs to left else { left += (arr + i * N)[j]; } } // If i+j > N - 1 then // it belongs to right // or bottom else if (i + j > N - 1 && i != j) { // Belongs to right if (i > j) { bottom += (arr + i * N)[j]; } // Belongs to bottom else { right += (arr + i * N)[j]; } } } } cout << top << ' ' << left << ' ' << right << ' ' << bottom << endl;} // Driver Codeint main(){ int N = 4; int arr[N][N] = { { 1, 3, 1, 5 }, { 2, 2, 4, 1 }, { 5, 0, 2, 3 }, { 1, 3, 3, 5 } }; // Function call to find print // sum of al parts SumOfPartsOfMetrics((int*)arr, N); return 0;}", "e": 3500, "s": 1823, "text": null }, { "code": "// Java program for the above approachclass GFG { // Function to calculate the// sum of all parts of matrixstatic void SumOfPartsOfMetrics(int [][]arr, int N){ // To store the sum of all four // parts of the diagonals // Initialise respective sum // as zero int top = 0, bottom = 0; int left = 0, right = 0; // Traversing the matrix for(int i = 0; i < N; i++) { for(int j = 0; j < N; j++) { // If i + j < N -1 // then it belongs to // top or left if (i + j < N - 1 && i != j) { // Belongs to top if (i < j) { top += arr[i][j]; } // Belongs to left else { left += arr[i][j]; } } // If i+j > N - 1 then // it belongs to right // or bottom else if (i + j > N - 1 && i != j) { // Belongs to right if (i > j) { bottom += arr[i][j]; } // Belongs to bottom else { right += arr[i][j]; } } } } System.out.println(top + \" \" + left + \" \" + right + \" \" + bottom);} // Driver Codepublic static void main (String[] args){ int N = 4; int arr[][] = { { 1, 3, 1, 5 }, { 2, 2, 4, 1 }, { 5, 0, 2, 3 }, { 1, 3, 3, 5 } }; // Function call to find print // sum of al parts SumOfPartsOfMetrics(arr, N);}} // This code is contributed by AnkitRai01", "e": 5299, "s": 3500, "text": null }, { "code": "# Python3 program for the above approach # Function to calculate the# sum of all parts of matrixdef SumOfPartsOfMetrics(arr, N): # To store the sum of all four # parts of the diagonals # Initialise respective sum # as zero top = bottom = right = left = 0; # Traversing the matrix for i in range(N): for j in range(N): # If i + j < N -1 # then it belongs to # top or left if (i + j < N - 1 and i != j): # Belongs to top if (i < j): top += arr[i][j]; # Belongs to left else: left += arr[i][j]; # If i+j > N - 1 then # it belongs to right # or bottom elif (i + j > N - 1 and i != j): # Belongs to right if (i > j): bottom += arr[i][j]; # Belongs to bottom else: right += arr[i][j]; print(top, left, right, bottom); # Driver Codeif __name__ == \"__main__\": N = 4; arr = [ [ 1, 3, 1, 5 ], [ 2, 2, 4, 1 ], [ 5, 0, 2, 3 ], [ 1, 3, 3, 5 ] ]; # Function call to find print # sum of al parts SumOfPartsOfMetrics(arr, N); # This code is contributed by AnkitRai01", "e": 6664, "s": 5299, "text": null }, { "code": "// C# program for the above approachusing System; class GFG { // Function to calculate the// sum of all parts of matrixstatic void SumOfPartsOfMetrics(int [,]arr, int N){ // To store the sum of all four // parts of the diagonals // Initialise respective sum // as zero int top = 0, bottom = 0; int left = 0, right = 0; // Traversing the matrix for(int i = 0; i < N; i++) { for(int j = 0; j < N; j++) { // If i + j < N -1 // then it belongs to // top or left if (i + j < N - 1 && i != j) { // Belongs to top if (i < j) { top += arr[i, j]; } // Belongs to left else { left += arr[i, j]; } } // If i+j > N - 1 then // it belongs to right // or bottom else if (i + j > N - 1 && i != j) { // Belongs to right if (i > j) { bottom += arr[i, j]; } // Belongs to bottom else { right += arr[i, j]; } } } } Console.WriteLine(top + \" \" + left + \" \" + right + \" \" + bottom);} // Driver Codepublic static void Main (string[] args){ int N = 4; int [,]arr = { { 1, 3, 1, 5 }, { 2, 2, 4, 1 }, { 5, 0, 2, 3 }, { 1, 3, 3, 5 } }; // Function call to find print // sum of al parts SumOfPartsOfMetrics(arr, N);}} // This code is contributed by AnkitRai01", "e": 8454, "s": 6664, "text": null }, { "code": "<script>// Javascript program for the above approach // Function to calculate the// sum of all parts of matrixfunction SumOfPartsOfMetrics(arr, N){ // To store the sum of all four // parts of the diagonals let top, bottom, left, right; // Initialise respective sum // as zero top = bottom = right = left = 0; // Traversing the matrix for (let i = 0; i < N; i++) { for (let j = 0; j < N; j++) { // If i + j < N -1 // then it belongs to // top or left if (i + j < N - 1 && i != j) { // Belongs to top if (i < j) { top += arr[i][j]; } // Belongs to left else { left += arr[i][j]; } } // If i+j > N - 1 then // it belongs to right // or bottom else if (i + j > N - 1 && i != j) { // Belongs to right if (i > j) { bottom += arr[i][j]; } // Belongs to bottom else { right += arr[i][j]; } } } } document.write(top + ' ' + left + ' ' + right + ' ' + bottom + \"<br>\");} // Driver Code let N = 4; let arr = [ [ 1, 3, 1, 5 ], [ 2, 2, 4, 1 ], [ 5, 0, 2, 3 ], [ 1, 3, 3, 5 ] ]; // Function call to find print // sum of al parts SumOfPartsOfMetrics(arr, N); // This code is contributed by rishavmahato348.</script>", "e": 10068, "s": 8454, "text": null }, { "code": null, "e": 10076, "s": 10068, "text": "4 7 4 6" }, { "code": null, "e": 10102, "s": 10078, "text": "Time Complexity: O(N2) " }, { "code": null, "e": 10110, "s": 10102, "text": "ankthon" }, { "code": null, "e": 10126, "s": 10110, "text": "rishavmahato348" }, { "code": null, "e": 10141, "s": 10126, "text": "adnanirshad158" }, { "code": null, "e": 10165, "s": 10141, "text": "Competitive Programming" }, { "code": null, "e": 10172, "s": 10165, "text": "Matrix" }, { "code": null, "e": 10179, "s": 10172, "text": "Matrix" } ]
Python Selenium – Find Button by text
03 Mar, 2021 In this article, let’s discuss how to find a button by text using selenium. See the below example to get an idea about the meaning of the finding button by text. Example: URL: https://html.com/tags/button/ We need to find the “CLICK ME!” button using the text “Click me!”. Selenium: The selenium package is used to automate web browser interaction from Python. It is an open-source tool primarily used for testing. Run the following command in the terminal to install this library: pip install selenium Setup Web Drivers: Web Driver is a package to interact with a Web Browser. You can install any Web Driver according to your browser choice. Install any one of them using the given links- Here, we are going to use ChromeDriver. Find xpath of the button: Method 1: Using Inspect ElementRight Click on the element you are trying to find the xpath. Select the “Inspect” option. Right click on the highlighted area on the console. Go to Copy xpath Method 2: Using Chrome Extension to find xpath easily: We can easily find xpath of an element using a Chrome extension like SelectorGadget. Approach: Import Selenium and time library Set the Web Driver path with the location where you have downloaded the WebDriverExample- “C:\\chromedriver.exe” Call driver.get() function to navigate to a particular URL. Call time.sleep() function to wait for the driver to completely load the webpage. Use driver.find_element_by_xpath() method to find the button using xpath. Finding button by text-(i) Using normalize-space() method:driver.find_element_by_xpath(‘//button[normalize-space()=”Click me!”]’)(ii) Using text() method:driver.find_element_by_xpath(‘//button’)Note: It is recommended to use normalize-space() method because it trim the left and right side spaces. It is possible that there can be spaces present at the start or at the end of the target text. Lastly close the driver using driver.close() function. Implementation: Python3 # Import Libraryfrom selenium import webdriverimport time # set webdriver path here it may vary# Its the location where you have downloaded the ChromeDriverdriver = webdriver.Chrome(executable_path=r"C:\\chromedriver.exe") # Get the target URLdriver.get('https://html.com/tags/button/') # Wait for 5 seconds to load the webpage completelytime.sleep(5) # Find the button using textdriver.find_element_by_xpath('//button[normalize-space()="Click me!"]').click() time.sleep(5) # Close the driverdriver.close() Output: Picked Python Selenium-Exercises Python-selenium 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 Convert integer to string in Python
[ { "code": null, "e": 52, "s": 24, "text": "\n03 Mar, 2021" }, { "code": null, "e": 214, "s": 52, "text": "In this article, let’s discuss how to find a button by text using selenium. See the below example to get an idea about the meaning of the finding button by text." }, { "code": null, "e": 223, "s": 214, "text": "Example:" }, { "code": null, "e": 258, "s": 223, "text": "URL: https://html.com/tags/button/" }, { "code": null, "e": 325, "s": 258, "text": "We need to find the “CLICK ME!” button using the text “Click me!”." }, { "code": null, "e": 534, "s": 325, "text": "Selenium: The selenium package is used to automate web browser interaction from Python. It is an open-source tool primarily used for testing. Run the following command in the terminal to install this library:" }, { "code": null, "e": 555, "s": 534, "text": "pip install selenium" }, { "code": null, "e": 574, "s": 555, "text": "Setup Web Drivers:" }, { "code": null, "e": 742, "s": 574, "text": "Web Driver is a package to interact with a Web Browser. You can install any Web Driver according to your browser choice. Install any one of them using the given links-" }, { "code": null, "e": 782, "s": 742, "text": "Here, we are going to use ChromeDriver." }, { "code": null, "e": 808, "s": 782, "text": "Find xpath of the button:" }, { "code": null, "e": 930, "s": 808, "text": "Method 1: Using Inspect ElementRight Click on the element you are trying to find the xpath. Select the “Inspect” option. " }, { "code": null, "e": 1000, "s": 930, "text": "Right click on the highlighted area on the console. Go to Copy xpath " }, { "code": null, "e": 1141, "s": 1000, "text": "Method 2: Using Chrome Extension to find xpath easily: We can easily find xpath of an element using a Chrome extension like SelectorGadget. " }, { "code": null, "e": 1151, "s": 1141, "text": "Approach:" }, { "code": null, "e": 1184, "s": 1151, "text": "Import Selenium and time library" }, { "code": null, "e": 1297, "s": 1184, "text": "Set the Web Driver path with the location where you have downloaded the WebDriverExample- “C:\\\\chromedriver.exe”" }, { "code": null, "e": 1357, "s": 1297, "text": "Call driver.get() function to navigate to a particular URL." }, { "code": null, "e": 1439, "s": 1357, "text": "Call time.sleep() function to wait for the driver to completely load the webpage." }, { "code": null, "e": 1513, "s": 1439, "text": "Use driver.find_element_by_xpath() method to find the button using xpath." }, { "code": null, "e": 1906, "s": 1513, "text": "Finding button by text-(i) Using normalize-space() method:driver.find_element_by_xpath(‘//button[normalize-space()=”Click me!”]’)(ii) Using text() method:driver.find_element_by_xpath(‘//button’)Note: It is recommended to use normalize-space() method because it trim the left and right side spaces. It is possible that there can be spaces present at the start or at the end of the target text." }, { "code": null, "e": 1961, "s": 1906, "text": "Lastly close the driver using driver.close() function." }, { "code": null, "e": 1977, "s": 1961, "text": "Implementation:" }, { "code": null, "e": 1985, "s": 1977, "text": "Python3" }, { "code": "# Import Libraryfrom selenium import webdriverimport time # set webdriver path here it may vary# Its the location where you have downloaded the ChromeDriverdriver = webdriver.Chrome(executable_path=r\"C:\\\\chromedriver.exe\") # Get the target URLdriver.get('https://html.com/tags/button/') # Wait for 5 seconds to load the webpage completelytime.sleep(5) # Find the button using textdriver.find_element_by_xpath('//button[normalize-space()=\"Click me!\"]').click() time.sleep(5) # Close the driverdriver.close()", "e": 2498, "s": 1985, "text": null }, { "code": null, "e": 2506, "s": 2498, "text": "Output:" }, { "code": null, "e": 2513, "s": 2506, "text": "Picked" }, { "code": null, "e": 2539, "s": 2513, "text": "Python Selenium-Exercises" }, { "code": null, "e": 2555, "s": 2539, "text": "Python-selenium" }, { "code": null, "e": 2562, "s": 2555, "text": "Python" }, { "code": null, "e": 2660, "s": 2562, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2678, "s": 2660, "text": "Python Dictionary" }, { "code": null, "e": 2720, "s": 2678, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 2742, "s": 2720, "text": "Enumerate() in Python" }, { "code": null, "e": 2777, "s": 2742, "text": "Read a file line by line in Python" }, { "code": null, "e": 2803, "s": 2777, "text": "Python String | replace()" }, { "code": null, "e": 2835, "s": 2803, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 2864, "s": 2835, "text": "*args and **kwargs in Python" }, { "code": null, "e": 2894, "s": 2864, "text": "Iterate over a list in Python" }, { "code": null, "e": 2921, "s": 2894, "text": "Python Classes and Objects" } ]
SAP Web Dynpro - Quick Guide
Web Dynpro is a standard SAP UI technology that allows you to develop web applications using graphical tools and development environment integrated with ABAP workbench. Using graphical tools reduces the implementation effort and you can better reuse and maintain components in ABAP workbench. To access Web Dynpro runtime environment and graphical tools in ABAP workbench, you can use Transaction code − SE80 Following are the key benefits of using Web Dynpro for developers in ABAP environment − You can easily maintain and reuse the components for development. Less implementation time with the use of graphical tools. You can easily change the layout and navigation using graphical tools. Easy structure changes. With the use of data binding, you can use automatic data transport. Ease of integration in ABAP environment. Web Dynpro ABAP is the same as Web Dynpro Java and supports the same set of functions for the application development. Once you install ABAP application server, it is necessary to configure it properly for application development. To find the details about ABAP configuration, you can go to SAP Reference IMG → SAP NetWeaver → Application Server If you are using SAP Solman, you can check this configuration by going to T-Code − SOLAR_LIBRARY. To use Web Dynpro with ABAP application development, you have to make additional configuration for web Dynpro programming. You need to set HTTP/HTTPS in ICM service. A service contains following different components − Service/Port Protocol used in service HTTP/HTTPS Processing timeout Keep alive timeout Service status − Active/inactive You can choose Go To → Service to create, delete, activate or deactivate services. To display the ICM server cache statistics, choose Goto → Statistics You should activate the Internet Communication Framework (ICF) service. You can activate this service by going to SPRO → SAP Reference IMG → SAP NetWeaver → Application Server → Internet Communication Framework → Activate HTTP service When you install Application server ABAP, all ICF services are in inactive state. You can maintain ICF services using T-code − SICF under ICF tree. You can activate ICF service in the following ways − Using the menu option, Service/Host → Activate Using the context menu and choosing Activate Service. You should activate all the services in SICF for Web Dynpro ABAP to use the layout editor in the view designer. You should set SSO on the relevant host. You should use fully qualified domain names FQDN and short forms should be avoided. Web Dynpro is an ABAP environment for web development and is based on the Model View Controller (MVC) concept of UI programming. It is available for both Java and ABAP as per the platform, and supports similar functions. Web Dynpro has the following features − Separation of display and business logic Easy change in the layout with the use of graphical tools No platform dependency of interfaces Following are the key concepts as part of Web Dynpro architecture − Web Dynpro provides you with an environment for the development of web-based applications and you can use graphical tools to define web Dynpro application in the form of metadata in application development. You can also define your own events; however, event handling should be defined in a separate code and that has to be executed when an event is triggered. The user interface in Web Dynpro application consists of small elements defined by using Web Dynpro tools. You can also change or enhance the user interface by changing these elements at run time or integrate the elements again. There are a wide range of graphical Web Dynpro tools that you can use to generate webbased applications. You don’t need to create source code for this. Following are the key features of graphical tools in Web Dynpro application − Define properties of user interface elements Data flow User interface layout For all these properties, you can use graphical tools without creating a source code. Web Dynpro allows you to run your application on the front-end and the back-end system can be accessed using service locally or via a remote connection. Your user interface is maintained in Dynpro application and persistent logic runs in the back-end system. You can connect Web Dynpro application to the back-end system using an adaptive RFC service or by calling a web service. Web Dynpro applications are based on MVC model − Model − This allows the access to back end data in a Web Dynpro application. View − This is used to ensure the representation of data in a web browser. Controller − This is used to control communication between Model and View where it takes input from the users and gets the processes data from the model and displays the data in the browser. In Web Dynpro application, you can navigate from one view to the other view using plugs. Run T-code − SE 80 and create a simple Web Dynpro component − We have created a Web Dynpro component with two nodes and two views. VIEW_DISPLAY displays the output in a tabular format and VIEW_MAIN performs search parameters. In VIEW_MAIN you have configured the search layout and VIEW_DISPLAY contains the display layout. In VIEW_MAIN you have configured inbound plugs IN_MAIN and OUT_FROM_MAIN as outbound plugs. Similarly, create an inbound and outbound plugs for VIEW_DISPLAY. Step 1 − Click the component in object tree and go to the context menu as shown in the following screenshot − Step 2 − Enter view name and click on tick mark. Web Dynpro component is an entity used to create a Dynpro application. These are reusable entities, which are combined together to create application blocks. Each Web Dynpro component contains a window, view, and controller pages. You can also embed a Web Dynpro component to other Web Dynrpo component in an application and communication takes place using the component interface. Lifetime of a component starts when you call it first at runtime and ends with Web Dynpro application. Each Web Dynpro application contains at least one view and it is used to define the layout of a user interface. Each view consists of multiple user elements and a controller and context. The controller is used to process the user request and processing of data. Context contains data to which the elements of view are bound. Each view also contains an inbound and outbound plug so you can connect views to each other. Plugs can be linked to each other using navigation links. You can navigate between different views using inbound and outbound plugs. The inbound and outbound plugs are part of the view controller. The inbound plug defines the starting point of view while the outbound plug tells the subsequent view to be called. A view set is defined as a predefined section where you can embed different views in a Web Dynpro application. View set allows you to display more than one view in a screen. Following are a few advantages of view set in designing an application − You can reuse views in a Web Dynpro window. You can easily make changes to the layout at a later stage. It is a more structured approach to use more than one view. In Web Dynpro, the window is for multiple views or view sets. A view can only be displayed when it is embedded in a view and a window always contain one or more views connected by navigation links. Each window contains an inbound and an outbound plug and they can be included in a navigation chain. Inbound plugs within a window lead from the outbound plug of a view to the embedding window. Just like all other inbound plugs, they represent an event and thus call the event handler assigned to them. Controllers are used to define how a Dynpro application responds to user interactions. Each view has one controller which is responsible to perform actions as per the user’s interaction. In Dynpro application, you can define mapping between two global controller contexts or from the view context to the global controller context. Data binding of a UI element property is set up in the view layout. For this purpose, you use the Binding column in the properties table of the embedded UI elements. You click the button to open a dialog box, which provides the context structure of the corresponding view for an element selection. Context element can be defined to link a node to another node of context. In the above diagram, you can see mapping between Node 1 from the context of View 1 and the node of the same name in the context of the component controller. It also shows the mapping from Node 2 from the context of View 2, also to a node with the same name in the component controller context. The context of the component controller is available to both the view controllers with readwrite access to all the attributes. To display the context data in the browser, you can also bind UI elements properties in a view to the attributes of the view context. You can bind multiple properties to one context element. In a view context, all data types are available to bind with different attributes of a view. Internal mapping is defined as the mapping between contexts of a single component. External mapping is defined as the mapping between multiple components using the interface controller. You can create events to enable communication between the controllers. You can allow one controller to trigger events in a different controller. All events that you create in the component controller are available in the component. Inbound plugs can also act as an event, thus when you call a view using the inbound plug, an event handler is called first. You can also use some special events like Button to link with the user actions. Button element like pushbutton can react to a user interaction by clicking on the corresponding pushbutton that can trigger a handling method to be called in the view controller. These UI elements contain one or several general events, which can be linked with a specific action that executes at design time. When an action is created, an event handler is created automatically. You can associate a UI element with different actions. You can also reuse actions within a view by linking an action to several UI elements. An onAction event for the button click or onEnter event for the Input field, when the user presses the "Enter" key in the field. Actions can be created for any UI elements in Web Dynpro framework. To set an action, go to Properties tab → Event section. You can also create Actions from the actions tab of the view controller. An Event handler is automatically created with naming convention onaction<actionname> Action name is SET_ATTRIBUTES and the event handler for an action would be ON_SET_ATTRIBUTES. A Web Dynpro application can be accessed by the user using a URL with a window in the Dynpro component. A Web Dynpro application connects to an interface view using an inbound plug, which is further connected to the Dynpro component that contains Model View and Controller to process the data for the Web Dynpro application. MVC model enables you to separate the user interface and application logic. Model is used to get the data from the back-end system as per application logic. The following image depicts a high level diagram of a Web Dynpro application − You can use different data sources for a Web Dynpro application − Using web service SAP data using BAPIs From external data sources with tools To develop a Web Dynpro application, you can use Web Dynpro explorer, which is easily integrated to ABAP workbench. In a Web Dynpro application, the URL is automatically generated. You can find the URL of an application in the Properties tab. The URL structure can be of two types − SAP namespace − SAP namespace − <schema>://<host>.<domain>.<extension>:<port>/sap/bc/webdynpro/<namespace>/<application name> Custom namespace − <schema>://<host>.<domain>.<extension>:<port>/abc/klm/xyz/<namespace>/webdynpro/<application name> <schema>://<host>.<domain>.<extension>:<port>/namespace>/webdynpro/<application name> where, <schema> − Defines the protocol to access application http/https <host> − Defines the name of the application server <domain><extension> − Defines several hosts under a common name <port> − It can be omitted if the standard port 80 (http) or 443 (https) is used You should specify Fully Qualified Domain Name (FQDN) in Web Dynpro application URL. Application 1 http://xyz.sap.corp:1080/sap/bc/webdynpro/sap/myFirstApp/ Application 2 http://xyz.sap.corp:1080/sap/bc/webdynpro/sap/ mySecondApp/ To check fully qualified domain name, go to Web Dynpro explorer in the ABAP development environment use T-code − SE80 and select the Web Dynpro application from the navigation tree for your Web Dynpro component/interface and check the URL in the administration data. You also need to check the path details in the field URL. It should contain the full domain and host name. Full Domain name should be used for the following reasons − You need a domain to set cookies. You should use FQDN for certificate and SSL protocol in https mode. For portal integration, domain relation code is used. To create a Web Dynpro application, we will create a Web Dynpro component that consists of one view. We will create a view context → linked to a table element on the view layout and contains the data from the table. The table will be shown in the browser at runtime. A Web Dynpro application for this simple Web Dynpro component, which can be run in the browser will be created. Step 1 − Go to T-Code − SE80 and select Web Dynpro component/intf from the list. Step 2 − Create a new component as the following. Step 3 − Enter the name of the new component and click on display. Step 4 − In the next window, enter the following details − You can enter a description of this component. In type, select a Web Dynpro component. You can also maintain the name of the default window. Step 5 − Assign this component to Package $TMP and click the Save button. When you click Save, you can see this new component under the object tree and it contains − Component Controller Component Interface View Windows When you expand the component interface, you can see the interface controller and interface views. Step 1 − Click on the Web Dynpro component and go to the context menu (right click) → Create → View Step 2 − Create a view MAINVIEW as the following and click on the tick mark. This will open view editor in ABAP workbench under the name − MAINVIEW Step 3 − If you want to open the layout tab and view designer, you may need to enter the application server user name and password. Step 4 − Click the save icon at the top. When you save, it comes under the object tree and you can check by expanding the view tab. Step 5 − To assign the window to this view, select the window ZZ_00_TEST under the window tab and click on Change mode at the top of the screen. Step 6 − You can right-click → Display → In Same Window. Step 7 − Now open the view structure and move the view MAINVIEW inside the window structure on the right hand side by Drag and Drop. Step 8 − Open the window structure on the right hand side and you will see the embedded MAINVIEW. Step 9 − Save by clicking the Save icon on top of the screen. Step 1 − Open the View Editor to view MAINVIEW and switch to tab Context. Create a context node in the View Controller by opening the corresponding context menu. Step 2 − Select the View in the object tree and click Display. Step 3 − Maintain the Properties in the next window. Select the cardinality and dictionary structure (table). Select Add Attribute from Structure and select the components of the structure. Step 4 − To select all the components, click Select all option at the top and then click the tick mark at the bottom of the screen. A context node TEST_NODE has been created, which refers to the data structure of the table and which can contain 0 → n entries at runtime. The context node has been created in the view context, since no data exchange with other views is planned hence component controller context usage is not necessary. Step 5 − Save the changes to MAINVIEW by clicking the Save icon. Step 6 − Go to the Layout tab of MAINVIEW. Insert a new UI element of the type table under ROOTUIELEMENT CONTAINER and assign the properties in the given table. Step 7 − Enter the name of the element and type. Step 8 − Create the binding of TEST_TABLE with context node TEST_NODE. Select Text View as Standard Cell Editors and activate bindings for all cells. Step 9 − Click the Context button. Select the context node as TEST_NODE from the list. Step 10 − You can see all the attributes by selecting it. Step 11 − Activate all the checkboxes under Binding for all context attributes by selecting them. Confirm Entry by pressing the Enter key. The result should look like this − Step 12 − Save the changes. Step 13 − To supply data to TEST table, go to Methods tab and double-click method WDDOINIT. Enter the following code − method WDDOINIT . * data declaration data: Node_TEST type REF TO IF_WD_CONTEXT_NODE, Itab_TEST type standard table of TEST. * get data from table TEST select * from TEST into table Itab_TEST. * navigate from <CONTEXT> to <TEST> via lead selection Node_TEST = wd_Context->get_Child_Node( Name = `TEST_NODE` ). * bind internal table to context node <TEST> Node_TEST->Bind_Table( Itab_TEST ). endmethod. Web Dynpro applications, you should not access database tables directly from Web Dynpro methods, however, you should use supply functions or BAPI calls for data access. Step 14 − Save the changes by clicking the save icon on top of the screen. Step 1 − Select the ZZ_00_TEST component in the object tree → right-click and create a new application. Step 2 − Enter the application name and click continue. Step 3 − Save the changes. Save as a local object. Next is activating objects in Web Dynpro component − Step 4 − Double-click on the component ZZ_00_TEST and click Activate. Step 5 − Select all the objects and click continue. Step 6 − To run the application, select Web Dynpro application → Right-click and Test. A browser will be started and Web Dypro application will be run. In a Web Dynpro application, the component window has an inbound plug. This inbound plug can have parameters, which have to be specified as URL parameters. Default values that are overwritten by the URL parameters can be set in the application for these parameters. If neither a default value nor a URL parameter is specified, a runtime error is triggered. To create a new inbound plug, specify plug as a startup and data type should be a string. Activate the component. Next is to specify the component to be called, parameters, window, and start-up plug. Call the application and URL parameters overwrite application parameters. When you create a Web Dynpro component, the creation procedure creates a component interface. Each component interface contains exactly one interface controller and one interface view. The interface view has no direct connection with the interface controller and are created automatically. Using the component interface, you can define the interface structure and you can use in different application components. The interface controller of a component interface definition and the interface controller of a component are different. You can add multiple number of interface views to a component interface definition. Consider the same screenshot as in the previous chapter. Step 1 − Enter the name of the new component and click display. Step 2 − In the next window, enter the following details − You can enter a description of this component. In type, select a Web Dynpro component. You can also maintain the name of default window. Step 3 − Assign this component to Package $TMP and click the Save button. When you click on save, you can see this new component under the object tree and it contains − Component Controller Component Interface View Windows Faceless components in Web Dynpro do not contain any graphical components, no views and no windows. It only contains a component controller and you can add an additional custom controller. Faceless components are specifically used for receiving and structuring the data. Faceless components can be embedded to other components using the component usage and you can supply the required data to these components. Step 1 − Create a new Web Dynpro component. Step 2 − Select the package and click save button. Step 3 − To create a Faceless component, delete the two elements − View and Window. In Web Dynpro component, you can create a uniquely assigned class inherited from the abstract class. Assistance class can store the coding that is required in a component but is not linked with the layout. You can store dynamic text in assistance class, text combined at run time or contains variable that can be stored in the text pool. In Assistance class, you can also save a code that is not directly linked with the layout of the application or with the controller. Using the method _WD_COMPONENT_ASSISTANCE~GET_TEXT( ) allows you to access text symbols of the assistance class in the controller of your component. When you call the method, 3-digit id of the text symbol is used − method MY_CONTROLLER_METHOD . data: my_text type string. my_text = WD_ASSIST->IF_WD_COMPONENT_ASSISTANCE~GET_TEXT( KEY = ‘001’ ). Endmethod You can maintain text symbols in assistance class using each controller. Click on Go to → Text Symbols in the menu. Note − Each ABAP class can act as assistance class but service integrated with Web Dynpro application is only available if assistance class is derived from class − CL_WD_COMPONENT_ASSISTANCE. You can call an existing functional module in a Web Dynpro component using a service call. To create a service call, you can use easy-to-use wizard in Web Dynpro tools. You can launch the wizard in ABAP workbench to create a service call. Run T-Code − SE80 Step 1 − Select Web Dynpro component → Right-click to open the context menu. Go to create → Service call. It will open Web Dynpro wizard − Start screen. Step 2 − You can select if you want service call to be embedded in an existing controller or you want to create a new controller. Note − The service calls should be embedded in global controllers and it can’t be used with the view controllers in Web Dynpro. Step 3 − In the next window, select the service type. Click the Continue button. Step 4 − In the next window, select a function module as a service. You can use the input help for this. If you choose a remote capable function module, you can optionally specify an RFC destination that is to be used when calling the function module. If you do not specify a destination, the function module will be called locally. Note − The function module must exist in the current system! The wizard does not support to call a remote capable function module that does not exist in the current system. Step 5 − Click Continue. Step 6 − In the next window, you can choose which object type to use to represent the service function parameters in Web Dynpro controller − As a parameter of the controller method As a controller attribute As a context node or a context attribute To do this, select the required object type from the list box in the relevant lines. Note − Only UI-relevant data should be stored in the context. You can also individually name the controller attributes and the context nodes to be created. The following proposal is generated − The root node receives the name of the service. The root node receives the name of the service. The nodes for grouping the parameters according to their declaration types receive appropriate names such as IMPORTING, EXPORTING, ... The nodes for grouping the parameters according to their declaration types receive appropriate names such as IMPORTING, EXPORTING, ... The node names and attribute names for the parameters themselves are identical to the parameter names. The node names and attribute names for the parameters themselves are identical to the parameter names. As the length of the node and the attribute names is limited to 20 characters, they are abbreviated accordingly, if necessary. As the length of the node and the attribute names is limited to 20 characters, they are abbreviated accordingly, if necessary. In the next window, selected service uses types from type groups as parameter types and/or defines implicit table parameters. For all the types listed below, define (table) types with the same equal structure in the Data Dictionary. These will then be used for typing of controller attributes or method parameters created by the wizard. Step 7 − Enter Attribute Type − TEST and click Continue. Step 8 − In the next window, specify the name of the method that should execute the service. The wizard generates coding for calling the service and for the context binding. The method must not yet exist in the controller. You have now entered all the necessary information for the creation of the model-oriented controller. Step 9 − Click ‘Complete’ to create the controller, or enhance it respectively, to generate the service call. You can also cancel the wizard at this position. However, data entered before are lost. When a service call is created, a function module is available to the component. Now it is possible to choose a view in order to display the elements of the database table in the browser. Provided the global controller is not the component controller, a use page of the global controller must be entered for the controller of the selected view. Afterwards, there should be mapping of the node. FUNCMODUL1 onto the node with the same name in a view controller context is generated. To fill the context node FUNCMODUL1 of the view controller context with the data of the database table, the method EXECUTE_FUNCMODULE of the global controller is called its supply function. For this purpose, you must create such a supply function by calling the method EXECUTE_FUNCMODULE1. There are various tools in ABAP workbench that you can use for debugging purpose of source code. You can test all source code of Web Dynpro application using a debugger. Step 1 − To start the debugger, you have to select a new debugger in ABAP workbench. Step 2 − Go to Utilities → Settings A dialog box now appears that contains two nested tab page areas. Step 3 − Choose the “parent” tab page ABAP Editor. The settings for ABAP Editor always open with the content of the child tab page Editor. Step 4 − Select the Front End Editor (New). Step 5 − Now switch to the Debugging tab page in the ABAP Editor settings and select New Debugger. Step 6 − Save your changes and close the dialog. If you want to run an application in debugging mode, you need to set an external breakpoint in one of the methods in Dynpro component. It is suggested to set the breakpoint in method WDDOMODIFYVIEW under METHODS tab of Dynpro view. Provided that the context of the view controller is not filled using a supply method, the view is fully instantiated in the phase model at this point in time. Note − The method in which you set the breakpoint depends on the purpose of the test run and it is advised to set it in WDDMODIFYVIEW. When you start a Web Dynpro application, a debugger automatically starts in another session. You can use version management to manage the older version of an object, compare the versions or you can also reset them. In version management, you can store different versions of ABAP development objects. In an ABAP workbench, you can compare different versions of − Views Windows Controllers You can also store a version of an object without releasing it. To perform this, select the object in the editor area and go to Utilities tab → Versions → Generate Version Before version generation, you can see no version in the database, if you go to version management. When you click on Generate version, you get a confirmation that a version is created. Go to Utilities → Versions → Version Management It shows all the stored version of the selected object in version database. It consists of all previously released or all active versions. To start comparison of objects, select object and click the comparison button at the top of the screen. For all versions, a comparison is performed and any difference is highlighted in a table. In ABAP Workbench, you can also create and show messages that contain information for end users of Dynpro application. These messages are displayed on the screen. These are user interactive messages that display important information about Web Dynpro application. To provide users with information, warning or error details, you can program these methods in ABAP workbench using runtime service. These messages are configured under Setting on Web Dynpro application. You can assign different settings for handling messages in Web Dynpro application − Show message component − In this case, if the message exists, it will be displayed. Always show message component − Even if there is no message, the message component is shown at the top. The message is displayed without the component − In this setting, one message is displayed and no message log exists. All these user messages are shown in the status bar. The user can navigate to the UI element to remove the error in the error message. Messages in popup window − In this configuration, you can set the message to display in the popup window, irrespective of what is configured in Web Dynpro application. You can configure the following popup messages to display − Messages belong to specific window All the messages till now No messages You can use the message manager to integrate messages into the message log. You can open the message manager using Web Dynpro code wizard. You can open Web Dynpro code wizard from the tool bar. It is available when your ABAP workbench is in change mode or while editing a view or a controller. To set ABAP workbench in the change mode, select the view and go to context to Change. You can use the following methods for triggering messages − IS_EMPTY − This is used to query if there are any messages. IS_EMPTY − This is used to query if there are any messages. CLEAR_MESSAGES − This is used to deletes all messages. CLEAR_MESSAGES − This is used to deletes all messages. REPORT_ATTRIBUTE_ERROR_MESSAGE − This is used to report a Web Dynpro exception to a context attribute. REPORT_ATTRIBUTE_ERROR_MESSAGE − This is used to report a Web Dynpro exception to a context attribute. REPORT_ATTRIBUTE_EXCEPTION − This is used to report a Web Dynpro exception to a context attribute. REPORT_ATTRIBUTE_EXCEPTION − This is used to report a Web Dynpro exception to a context attribute. REPORT_ERROR_MESSAGE − This is used to report a Web Dynpro message with optional parameters. REPORT_ERROR_MESSAGE − This is used to report a Web Dynpro message with optional parameters. REPORT_EXCEPTION − This is used to report a Web Dynpro exception that may come back. REPORT_EXCEPTION − This is used to report a Web Dynpro exception that may come back. REPORT_FATAL_ERROR_MESSAGE − This is used to report a fatal Web Dynpro message with optional parameters. REPORT_FATAL_ERROR_MESSAGE − This is used to report a fatal Web Dynpro message with optional parameters. REPORT_FATAL_EXCEPTION − This is used to report a fatal Web Dynpro exception. REPORT_FATAL_EXCEPTION − This is used to report a fatal Web Dynpro exception. REPORT_SUCCESS − This is used to report a success message. REPORT_SUCCESS − This is used to report a success message. REPORT_T100_MESSAGE − This is used to report a message using a T100 entry. REPORT_T100_MESSAGE − This is used to report a message using a T100 entry. REPORT_WARNING − This is used to report a warning. REPORT_WARNING − This is used to report a warning. As per the business requirement, you can implement many standard applications and the UI of Web Dynpro application can vary as per the requirement. To configure a Web Dynpro application, you first configure data records for individual Web Dynpro components. Using the component configuration, it allows you to manage the behavior. Next is to configure the application. All the components that are created require to be used in the specific configuration. The configuration of Web Dynpro application defines which component is configured in an application. In ABAP object list, select a Web Dynpro component − Right-click → Create/Change configuration. This opens a browser with the dialog window of the configurator. The mode Component Configurator is active and you enter a name for your new component configuration. You can also define implicit and explicit configuration. Save the configuration and close the window. Note − You can save a new configuration only when it actually contains values. An empty configuration file that doesn’t contain any data and has a name is not stored. As this configurator is not part of the ABAP Workbench and runs separately in the browser, you need to update the hierarchy of the object list in the workbench after completion of the creation or change procedure in a configuration. This allows you to store different configurations for each object. When you save the application configuration, you can’t check the changes made by an administrator and an end user. There is a need to store customization and personalization data that allows merged data to be managed. The following points should be considered − Application users and administrators should be able to reverse the changes. Application users and administrators should be able to reverse the changes. Customization changes of an application should be visible to the user for all the pages. Customization changes of an application should be visible to the user for all the pages. Application administrator should have access to mark the report as final and this should be valid for all users. When an administrator flags a property final, any changes to the value as a personalization of a single user must no longer be permitted. Application administrator should have access to mark the report as final and this should be valid for all users. When an administrator flags a property final, any changes to the value as a personalization of a single user must no longer be permitted. You can integrate an ABAP application into the enterprise portal. You can also manage portal functions from a Web Dynpro application. You can call Web Dynpro code wizard to access portal manager methods. This can be used to perform the following functions − Portal Events − To navigate between Web Dynpro application within the portal or portal content. Following navigation types are supported − Object-based navigation Absolute navigation Relative navigation Work Protect Mode − For portal integration, following Web Dynpro applications are available in package SWDP_TEST − WDR_TEST_PORTAL_EVENT_FIRE Trigger event WDR_TEST_PORTAL_EVENT_FIRE Trigger event WDR_TEST_PORTAL_EVENT_FIRE2 Trigger free event WDR_TEST_PORTAL_EVENT_FIRE2 Trigger free event WDR_TEST_PORTAL_NAV_OBN Object-based navigation WDR_TEST_PORTAL_NAV_OBN Object-based navigation WDR_TEST_PORTAL_NAV_PAGE Page navigation WDR_TEST_PORTAL_NAV_PAGE Page navigation WDR_TEST_PORTAL_WORKPROTECT Security monitoring WDR_TEST_PORTAL_WORKPROTECT Security monitoring WDR_TEST_PORTAL_EVENT_REC Receive portal event WDR_TEST_PORTAL_EVENT_REC Receive portal event WDR_TEST_PORTAL_EVENT_REC2 Receive free portal event WDR_TEST_PORTAL_EVENT_REC2 Receive free portal event Following are the steps to integrate Web Dynpro ABAP (WDA) in the portal. Step 1 − Go to ABAP workbench using T-code − SE80 and create Web Dynpro component. Step 2 − Save the component and activate it. Step 3 − Define data binding and context mapping. Create a Web Dynpro application and save it. Step 4 − Login to SAP NetWeaver portal. Step 5 − Go to Portal Content → Content Administration tab. Step 6 − Right-click on the portal content and create a new folder. Step 7 − Enter the folder name and click Finish. Step 8 − Right-click on the created folder and create a new iView. Step 9 − Select iView template. Create an iView from an existing iView template and click Next. Step 10 − Select SAP Web Dynpro iView as template and click Next. Step 11 − Enter iView name, iView ID, iView prefix ID and click Next. Enter definition type as ABAP and click Next. Step 12 − Enter Web Dynpro details and ECC system is created. Step 13 − Enter application parameter in the same screen and click Next. You will be prompted to see the summary screen. Click Finish. You can create forms based on Adobe software and can use in context for Web Dynpro user interfaces. You can integrate Adobe lifecycle development tool with ABAP editor to ease the development of user interface. Interactive forms using Adobe software allows you to efficiently and easily develop UI elements. Following scenarios can be used for creating interactive forms − Interactive scenario Print scenario Offline scenario Using digital signature You can create forms independently using form editor. Go to T-code − SFP When you click Create, you will be prompted to enter the form name, form description, and interface. The example component for the interactive scenario in the system are available in the package SWDP_TEST → WDR_TEST_IA_FORMS. In a Dynpro application, both scenarios - print scenario and interactive scenario − for inserting interactive forms is similar. The form that contains the static components can be used to display data in a Dynpro application using Print scenario. Using interactive forms, you can reuse entries in Web Dynpro context for Web Dynpro application. Step 1 − Create a view of your Web Dynpro component. Step 2 − Right-click on View and create a node. This node will be bound to form. Step 3 − Drag the interactive form from Adobe library to Designer window. Step 4 − Design the form, enter the name, and bound the attributes. Step 5 − Once you are done with the form design, go to edit mode in the workbench and define if the form is static content, PDF-based print form, or an interactive form. SAP List Viewer is used to add an ALV component and provides a flexible environment to display lists and tabular structure. A standard output consists of header, toolbar, and an output table. The user can adjust the settings to add column display, aggregations, and sorting options using additional dialog boxes. Following are the key features of ALV − It supports many properties of the table element as it is based on Web Dynpro table UI element. It supports many properties of the table element as it is based on Web Dynpro table UI element. ALV output can be filtered, sorted, or you can apply calculations. ALV output can be filtered, sorted, or you can apply calculations. The user can perform application specific functions using UI elements in the toolbar. The user can perform application specific functions using UI elements in the toolbar. Allows the user to save the setting in different views. Allows the user to save the setting in different views. Allows to configure special areas above and below ALV output. Allows to configure special areas above and below ALV output. Allows to define the extent to which ALV output can be edited. Allows to define the extent to which ALV output can be edited. Following are the steps to create an ALV. Step 1 − Use T-code: SE80. Select Web Dynpro comp/intf from the list and enter the name. Click on display. You will be prompted create the component. Click on Yes. Step 2 − Select type as Web Dynpro component. Enter the Window name and the View name. Step 3 − Click the tick mark. Step 4 − In the change window, enter the component use as ALV, component as SALV_WD_TABLE and description as ALV component. Step 5 − Go to Component Controller and right-click the context. Then select Create Node MAKT with the dictionary structure MAKT. Step 6 − Select the required attributes from MAKT by using Add Attribute from Structure. Step 7 − Remove the dictionary structure MAKT from the node MAKT and set the properties as follows (Cardinality, Lead selection, etc.) Step 8 − Right-click on Component usage in the Object tree → Create Controller Usage. Step 9 − Go to View → Context tab and drag MAKT node to the view. After mapping, it will appear as shown in the following screenshot. Step 10 − Go to Layout and right-click Insert Element. The layout will appear as shown in the following screenshot − Step 11 − Go to Properties tab, click create controller usage to add the following to View. Step 12 − Go to method, use WDDOINIT to write code. Step 13 − Double-click on the method to enter the code. Enter the following code and initiate the used component ALV. Use GET_MODEL method in the controller. Step 14 − Bind the table to the context node using BIND_TABLE method as follows − Step 15 − Go to Window in the Object tree and right-click C1 to embed ALV table to the view. Once you embed the ALV table, it will appear like this − Step 16 − The last step is to create a Web Dynpro application under the object tree. Enter the name of the application. Step 17 − To execute application, double-click and you will see the output. Using filters, you can limit the data in ALV output. You can create multiple number of filter conditions for each field. To create or delete a filter condition, you can use the method of interface class IF_SALV_WD_FILTER. You can use the following methods for creating, getting, and deleting filter conditions − In Web Dynpro ABAP administration, you can perform various administration tasks using different tools − ICM Tracing Web Dynpro Trace tool Browser Tracing Logging Security Web Dynpro trace tool can be used for checking the errors and problems in Dynpro application. You can activate Web Dynpro trace tool for a specific user. Step 1 − To activate trace tool in SAP GUI client, use T-code − WD_TRACE_TOOL Step 2 − Click on Activate for this user. This allows to set the trace active for the user. Step 3 − Select Trace features in the new window and click OK. Step 4 − Start Web Dynpro application that you want to trace. You can see a new area Web Dynpro trace tool in Web application. Step 5 − Execute the application. Enter the details of problem → Choose Continue. Step 6 − You can also send it with Insert and add a screenshot or you insert a file with additional information. Go to Browse → Select File and click Add File. Step 7 − You can download the trace file in Zip format and end tracing by clicking on Save Trace as Zip file and Stop Trace. This file can be uploaded to SAP portal and can be sent to SAP for debugging. To analyze the problem, you can also trace the data stream in SAP Web Application server. Step 1 − Use T-Code − SMICM. In the next window, click on GOTO → Trace File → Display file or start. You will see ICM trace result as shown in the following screenshot − Step 2 − You can also increase the trace level from default level 1. To increase the trace level, GOTO → Trace Level → Increase. This is used to analyze the dynamic behavior of your code. This can be used as an alternative to ICM tracing. To use browser tracing, you need to install proxy tool on your local system. You can monitor Web Dynpro application using ABAP monitor. Information is stored about Web Dynpro application. You can view this information using T-code − RZ20. You can check the following information in Web Dynpro ABAP monitor − Session Count Application Count CPU time Data To view the report, use T-code − RZ20 Step 1 − Go to SAP CCMS Monitor template. Step 2 − Click the sub node Entire System. Step 3 − Enter the system ID of the current SAP system where the application you want to monitor is installed. Step 4 − Select Application Server. Step 5 − Select the name of the relevant application server. For instance, select Web Dynpro ABAP as shown in the following screenshot − The result will be displayed with the following information when a Web Dynpro application will be called −
[ { "code": null, "e": 2606, "s": 2313, "text": "Web Dynpro is a standard SAP UI technology that allows you to develop web applications using graphical tools and development environment integrated with ABAP workbench. Using graphical tools reduces the implementation effort and you can better reuse and maintain components in ABAP workbench." }, { "code": null, "e": 2722, "s": 2606, "text": "To access Web Dynpro runtime environment and graphical tools in ABAP workbench, you can use Transaction code − SE80" }, { "code": null, "e": 2810, "s": 2722, "text": "Following are the key benefits of using Web Dynpro for developers in ABAP environment −" }, { "code": null, "e": 2876, "s": 2810, "text": "You can easily maintain and reuse the components for development." }, { "code": null, "e": 2934, "s": 2876, "text": "Less implementation time with the use of graphical tools." }, { "code": null, "e": 3005, "s": 2934, "text": "You can easily change the layout and navigation using graphical tools." }, { "code": null, "e": 3029, "s": 3005, "text": "Easy structure changes." }, { "code": null, "e": 3097, "s": 3029, "text": "With the use of data binding, you can use automatic data transport." }, { "code": null, "e": 3138, "s": 3097, "text": "Ease of integration in ABAP environment." }, { "code": null, "e": 3257, "s": 3138, "text": "Web Dynpro ABAP is the same as Web Dynpro Java and supports the same set of functions for the application development." }, { "code": null, "e": 3369, "s": 3257, "text": "Once you install ABAP application server, it is necessary to configure it properly for application development." }, { "code": null, "e": 3484, "s": 3369, "text": "To find the details about ABAP configuration, you can go to SAP Reference IMG → SAP NetWeaver → Application Server" }, { "code": null, "e": 3582, "s": 3484, "text": "If you are using SAP Solman, you can check this configuration by going to T-Code − SOLAR_LIBRARY." }, { "code": null, "e": 3705, "s": 3582, "text": "To use Web Dynpro with ABAP application development, you have to make additional configuration for web Dynpro programming." }, { "code": null, "e": 3800, "s": 3705, "text": "You need to set HTTP/HTTPS in ICM service. A service contains following different components −" }, { "code": null, "e": 3813, "s": 3800, "text": "Service/Port" }, { "code": null, "e": 3849, "s": 3813, "text": "Protocol used in service HTTP/HTTPS" }, { "code": null, "e": 3868, "s": 3849, "text": "Processing timeout" }, { "code": null, "e": 3887, "s": 3868, "text": "Keep alive timeout" }, { "code": null, "e": 3920, "s": 3887, "text": "Service status − Active/inactive" }, { "code": null, "e": 4072, "s": 3920, "text": "You can choose Go To → Service to create, delete, activate or deactivate services. To display the ICM server cache statistics, choose Goto → Statistics" }, { "code": null, "e": 4307, "s": 4072, "text": "You should activate the Internet Communication Framework (ICF) service. You can activate this service by going to SPRO → SAP Reference IMG → SAP NetWeaver → Application Server → Internet Communication Framework → Activate HTTP service" }, { "code": null, "e": 4455, "s": 4307, "text": "When you install Application server ABAP, all ICF services are in inactive state. You can maintain ICF services using T-code − SICF under ICF tree." }, { "code": null, "e": 4508, "s": 4455, "text": "You can activate ICF service in the following ways −" }, { "code": null, "e": 4555, "s": 4508, "text": "Using the menu option, Service/Host → Activate" }, { "code": null, "e": 4609, "s": 4555, "text": "Using the context menu and choosing Activate Service." }, { "code": null, "e": 4721, "s": 4609, "text": "You should activate all the services in SICF for Web Dynpro ABAP to use the layout editor in the view designer." }, { "code": null, "e": 4762, "s": 4721, "text": "You should set SSO on the relevant host." }, { "code": null, "e": 4846, "s": 4762, "text": "You should use fully qualified domain names FQDN and short forms should be avoided." }, { "code": null, "e": 5067, "s": 4846, "text": "Web Dynpro is an ABAP environment for web development and is based on the Model View Controller (MVC) concept of UI programming. It is available for both Java and ABAP as per the platform, and supports similar functions." }, { "code": null, "e": 5107, "s": 5067, "text": "Web Dynpro has the following features −" }, { "code": null, "e": 5148, "s": 5107, "text": "Separation of display and business logic" }, { "code": null, "e": 5206, "s": 5148, "text": "Easy change in the layout with the use of graphical tools" }, { "code": null, "e": 5243, "s": 5206, "text": "No platform dependency of interfaces" }, { "code": null, "e": 5311, "s": 5243, "text": "Following are the key concepts as part of Web Dynpro architecture −" }, { "code": null, "e": 5672, "s": 5311, "text": "Web Dynpro provides you with an environment for the development of web-based applications and you can use graphical tools to define web Dynpro application in the form of metadata in application development. You can also define your own events; however, event handling should be defined in a separate code and that has to be executed when an event is triggered." }, { "code": null, "e": 5901, "s": 5672, "text": "The user interface in Web Dynpro application consists of small elements defined by using Web Dynpro tools. You can also change or enhance the user interface by changing these elements at run time or integrate the elements again." }, { "code": null, "e": 6131, "s": 5901, "text": "There are a wide range of graphical Web Dynpro tools that you can use to generate webbased applications. You don’t need to create source code for this. Following are the key features of graphical tools in Web Dynpro application −" }, { "code": null, "e": 6176, "s": 6131, "text": "Define properties of user interface elements" }, { "code": null, "e": 6186, "s": 6176, "text": "Data flow" }, { "code": null, "e": 6208, "s": 6186, "text": "User interface layout" }, { "code": null, "e": 6294, "s": 6208, "text": "For all these properties, you can use graphical tools without creating a source code." }, { "code": null, "e": 6553, "s": 6294, "text": "Web Dynpro allows you to run your application on the front-end and the back-end system can be accessed using service locally or via a remote connection. Your user interface is maintained in Dynpro application and persistent logic runs in the back-end system." }, { "code": null, "e": 6674, "s": 6553, "text": "You can connect Web Dynpro application to the back-end system using an adaptive RFC service or by calling a web service." }, { "code": null, "e": 6723, "s": 6674, "text": "Web Dynpro applications are based on MVC model −" }, { "code": null, "e": 6800, "s": 6723, "text": "Model − This allows the access to back end data in a Web Dynpro application." }, { "code": null, "e": 6875, "s": 6800, "text": "View − This is used to ensure the representation of data in a web browser." }, { "code": null, "e": 7066, "s": 6875, "text": "Controller − This is used to control communication between Model and View where it takes input from the users and gets the processes data from the model and displays the data in the browser." }, { "code": null, "e": 7155, "s": 7066, "text": "In Web Dynpro application, you can navigate from one view to the other view using plugs." }, { "code": null, "e": 7217, "s": 7155, "text": "Run T-code − SE 80 and create a simple Web Dynpro component −" }, { "code": null, "e": 7286, "s": 7217, "text": "We have created a Web Dynpro component with two nodes and two views." }, { "code": null, "e": 7478, "s": 7286, "text": "VIEW_DISPLAY displays the output in a tabular format and VIEW_MAIN performs search parameters. In VIEW_MAIN you have configured the search layout and VIEW_DISPLAY contains the display layout." }, { "code": null, "e": 7636, "s": 7478, "text": "In VIEW_MAIN you have configured inbound plugs IN_MAIN and OUT_FROM_MAIN as outbound plugs. Similarly, create an inbound and outbound plugs for VIEW_DISPLAY." }, { "code": null, "e": 7746, "s": 7636, "text": "Step 1 − Click the component in object tree and go to the context menu as shown in the following screenshot −" }, { "code": null, "e": 7795, "s": 7746, "text": "Step 2 − Enter view name and click on tick mark." }, { "code": null, "e": 7953, "s": 7795, "text": "Web Dynpro component is an entity used to create a Dynpro application. These are reusable entities, which are combined together to create application blocks." }, { "code": null, "e": 8177, "s": 7953, "text": "Each Web Dynpro component contains a window, view, and controller pages. You can also embed a Web Dynpro component to other Web Dynrpo component in an application and communication takes place using the component interface." }, { "code": null, "e": 8280, "s": 8177, "text": "Lifetime of a component starts when you call it first at runtime and ends with Web Dynpro application." }, { "code": null, "e": 8467, "s": 8280, "text": "Each Web Dynpro application contains at least one view and it is used to define the layout of a user interface. Each view consists of multiple user elements and a controller and context." }, { "code": null, "e": 8605, "s": 8467, "text": "The controller is used to process the user request and processing of data. Context contains data to which the elements of view are bound." }, { "code": null, "e": 8756, "s": 8605, "text": "Each view also contains an inbound and outbound plug so you can connect views to each other. Plugs can be linked to each other using navigation links." }, { "code": null, "e": 9011, "s": 8756, "text": "You can navigate between different views using inbound and outbound plugs. The inbound and outbound plugs are part of the view controller. The inbound plug defines the starting point of view while the outbound plug tells the subsequent view to be called." }, { "code": null, "e": 9185, "s": 9011, "text": "A view set is defined as a predefined section where you can embed different views in a Web Dynpro application. View set allows you to display more than one view in a screen." }, { "code": null, "e": 9258, "s": 9185, "text": "Following are a few advantages of view set in designing an application −" }, { "code": null, "e": 9302, "s": 9258, "text": "You can reuse views in a Web Dynpro window." }, { "code": null, "e": 9362, "s": 9302, "text": "You can easily make changes to the layout at a later stage." }, { "code": null, "e": 9422, "s": 9362, "text": "It is a more structured approach to use more than one view." }, { "code": null, "e": 9620, "s": 9422, "text": "In Web Dynpro, the window is for multiple views or view sets. A view can only be displayed when it is embedded in a view and a window always contain one or more views connected by navigation links." }, { "code": null, "e": 9923, "s": 9620, "text": "Each window contains an inbound and an outbound plug and they can be included in a navigation chain. Inbound plugs within a window lead from the outbound plug of a view to the embedding window. Just like all other inbound plugs, they represent an event and thus call the event handler assigned to them." }, { "code": null, "e": 10110, "s": 9923, "text": "Controllers are used to define how a Dynpro application responds to user interactions. Each view has one controller which is responsible to perform actions as per the user’s interaction." }, { "code": null, "e": 10254, "s": 10110, "text": "In Dynpro application, you can define mapping between two global controller contexts or from the view context to the global controller context." }, { "code": null, "e": 10552, "s": 10254, "text": "Data binding of a UI element property is set up in the view layout. For this purpose, you use the Binding column in the properties table of the embedded UI elements. You click the button to open a dialog box, which provides the context structure of the corresponding view for an element selection." }, { "code": null, "e": 10626, "s": 10552, "text": "Context element can be defined to link a node to another node of context." }, { "code": null, "e": 10921, "s": 10626, "text": "In the above diagram, you can see mapping between Node 1 from the context of View 1 and the node of the same name in the context of the component controller. It also shows the mapping from Node 2 from the context of View 2, also to a node with the same name in the component controller context." }, { "code": null, "e": 11048, "s": 10921, "text": "The context of the component controller is available to both the view controllers with readwrite access to all the attributes." }, { "code": null, "e": 11239, "s": 11048, "text": "To display the context data in the browser, you can also bind UI elements properties in a view to the attributes of the view context. You can bind multiple properties to one context element." }, { "code": null, "e": 11332, "s": 11239, "text": "In a view context, all data types are available to bind with different attributes of a view." }, { "code": null, "e": 11415, "s": 11332, "text": "Internal mapping is defined as the mapping between contexts of a single component." }, { "code": null, "e": 11518, "s": 11415, "text": "External mapping is defined as the mapping between multiple components using the interface controller." }, { "code": null, "e": 11750, "s": 11518, "text": "You can create events to enable communication between the controllers. You can allow one controller to trigger events in a different controller. All events that you create in the component controller are available in the component." }, { "code": null, "e": 11874, "s": 11750, "text": "Inbound plugs can also act as an event, thus when you call a view using the inbound plug, an event handler is called first." }, { "code": null, "e": 11954, "s": 11874, "text": "You can also use some special events like Button to link with the user actions." }, { "code": null, "e": 12263, "s": 11954, "text": "Button element like pushbutton can react to a user interaction by clicking on the corresponding pushbutton that can trigger a handling method to be called in the view controller. These UI elements contain one or several general events, which can be linked with a specific action that executes at design time." }, { "code": null, "e": 12388, "s": 12263, "text": "When an action is created, an event handler is created automatically. You can associate a UI element with different actions." }, { "code": null, "e": 12474, "s": 12388, "text": "You can also reuse actions within a view by linking an action to several UI elements." }, { "code": null, "e": 12603, "s": 12474, "text": "An onAction event for the button click or onEnter event for the Input field, when the user presses the \"Enter\" key in the field." }, { "code": null, "e": 12727, "s": 12603, "text": "Actions can be created for any UI elements in Web Dynpro framework. To set an action, go to Properties tab → Event section." }, { "code": null, "e": 12886, "s": 12727, "text": "You can also create Actions from the actions tab of the view controller. An Event handler is automatically created with naming convention onaction<actionname>" }, { "code": null, "e": 12980, "s": 12886, "text": "Action name is SET_ATTRIBUTES and the event handler for an action would be ON_SET_ATTRIBUTES." }, { "code": null, "e": 13305, "s": 12980, "text": "A Web Dynpro application can be accessed by the user using a URL with a window in the Dynpro component. A Web Dynpro application connects to an interface view using an inbound plug, which is further connected to the Dynpro component that contains Model View and Controller to process the data for the Web Dynpro application." }, { "code": null, "e": 13462, "s": 13305, "text": "MVC model enables you to separate the user interface and application logic. Model is used to get the data from the back-end system as per application logic." }, { "code": null, "e": 13541, "s": 13462, "text": "The following image depicts a high level diagram of a Web Dynpro application −" }, { "code": null, "e": 13607, "s": 13541, "text": "You can use different data sources for a Web Dynpro application −" }, { "code": null, "e": 13625, "s": 13607, "text": "Using web service" }, { "code": null, "e": 13646, "s": 13625, "text": "SAP data using BAPIs" }, { "code": null, "e": 13684, "s": 13646, "text": "From external data sources with tools" }, { "code": null, "e": 13800, "s": 13684, "text": "To develop a Web Dynpro application, you can use Web Dynpro explorer, which is easily integrated to ABAP workbench." }, { "code": null, "e": 13967, "s": 13800, "text": "In a Web Dynpro application, the URL is automatically generated. You can find the URL of an application in the Properties tab. The URL structure can be of two types −" }, { "code": null, "e": 13983, "s": 13967, "text": "SAP namespace −" }, { "code": null, "e": 13999, "s": 13983, "text": "SAP namespace −" }, { "code": null, "e": 14094, "s": 13999, "text": "<schema>://<host>.<domain>.<extension>:<port>/sap/bc/webdynpro/<namespace>/<application name>\n" }, { "code": null, "e": 14113, "s": 14094, "text": "Custom namespace −" }, { "code": null, "e": 14299, "s": 14113, "text": "<schema>://<host>.<domain>.<extension>:<port>/abc/klm/xyz/<namespace>/webdynpro/<application name>\n<schema>://<host>.<domain>.<extension>:<port>/namespace>/webdynpro/<application name>\n" }, { "code": null, "e": 14306, "s": 14299, "text": "where," }, { "code": null, "e": 14371, "s": 14306, "text": "<schema> − Defines the protocol to access application http/https" }, { "code": null, "e": 14423, "s": 14371, "text": "<host> − Defines the name of the application server" }, { "code": null, "e": 14487, "s": 14423, "text": "<domain><extension> − Defines several hosts under a common name" }, { "code": null, "e": 14568, "s": 14487, "text": "<port> − It can be omitted if the standard port 80 (http) or 443 (https) is used" }, { "code": null, "e": 14653, "s": 14568, "text": "You should specify Fully Qualified Domain Name (FQDN) in Web Dynpro application URL." }, { "code": null, "e": 14725, "s": 14653, "text": "Application 1 http://xyz.sap.corp:1080/sap/bc/webdynpro/sap/myFirstApp/" }, { "code": null, "e": 14799, "s": 14725, "text": "Application 2 http://xyz.sap.corp:1080/sap/bc/webdynpro/sap/ mySecondApp/" }, { "code": null, "e": 15173, "s": 14799, "text": "To check fully qualified domain name, go to Web Dynpro explorer in the ABAP development environment use T-code − SE80 and select the Web Dynpro application from the navigation tree for your Web Dynpro component/interface and check the URL in the administration data. You also need to check the path details in the field URL. It should contain the full domain and host name." }, { "code": null, "e": 15233, "s": 15173, "text": "Full Domain name should be used for the following reasons −" }, { "code": null, "e": 15267, "s": 15233, "text": "You need a domain to set cookies." }, { "code": null, "e": 15335, "s": 15267, "text": "You should use FQDN for certificate and SSL protocol in https mode." }, { "code": null, "e": 15389, "s": 15335, "text": "For portal integration, domain relation code is used." }, { "code": null, "e": 15605, "s": 15389, "text": "To create a Web Dynpro application, we will create a Web Dynpro component that consists of one view. We will create a view context → linked to a table element on the view layout and contains the data from the table." }, { "code": null, "e": 15768, "s": 15605, "text": "The table will be shown in the browser at runtime. A Web Dynpro application for this simple Web Dynpro component, which can be run in the browser will be created." }, { "code": null, "e": 15849, "s": 15768, "text": "Step 1 − Go to T-Code − SE80 and select Web Dynpro component/intf from the list." }, { "code": null, "e": 15899, "s": 15849, "text": "Step 2 − Create a new component as the following." }, { "code": null, "e": 15966, "s": 15899, "text": "Step 3 − Enter the name of the new component and click on display." }, { "code": null, "e": 16025, "s": 15966, "text": "Step 4 − In the next window, enter the following details −" }, { "code": null, "e": 16072, "s": 16025, "text": "You can enter a description of this component." }, { "code": null, "e": 16112, "s": 16072, "text": "In type, select a Web Dynpro component." }, { "code": null, "e": 16166, "s": 16112, "text": "You can also maintain the name of the default window." }, { "code": null, "e": 16240, "s": 16166, "text": "Step 5 − Assign this component to Package $TMP and click the Save button." }, { "code": null, "e": 16332, "s": 16240, "text": "When you click Save, you can see this new component under the object tree and it contains −" }, { "code": null, "e": 16353, "s": 16332, "text": "Component Controller" }, { "code": null, "e": 16373, "s": 16353, "text": "Component Interface" }, { "code": null, "e": 16378, "s": 16373, "text": "View" }, { "code": null, "e": 16386, "s": 16378, "text": "Windows" }, { "code": null, "e": 16485, "s": 16386, "text": "When you expand the component interface, you can see the interface controller and interface views." }, { "code": null, "e": 16585, "s": 16485, "text": "Step 1 − Click on the Web Dynpro component and go to the context menu (right click) → Create → View" }, { "code": null, "e": 16662, "s": 16585, "text": "Step 2 − Create a view MAINVIEW as the following and click on the tick mark." }, { "code": null, "e": 16733, "s": 16662, "text": "This will open view editor in ABAP workbench under the name − MAINVIEW" }, { "code": null, "e": 16865, "s": 16733, "text": "Step 3 − If you want to open the layout tab and view designer, you may need to enter the application server user name and password." }, { "code": null, "e": 16906, "s": 16865, "text": "Step 4 − Click the save icon at the top." }, { "code": null, "e": 16997, "s": 16906, "text": "When you save, it comes under the object tree and you can check by expanding the view tab." }, { "code": null, "e": 17142, "s": 16997, "text": "Step 5 − To assign the window to this view, select the window ZZ_00_TEST under the window tab and click on Change mode at the top of the screen." }, { "code": null, "e": 17199, "s": 17142, "text": "Step 6 − You can right-click → Display → In Same Window." }, { "code": null, "e": 17332, "s": 17199, "text": "Step 7 − Now open the view structure and move the view MAINVIEW inside the window structure on the right hand side by Drag and Drop." }, { "code": null, "e": 17430, "s": 17332, "text": "Step 8 − Open the window structure on the right hand side and you will see the embedded MAINVIEW." }, { "code": null, "e": 17492, "s": 17430, "text": "Step 9 − Save by clicking the Save icon on top of the screen." }, { "code": null, "e": 17654, "s": 17492, "text": "Step 1 − Open the View Editor to view MAINVIEW and switch to tab Context. Create a context node in the View Controller by opening the corresponding context menu." }, { "code": null, "e": 17717, "s": 17654, "text": "Step 2 − Select the View in the object tree and click Display." }, { "code": null, "e": 17907, "s": 17717, "text": "Step 3 − Maintain the Properties in the next window. Select the cardinality and dictionary structure (table). Select Add Attribute from Structure and select the components of the structure." }, { "code": null, "e": 18039, "s": 17907, "text": "Step 4 − To select all the components, click Select all option at the top and then click the tick mark at the bottom of the screen." }, { "code": null, "e": 18343, "s": 18039, "text": "A context node TEST_NODE has been created, which refers to the data structure of the table and which can contain 0 → n entries at runtime. The context node has been created in the view context, since no data exchange with other views is planned hence component controller context usage is not necessary." }, { "code": null, "e": 18408, "s": 18343, "text": "Step 5 − Save the changes to MAINVIEW by clicking the Save icon." }, { "code": null, "e": 18569, "s": 18408, "text": "Step 6 − Go to the Layout tab of MAINVIEW. Insert a new UI element of the type table under ROOTUIELEMENT CONTAINER and assign the properties in the given table." }, { "code": null, "e": 18618, "s": 18569, "text": "Step 7 − Enter the name of the element and type." }, { "code": null, "e": 18768, "s": 18618, "text": "Step 8 − Create the binding of TEST_TABLE with context node TEST_NODE. Select Text View as Standard Cell Editors and activate bindings for all cells." }, { "code": null, "e": 18855, "s": 18768, "text": "Step 9 − Click the Context button. Select the context node as TEST_NODE from the list." }, { "code": null, "e": 18913, "s": 18855, "text": "Step 10 − You can see all the attributes by selecting it." }, { "code": null, "e": 19052, "s": 18913, "text": "Step 11 − Activate all the checkboxes under Binding for all context attributes by selecting them. Confirm Entry by pressing the Enter key." }, { "code": null, "e": 19087, "s": 19052, "text": "The result should look like this −" }, { "code": null, "e": 19115, "s": 19087, "text": "Step 12 − Save the changes." }, { "code": null, "e": 19234, "s": 19115, "text": "Step 13 − To supply data to TEST table, go to Methods tab and double-click method WDDOINIT. Enter the following code −" }, { "code": null, "e": 19636, "s": 19234, "text": "method WDDOINIT .\n* data declaration\ndata:\nNode_TEST type REF TO IF_WD_CONTEXT_NODE,\nItab_TEST type standard table of TEST.\n* get data from table TEST\nselect * from TEST into table Itab_TEST.\n* navigate from <CONTEXT> to <TEST> via lead selection\nNode_TEST = wd_Context->get_Child_Node( Name = `TEST_NODE` ).\n* bind internal table to context node <TEST>\nNode_TEST->Bind_Table( Itab_TEST ).\nendmethod.\n" }, { "code": null, "e": 19805, "s": 19636, "text": "Web Dynpro applications, you should not access database tables directly from Web Dynpro methods, however, you should use supply functions or BAPI calls for data access." }, { "code": null, "e": 19880, "s": 19805, "text": "Step 14 − Save the changes by clicking the save icon on top of the screen." }, { "code": null, "e": 19984, "s": 19880, "text": "Step 1 − Select the ZZ_00_TEST component in the object tree → right-click and create a new application." }, { "code": null, "e": 20040, "s": 19984, "text": "Step 2 − Enter the application name and click continue." }, { "code": null, "e": 20091, "s": 20040, "text": "Step 3 − Save the changes. Save as a local object." }, { "code": null, "e": 20144, "s": 20091, "text": "Next is activating objects in Web Dynpro component −" }, { "code": null, "e": 20214, "s": 20144, "text": "Step 4 − Double-click on the component ZZ_00_TEST and click Activate." }, { "code": null, "e": 20266, "s": 20214, "text": "Step 5 − Select all the objects and click continue." }, { "code": null, "e": 20353, "s": 20266, "text": "Step 6 − To run the application, select Web Dynpro application → Right-click and Test." }, { "code": null, "e": 20418, "s": 20353, "text": "A browser will be started and Web Dypro application will be run." }, { "code": null, "e": 20574, "s": 20418, "text": "In a Web Dynpro application, the component window has an inbound plug. This inbound plug can have parameters, which have to be specified as URL parameters." }, { "code": null, "e": 20775, "s": 20574, "text": "Default values that are overwritten by the URL parameters can be set in the application for these parameters. If neither a default value nor a URL parameter is specified, a runtime error is triggered." }, { "code": null, "e": 20889, "s": 20775, "text": "To create a new inbound plug, specify plug as a startup and data type should be a string. Activate the component." }, { "code": null, "e": 20975, "s": 20889, "text": "Next is to specify the component to be called, parameters, window, and start-up plug." }, { "code": null, "e": 21049, "s": 20975, "text": "Call the application and URL parameters overwrite application parameters." }, { "code": null, "e": 21339, "s": 21049, "text": "When you create a Web Dynpro component, the creation procedure creates a component interface. Each component interface contains exactly one interface controller and one interface view. The interface view has no direct connection with the interface controller and are created automatically." }, { "code": null, "e": 21462, "s": 21339, "text": "Using the component interface, you can define the interface structure and you can use in different application components." }, { "code": null, "e": 21582, "s": 21462, "text": "The interface controller of a component interface definition and the interface controller of a component are different." }, { "code": null, "e": 21666, "s": 21582, "text": "You can add multiple number of interface views to a component interface definition." }, { "code": null, "e": 21723, "s": 21666, "text": "Consider the same screenshot as in the previous chapter." }, { "code": null, "e": 21787, "s": 21723, "text": "Step 1 − Enter the name of the new component and click display." }, { "code": null, "e": 21846, "s": 21787, "text": "Step 2 − In the next window, enter the following details −" }, { "code": null, "e": 21893, "s": 21846, "text": "You can enter a description of this component." }, { "code": null, "e": 21933, "s": 21893, "text": "In type, select a Web Dynpro component." }, { "code": null, "e": 21983, "s": 21933, "text": "You can also maintain the name of default window." }, { "code": null, "e": 22057, "s": 21983, "text": "Step 3 − Assign this component to Package $TMP and click the Save button." }, { "code": null, "e": 22152, "s": 22057, "text": "When you click on save, you can see this new component under the object tree and it contains −" }, { "code": null, "e": 22173, "s": 22152, "text": "Component Controller" }, { "code": null, "e": 22193, "s": 22173, "text": "Component Interface" }, { "code": null, "e": 22198, "s": 22193, "text": "View" }, { "code": null, "e": 22206, "s": 22198, "text": "Windows" }, { "code": null, "e": 22395, "s": 22206, "text": "Faceless components in Web Dynpro do not contain any graphical components, no views and no windows. It only contains a component controller and you can add an additional custom controller." }, { "code": null, "e": 22617, "s": 22395, "text": "Faceless components are specifically used for receiving and structuring the data. Faceless components can be embedded to other components using the component usage and you can supply the required data to these components." }, { "code": null, "e": 22661, "s": 22617, "text": "Step 1 − Create a new Web Dynpro component." }, { "code": null, "e": 22712, "s": 22661, "text": "Step 2 − Select the package and click save button." }, { "code": null, "e": 22796, "s": 22712, "text": "Step 3 − To create a Faceless component, delete the two elements − View and Window." }, { "code": null, "e": 23002, "s": 22796, "text": "In Web Dynpro component, you can create a uniquely assigned class inherited from the abstract class. Assistance class can store the coding that is required in a component but is not linked with the layout." }, { "code": null, "e": 23134, "s": 23002, "text": "You can store dynamic text in assistance class, text combined at run time or contains variable that can be stored in the text pool." }, { "code": null, "e": 23267, "s": 23134, "text": "In Assistance class, you can also save a code that is not directly linked with the layout of the application or with the controller." }, { "code": null, "e": 23482, "s": 23267, "text": "Using the method _WD_COMPONENT_ASSISTANCE~GET_TEXT( ) allows you to access text symbols of the assistance class in the controller of your component. When you call the method, 3-digit id of the text symbol is used −" }, { "code": null, "e": 23623, "s": 23482, "text": "method MY_CONTROLLER_METHOD .\ndata: my_text type string.\nmy_text = WD_ASSIST->IF_WD_COMPONENT_ASSISTANCE~GET_TEXT( KEY = ‘001’ ).\nEndmethod\n" }, { "code": null, "e": 23739, "s": 23623, "text": "You can maintain text symbols in assistance class using each controller. Click on Go to → Text Symbols in the menu." }, { "code": null, "e": 23931, "s": 23739, "text": "Note − Each ABAP class can act as assistance class but service integrated with Web Dynpro application is only available if assistance class is derived from class − CL_WD_COMPONENT_ASSISTANCE." }, { "code": null, "e": 24100, "s": 23931, "text": "You can call an existing functional module in a Web Dynpro component using a service call. To create a service call, you can use easy-to-use wizard in Web Dynpro tools." }, { "code": null, "e": 24170, "s": 24100, "text": "You can launch the wizard in ABAP workbench to create a service call." }, { "code": null, "e": 24188, "s": 24170, "text": "Run T-Code − SE80" }, { "code": null, "e": 24294, "s": 24188, "text": "Step 1 − Select Web Dynpro component → Right-click to open the context menu. Go to create → Service call." }, { "code": null, "e": 24341, "s": 24294, "text": "It will open Web Dynpro wizard − Start screen." }, { "code": null, "e": 24471, "s": 24341, "text": "Step 2 − You can select if you want service call to be embedded in an existing controller or you want to create a new controller." }, { "code": null, "e": 24599, "s": 24471, "text": "Note − The service calls should be embedded in global controllers and it can’t be used with the view controllers in Web Dynpro." }, { "code": null, "e": 24680, "s": 24599, "text": "Step 3 − In the next window, select the service type. Click the Continue button." }, { "code": null, "e": 24785, "s": 24680, "text": "Step 4 − In the next window, select a function module as a service. You can use the input help for this." }, { "code": null, "e": 25013, "s": 24785, "text": "If you choose a remote capable function module, you can optionally specify an RFC destination that is to be used when calling the function module. If you do not specify a destination, the function module will be called locally." }, { "code": null, "e": 25186, "s": 25013, "text": "Note − The function module must exist in the current system! The wizard does not support to call a remote capable function module that does not exist in the current system." }, { "code": null, "e": 25211, "s": 25186, "text": "Step 5 − Click Continue." }, { "code": null, "e": 25352, "s": 25211, "text": "Step 6 − In the next window, you can choose which object type to use to represent the service function parameters in Web Dynpro controller −" }, { "code": null, "e": 25392, "s": 25352, "text": "As a parameter of the controller method" }, { "code": null, "e": 25418, "s": 25392, "text": "As a controller attribute" }, { "code": null, "e": 25459, "s": 25418, "text": "As a context node or a context attribute" }, { "code": null, "e": 25544, "s": 25459, "text": "To do this, select the required object type from the list box in the relevant lines." }, { "code": null, "e": 25606, "s": 25544, "text": "Note − Only UI-relevant data should be stored in the context." }, { "code": null, "e": 25700, "s": 25606, "text": "You can also individually name the controller attributes and the context nodes to be created." }, { "code": null, "e": 25738, "s": 25700, "text": "The following proposal is generated −" }, { "code": null, "e": 25786, "s": 25738, "text": "The root node receives the name of the service." }, { "code": null, "e": 25834, "s": 25786, "text": "The root node receives the name of the service." }, { "code": null, "e": 25969, "s": 25834, "text": "The nodes for grouping the parameters according to their declaration types receive appropriate names such as IMPORTING, EXPORTING, ..." }, { "code": null, "e": 26104, "s": 25969, "text": "The nodes for grouping the parameters according to their declaration types receive appropriate names such as IMPORTING, EXPORTING, ..." }, { "code": null, "e": 26207, "s": 26104, "text": "The node names and attribute names for the parameters themselves are identical to the parameter names." }, { "code": null, "e": 26310, "s": 26207, "text": "The node names and attribute names for the parameters themselves are identical to the parameter names." }, { "code": null, "e": 26437, "s": 26310, "text": "As the length of the node and the attribute names is limited to 20 characters, they are abbreviated accordingly, if necessary." }, { "code": null, "e": 26564, "s": 26437, "text": "As the length of the node and the attribute names is limited to 20 characters, they are abbreviated accordingly, if necessary." }, { "code": null, "e": 26690, "s": 26564, "text": "In the next window, selected service uses types from type groups as parameter types and/or defines implicit table parameters." }, { "code": null, "e": 26901, "s": 26690, "text": "For all the types listed below, define (table) types with the same equal structure in the Data Dictionary. These will then be used for typing of controller attributes or method parameters created by the wizard." }, { "code": null, "e": 26958, "s": 26901, "text": "Step 7 − Enter Attribute Type − TEST and click Continue." }, { "code": null, "e": 27132, "s": 26958, "text": "Step 8 − In the next window, specify the name of the method that should execute the service. The wizard generates coding for calling the service and for the context binding." }, { "code": null, "e": 27181, "s": 27132, "text": "The method must not yet exist in the controller." }, { "code": null, "e": 27283, "s": 27181, "text": "You have now entered all the necessary information for the creation of the model-oriented controller." }, { "code": null, "e": 27393, "s": 27283, "text": "Step 9 − Click ‘Complete’ to create the controller, or enhance it respectively, to generate the service call." }, { "code": null, "e": 27481, "s": 27393, "text": "You can also cancel the wizard at this position. However, data entered before are lost." }, { "code": null, "e": 27875, "s": 27481, "text": "When a service call is created, a function module is available to the component. Now it is possible to choose a view in order to display the elements of the database table in the browser. Provided the global controller is not the component controller, a use page of the global controller must be entered for the controller of the selected view. Afterwards, there should be mapping of the node." }, { "code": null, "e": 27962, "s": 27875, "text": "FUNCMODUL1 onto the node with the same name in a view controller context is generated." }, { "code": null, "e": 28252, "s": 27962, "text": "To fill the context node FUNCMODUL1 of the view controller context with the data of the database table, the method EXECUTE_FUNCMODULE of the global controller is called its supply function. For this purpose, you must create such a supply function by calling the method EXECUTE_FUNCMODULE1." }, { "code": null, "e": 28422, "s": 28252, "text": "There are various tools in ABAP workbench that you can use for debugging purpose of source code. You can test all source code of Web Dynpro application using a debugger." }, { "code": null, "e": 28507, "s": 28422, "text": "Step 1 − To start the debugger, you have to select a new debugger in ABAP workbench." }, { "code": null, "e": 28543, "s": 28507, "text": "Step 2 − Go to Utilities → Settings" }, { "code": null, "e": 28609, "s": 28543, "text": "A dialog box now appears that contains two nested tab page areas." }, { "code": null, "e": 28660, "s": 28609, "text": "Step 3 − Choose the “parent” tab page ABAP Editor." }, { "code": null, "e": 28748, "s": 28660, "text": "The settings for ABAP Editor always open with the content of the child tab page Editor." }, { "code": null, "e": 28792, "s": 28748, "text": "Step 4 − Select the Front End Editor (New)." }, { "code": null, "e": 28891, "s": 28792, "text": "Step 5 − Now switch to the Debugging tab page in the ABAP Editor settings and select New Debugger." }, { "code": null, "e": 28940, "s": 28891, "text": "Step 6 − Save your changes and close the dialog." }, { "code": null, "e": 29075, "s": 28940, "text": "If you want to run an application in debugging mode, you need to set an external breakpoint in one of the methods in Dynpro component." }, { "code": null, "e": 29331, "s": 29075, "text": "It is suggested to set the breakpoint in method WDDOMODIFYVIEW under METHODS tab of Dynpro view. Provided that the context of the view controller is not filled using a supply method, the view is fully instantiated in the phase model at this point in time." }, { "code": null, "e": 29466, "s": 29331, "text": "Note − The method in which you set the breakpoint depends on the purpose of the test run and it is advised to set it in WDDMODIFYVIEW." }, { "code": null, "e": 29559, "s": 29466, "text": "When you start a Web Dynpro application, a debugger automatically starts in another session." }, { "code": null, "e": 29766, "s": 29559, "text": "You can use version management to manage the older version of an object, compare the versions or you can also reset them. In version management, you can store different versions of ABAP development objects." }, { "code": null, "e": 29828, "s": 29766, "text": "In an ABAP workbench, you can compare different versions of −" }, { "code": null, "e": 29834, "s": 29828, "text": "Views" }, { "code": null, "e": 29842, "s": 29834, "text": "Windows" }, { "code": null, "e": 29854, "s": 29842, "text": "Controllers" }, { "code": null, "e": 30026, "s": 29854, "text": "You can also store a version of an object without releasing it. To perform this, select the object in the editor area and go to Utilities tab → Versions → Generate Version" }, { "code": null, "e": 30126, "s": 30026, "text": "Before version generation, you can see no version in the database, if you go to version management." }, { "code": null, "e": 30212, "s": 30126, "text": "When you click on Generate version, you get a confirmation that a version is created." }, { "code": null, "e": 30260, "s": 30212, "text": "Go to Utilities → Versions → Version Management" }, { "code": null, "e": 30399, "s": 30260, "text": "It shows all the stored version of the selected object in version database. It consists of all previously released or all active versions." }, { "code": null, "e": 30503, "s": 30399, "text": "To start comparison of objects, select object and click the comparison button at the top of the screen." }, { "code": null, "e": 30593, "s": 30503, "text": "For all versions, a comparison is performed and any difference is highlighted in a table." }, { "code": null, "e": 30857, "s": 30593, "text": "In ABAP Workbench, you can also create and show messages that contain information for end users of Dynpro application. These messages are displayed on the screen. These are user interactive messages that display important information about Web Dynpro application." }, { "code": null, "e": 30989, "s": 30857, "text": "To provide users with information, warning or error details, you can program these methods in ABAP workbench using runtime service." }, { "code": null, "e": 31144, "s": 30989, "text": "These messages are configured under Setting on Web Dynpro application. You can assign different settings for handling messages in Web Dynpro application −" }, { "code": null, "e": 31228, "s": 31144, "text": "Show message component − In this case, if the message exists, it will be displayed." }, { "code": null, "e": 31332, "s": 31228, "text": "Always show message component − Even if there is no message, the message component is shown at the top." }, { "code": null, "e": 31450, "s": 31332, "text": "The message is displayed without the component − In this setting, one message is displayed and no message log exists." }, { "code": null, "e": 31585, "s": 31450, "text": "All these user messages are shown in the status bar. The user can navigate to the UI element to remove the error in the error message." }, { "code": null, "e": 31813, "s": 31585, "text": "Messages in popup window − In this configuration, you can set the message to display in the popup window, irrespective of what is configured in Web Dynpro application. You can configure the following popup messages to display −" }, { "code": null, "e": 31848, "s": 31813, "text": "Messages belong to specific window" }, { "code": null, "e": 31874, "s": 31848, "text": "All the messages till now" }, { "code": null, "e": 31886, "s": 31874, "text": "No messages" }, { "code": null, "e": 32025, "s": 31886, "text": "You can use the message manager to integrate messages into the message log. You can open the message manager using Web Dynpro code wizard." }, { "code": null, "e": 32180, "s": 32025, "text": "You can open Web Dynpro code wizard from the tool bar. It is available when your ABAP workbench is in change mode or while editing a view or a controller." }, { "code": null, "e": 32267, "s": 32180, "text": "To set ABAP workbench in the change mode, select the view and go to context to Change." }, { "code": null, "e": 32327, "s": 32267, "text": "You can use the following methods for triggering messages −" }, { "code": null, "e": 32387, "s": 32327, "text": "IS_EMPTY − This is used to query if there are any messages." }, { "code": null, "e": 32447, "s": 32387, "text": "IS_EMPTY − This is used to query if there are any messages." }, { "code": null, "e": 32502, "s": 32447, "text": "CLEAR_MESSAGES − This is used to deletes all messages." }, { "code": null, "e": 32557, "s": 32502, "text": "CLEAR_MESSAGES − This is used to deletes all messages." }, { "code": null, "e": 32660, "s": 32557, "text": "REPORT_ATTRIBUTE_ERROR_MESSAGE − This is used to report a Web Dynpro exception to a context attribute." }, { "code": null, "e": 32763, "s": 32660, "text": "REPORT_ATTRIBUTE_ERROR_MESSAGE − This is used to report a Web Dynpro exception to a context attribute." }, { "code": null, "e": 32862, "s": 32763, "text": "REPORT_ATTRIBUTE_EXCEPTION − This is used to report a Web Dynpro exception to a context attribute." }, { "code": null, "e": 32961, "s": 32862, "text": "REPORT_ATTRIBUTE_EXCEPTION − This is used to report a Web Dynpro exception to a context attribute." }, { "code": null, "e": 33054, "s": 32961, "text": "REPORT_ERROR_MESSAGE − This is used to report a Web Dynpro message with optional parameters." }, { "code": null, "e": 33147, "s": 33054, "text": "REPORT_ERROR_MESSAGE − This is used to report a Web Dynpro message with optional parameters." }, { "code": null, "e": 33232, "s": 33147, "text": "REPORT_EXCEPTION − This is used to report a Web Dynpro exception that may come back." }, { "code": null, "e": 33317, "s": 33232, "text": "REPORT_EXCEPTION − This is used to report a Web Dynpro exception that may come back." }, { "code": null, "e": 33422, "s": 33317, "text": "REPORT_FATAL_ERROR_MESSAGE − This is used to report a fatal Web Dynpro message with optional parameters." }, { "code": null, "e": 33527, "s": 33422, "text": "REPORT_FATAL_ERROR_MESSAGE − This is used to report a fatal Web Dynpro message with optional parameters." }, { "code": null, "e": 33605, "s": 33527, "text": "REPORT_FATAL_EXCEPTION − This is used to report a fatal Web Dynpro exception." }, { "code": null, "e": 33683, "s": 33605, "text": "REPORT_FATAL_EXCEPTION − This is used to report a fatal Web Dynpro exception." }, { "code": null, "e": 33742, "s": 33683, "text": "REPORT_SUCCESS − This is used to report a success message." }, { "code": null, "e": 33801, "s": 33742, "text": "REPORT_SUCCESS − This is used to report a success message." }, { "code": null, "e": 33876, "s": 33801, "text": "REPORT_T100_MESSAGE − This is used to report a message using a T100 entry." }, { "code": null, "e": 33951, "s": 33876, "text": "REPORT_T100_MESSAGE − This is used to report a message using a T100 entry." }, { "code": null, "e": 34002, "s": 33951, "text": "REPORT_WARNING − This is used to report a warning." }, { "code": null, "e": 34053, "s": 34002, "text": "REPORT_WARNING − This is used to report a warning." }, { "code": null, "e": 34201, "s": 34053, "text": "As per the business requirement, you can implement many standard applications and the UI of Web Dynpro application can vary as per the requirement." }, { "code": null, "e": 34311, "s": 34201, "text": "To configure a Web Dynpro application, you first configure data records for individual Web Dynpro components." }, { "code": null, "e": 34384, "s": 34311, "text": "Using the component configuration, it allows you to manage the behavior." }, { "code": null, "e": 34609, "s": 34384, "text": "Next is to configure the application. All the components that are created require to be used in the specific configuration. The configuration of Web Dynpro application defines which component is configured in an application." }, { "code": null, "e": 34662, "s": 34609, "text": "In ABAP object list, select a Web Dynpro component −" }, { "code": null, "e": 34705, "s": 34662, "text": "Right-click → Create/Change configuration." }, { "code": null, "e": 34871, "s": 34705, "text": "This opens a browser with the dialog window of the configurator. The mode Component Configurator is active and you enter a name for your new component configuration." }, { "code": null, "e": 34973, "s": 34871, "text": "You can also define implicit and explicit configuration. Save the configuration and close the window." }, { "code": null, "e": 35140, "s": 34973, "text": "Note − You can save a new configuration only when it actually contains values. An empty configuration file that doesn’t contain any data and has a name is not stored." }, { "code": null, "e": 35373, "s": 35140, "text": "As this configurator is not part of the ABAP Workbench and runs separately in the browser, you need to update the hierarchy of the object list in the workbench after completion of the creation or change procedure in a configuration." }, { "code": null, "e": 35440, "s": 35373, "text": "This allows you to store different configurations for each object." }, { "code": null, "e": 35658, "s": 35440, "text": "When you save the application configuration, you can’t check the changes made by an administrator and an end user. There is a need to store customization and personalization data that allows merged data to be managed." }, { "code": null, "e": 35702, "s": 35658, "text": "The following points should be considered −" }, { "code": null, "e": 35778, "s": 35702, "text": "Application users and administrators should be able to reverse the changes." }, { "code": null, "e": 35854, "s": 35778, "text": "Application users and administrators should be able to reverse the changes." }, { "code": null, "e": 35943, "s": 35854, "text": "Customization changes of an application should be visible to the user for all the pages." }, { "code": null, "e": 36032, "s": 35943, "text": "Customization changes of an application should be visible to the user for all the pages." }, { "code": null, "e": 36283, "s": 36032, "text": "Application administrator should have access to mark the report as final and this should be valid for all users. When an administrator flags a property final, any changes to the value as a personalization of a single user must no longer be permitted." }, { "code": null, "e": 36534, "s": 36283, "text": "Application administrator should have access to mark the report as final and this should be valid for all users. When an administrator flags a property final, any changes to the value as a personalization of a single user must no longer be permitted." }, { "code": null, "e": 36668, "s": 36534, "text": "You can integrate an ABAP application into the enterprise portal. You can also manage portal functions from a Web Dynpro application." }, { "code": null, "e": 36792, "s": 36668, "text": "You can call Web Dynpro code wizard to access portal manager methods. This can be used to perform the following functions −" }, { "code": null, "e": 36888, "s": 36792, "text": "Portal Events − To navigate between Web Dynpro application within the portal or portal content." }, { "code": null, "e": 36931, "s": 36888, "text": "Following navigation types are supported −" }, { "code": null, "e": 36955, "s": 36931, "text": "Object-based navigation" }, { "code": null, "e": 36975, "s": 36955, "text": "Absolute navigation" }, { "code": null, "e": 36995, "s": 36975, "text": "Relative navigation" }, { "code": null, "e": 37110, "s": 36995, "text": "Work Protect Mode − For portal integration, following Web Dynpro applications are available in package SWDP_TEST −" }, { "code": null, "e": 37151, "s": 37110, "text": "WDR_TEST_PORTAL_EVENT_FIRE\nTrigger event" }, { "code": null, "e": 37178, "s": 37151, "text": "WDR_TEST_PORTAL_EVENT_FIRE" }, { "code": null, "e": 37192, "s": 37178, "text": "Trigger event" }, { "code": null, "e": 37239, "s": 37192, "text": "WDR_TEST_PORTAL_EVENT_FIRE2\nTrigger free event" }, { "code": null, "e": 37267, "s": 37239, "text": "WDR_TEST_PORTAL_EVENT_FIRE2" }, { "code": null, "e": 37286, "s": 37267, "text": "Trigger free event" }, { "code": null, "e": 37334, "s": 37286, "text": "WDR_TEST_PORTAL_NAV_OBN\nObject-based navigation" }, { "code": null, "e": 37358, "s": 37334, "text": "WDR_TEST_PORTAL_NAV_OBN" }, { "code": null, "e": 37382, "s": 37358, "text": "Object-based navigation" }, { "code": null, "e": 37423, "s": 37382, "text": "WDR_TEST_PORTAL_NAV_PAGE\nPage navigation" }, { "code": null, "e": 37448, "s": 37423, "text": "WDR_TEST_PORTAL_NAV_PAGE" }, { "code": null, "e": 37464, "s": 37448, "text": "Page navigation" }, { "code": null, "e": 37512, "s": 37464, "text": "WDR_TEST_PORTAL_WORKPROTECT\nSecurity monitoring" }, { "code": null, "e": 37540, "s": 37512, "text": "WDR_TEST_PORTAL_WORKPROTECT" }, { "code": null, "e": 37560, "s": 37540, "text": "Security monitoring" }, { "code": null, "e": 37607, "s": 37560, "text": "WDR_TEST_PORTAL_EVENT_REC\nReceive portal event" }, { "code": null, "e": 37633, "s": 37607, "text": "WDR_TEST_PORTAL_EVENT_REC" }, { "code": null, "e": 37654, "s": 37633, "text": "Receive portal event" }, { "code": null, "e": 37707, "s": 37654, "text": "WDR_TEST_PORTAL_EVENT_REC2\nReceive free portal event" }, { "code": null, "e": 37734, "s": 37707, "text": "WDR_TEST_PORTAL_EVENT_REC2" }, { "code": null, "e": 37760, "s": 37734, "text": "Receive free portal event" }, { "code": null, "e": 37834, "s": 37760, "text": "Following are the steps to integrate Web Dynpro ABAP (WDA) in the portal." }, { "code": null, "e": 37917, "s": 37834, "text": "Step 1 − Go to ABAP workbench using T-code − SE80 and create Web Dynpro component." }, { "code": null, "e": 37962, "s": 37917, "text": "Step 2 − Save the component and activate it." }, { "code": null, "e": 38057, "s": 37962, "text": "Step 3 − Define data binding and context mapping. Create a Web Dynpro application and save it." }, { "code": null, "e": 38097, "s": 38057, "text": "Step 4 − Login to SAP NetWeaver portal." }, { "code": null, "e": 38157, "s": 38097, "text": "Step 5 − Go to Portal Content → Content Administration tab." }, { "code": null, "e": 38225, "s": 38157, "text": "Step 6 − Right-click on the portal content and create a new folder." }, { "code": null, "e": 38274, "s": 38225, "text": "Step 7 − Enter the folder name and click Finish." }, { "code": null, "e": 38341, "s": 38274, "text": "Step 8 − Right-click on the created folder and create a new iView." }, { "code": null, "e": 38437, "s": 38341, "text": "Step 9 − Select iView template. Create an iView from an existing iView template and click Next." }, { "code": null, "e": 38503, "s": 38437, "text": "Step 10 − Select SAP Web Dynpro iView as template and click Next." }, { "code": null, "e": 38619, "s": 38503, "text": "Step 11 − Enter iView name, iView ID, iView prefix ID and click Next. Enter definition type as ABAP and click Next." }, { "code": null, "e": 38681, "s": 38619, "text": "Step 12 − Enter Web Dynpro details and ECC system is created." }, { "code": null, "e": 38816, "s": 38681, "text": "Step 13 − Enter application parameter in the same screen and click Next. You will be prompted to see the summary screen. Click Finish." }, { "code": null, "e": 39124, "s": 38816, "text": "You can create forms based on Adobe software and can use in context for Web Dynpro user interfaces. You can integrate Adobe lifecycle development tool with ABAP editor to ease the development of user interface. Interactive forms using Adobe software allows you to efficiently and easily develop UI elements." }, { "code": null, "e": 39189, "s": 39124, "text": "Following scenarios can be used for creating interactive forms −" }, { "code": null, "e": 39210, "s": 39189, "text": "Interactive scenario" }, { "code": null, "e": 39225, "s": 39210, "text": "Print scenario" }, { "code": null, "e": 39242, "s": 39225, "text": "Offline scenario" }, { "code": null, "e": 39266, "s": 39242, "text": "Using digital signature" }, { "code": null, "e": 39339, "s": 39266, "text": "You can create forms independently using form editor. Go to T-code − SFP" }, { "code": null, "e": 39440, "s": 39339, "text": "When you click Create, you will be prompted to enter the form name, form description, and interface." }, { "code": null, "e": 39565, "s": 39440, "text": "The example component for the interactive scenario in the system are available in the package SWDP_TEST → WDR_TEST_IA_FORMS." }, { "code": null, "e": 39812, "s": 39565, "text": "In a Dynpro application, both scenarios - print scenario and interactive scenario − for inserting interactive forms is similar. The form that contains the static components can be used to display data in a Dynpro application using Print scenario." }, { "code": null, "e": 39909, "s": 39812, "text": "Using interactive forms, you can reuse entries in Web Dynpro context for Web Dynpro application." }, { "code": null, "e": 39962, "s": 39909, "text": "Step 1 − Create a view of your Web Dynpro component." }, { "code": null, "e": 40043, "s": 39962, "text": "Step 2 − Right-click on View and create a node. This node will be bound to form." }, { "code": null, "e": 40117, "s": 40043, "text": "Step 3 − Drag the interactive form from Adobe library to Designer window." }, { "code": null, "e": 40185, "s": 40117, "text": "Step 4 − Design the form, enter the name, and bound the attributes." }, { "code": null, "e": 40355, "s": 40185, "text": "Step 5 − Once you are done with the form design, go to edit mode in the workbench and define if the form is static content, PDF-based print form, or an interactive form." }, { "code": null, "e": 40668, "s": 40355, "text": "SAP List Viewer is used to add an ALV component and provides a flexible environment to display lists and tabular structure. A standard output consists of header, toolbar, and an output table. The user can adjust the settings to add column display, aggregations, and sorting options using additional dialog boxes." }, { "code": null, "e": 40708, "s": 40668, "text": "Following are the key features of ALV −" }, { "code": null, "e": 40804, "s": 40708, "text": "It supports many properties of the table element as it is based on Web Dynpro table UI element." }, { "code": null, "e": 40900, "s": 40804, "text": "It supports many properties of the table element as it is based on Web Dynpro table UI element." }, { "code": null, "e": 40967, "s": 40900, "text": "ALV output can be filtered, sorted, or you can apply calculations." }, { "code": null, "e": 41034, "s": 40967, "text": "ALV output can be filtered, sorted, or you can apply calculations." }, { "code": null, "e": 41120, "s": 41034, "text": "The user can perform application specific functions using UI elements in the toolbar." }, { "code": null, "e": 41206, "s": 41120, "text": "The user can perform application specific functions using UI elements in the toolbar." }, { "code": null, "e": 41262, "s": 41206, "text": "Allows the user to save the setting in different views." }, { "code": null, "e": 41318, "s": 41262, "text": "Allows the user to save the setting in different views." }, { "code": null, "e": 41380, "s": 41318, "text": "Allows to configure special areas above and below ALV output." }, { "code": null, "e": 41442, "s": 41380, "text": "Allows to configure special areas above and below ALV output." }, { "code": null, "e": 41505, "s": 41442, "text": "Allows to define the extent to which ALV output can be edited." }, { "code": null, "e": 41568, "s": 41505, "text": "Allows to define the extent to which ALV output can be edited." }, { "code": null, "e": 41610, "s": 41568, "text": "Following are the steps to create an ALV." }, { "code": null, "e": 41774, "s": 41610, "text": "Step 1 − Use T-code: SE80. Select Web Dynpro comp/intf from the list and enter the name. Click on display. You will be prompted create the component. Click on Yes." }, { "code": null, "e": 41861, "s": 41774, "text": "Step 2 − Select type as Web Dynpro component. Enter the Window name and the View name." }, { "code": null, "e": 41891, "s": 41861, "text": "Step 3 − Click the tick mark." }, { "code": null, "e": 42015, "s": 41891, "text": "Step 4 − In the change window, enter the component use as ALV, component as SALV_WD_TABLE and description as ALV component." }, { "code": null, "e": 42145, "s": 42015, "text": "Step 5 − Go to Component Controller and right-click the context. Then select Create Node MAKT with the dictionary structure MAKT." }, { "code": null, "e": 42234, "s": 42145, "text": "Step 6 − Select the required attributes from MAKT by using Add Attribute from Structure." }, { "code": null, "e": 42369, "s": 42234, "text": "Step 7 − Remove the dictionary structure MAKT from the node MAKT and set the properties as follows (Cardinality, Lead selection, etc.)" }, { "code": null, "e": 42455, "s": 42369, "text": "Step 8 − Right-click on Component usage in the Object tree → Create Controller Usage." }, { "code": null, "e": 42521, "s": 42455, "text": "Step 9 − Go to View → Context tab and drag MAKT node to the view." }, { "code": null, "e": 42589, "s": 42521, "text": "After mapping, it will appear as shown in the following screenshot." }, { "code": null, "e": 42644, "s": 42589, "text": "Step 10 − Go to Layout and right-click Insert Element." }, { "code": null, "e": 42706, "s": 42644, "text": "The layout will appear as shown in the following screenshot −" }, { "code": null, "e": 42798, "s": 42706, "text": "Step 11 − Go to Properties tab, click create controller usage to add the following to View." }, { "code": null, "e": 42850, "s": 42798, "text": "Step 12 − Go to method, use WDDOINIT to write code." }, { "code": null, "e": 42968, "s": 42850, "text": "Step 13 − Double-click on the method to enter the code. Enter the following code and initiate the used component ALV." }, { "code": null, "e": 43008, "s": 42968, "text": "Use GET_MODEL method in the controller." }, { "code": null, "e": 43090, "s": 43008, "text": "Step 14 − Bind the table to the context node using BIND_TABLE method as follows −" }, { "code": null, "e": 43183, "s": 43090, "text": "Step 15 − Go to Window in the Object tree and right-click C1 to embed ALV table to the view." }, { "code": null, "e": 43240, "s": 43183, "text": "Once you embed the ALV table, it will appear like this −" }, { "code": null, "e": 43360, "s": 43240, "text": "Step 16 − The last step is to create a Web Dynpro application under the object tree. Enter the name of the application." }, { "code": null, "e": 43436, "s": 43360, "text": "Step 17 − To execute application, double-click and you will see the output." }, { "code": null, "e": 43658, "s": 43436, "text": "Using filters, you can limit the data in ALV output. You can create multiple number of filter conditions for each field. To create or delete a filter condition, you can use the method of interface class IF_SALV_WD_FILTER." }, { "code": null, "e": 43748, "s": 43658, "text": "You can use the following methods for creating, getting, and deleting filter conditions −" }, { "code": null, "e": 43852, "s": 43748, "text": "In Web Dynpro ABAP administration, you can perform various administration tasks using different tools −" }, { "code": null, "e": 43864, "s": 43852, "text": "ICM Tracing" }, { "code": null, "e": 43886, "s": 43864, "text": "Web Dynpro Trace tool" }, { "code": null, "e": 43902, "s": 43886, "text": "Browser Tracing" }, { "code": null, "e": 43910, "s": 43902, "text": "Logging" }, { "code": null, "e": 43919, "s": 43910, "text": "Security" }, { "code": null, "e": 44073, "s": 43919, "text": "Web Dynpro trace tool can be used for checking the errors and problems in Dynpro application. You can activate Web Dynpro trace tool for a specific user." }, { "code": null, "e": 44151, "s": 44073, "text": "Step 1 − To activate trace tool in SAP GUI client, use T-code − WD_TRACE_TOOL" }, { "code": null, "e": 44243, "s": 44151, "text": "Step 2 − Click on Activate for this user. This allows to set the trace active for the user." }, { "code": null, "e": 44306, "s": 44243, "text": "Step 3 − Select Trace features in the new window and click OK." }, { "code": null, "e": 44433, "s": 44306, "text": "Step 4 − Start Web Dynpro application that you want to trace. You can see a new area Web Dynpro trace tool in Web application." }, { "code": null, "e": 44515, "s": 44433, "text": "Step 5 − Execute the application. Enter the details of problem → Choose Continue." }, { "code": null, "e": 44675, "s": 44515, "text": "Step 6 − You can also send it with Insert and add a screenshot or you insert a file with additional information. Go to Browse → Select File and click Add File." }, { "code": null, "e": 44800, "s": 44675, "text": "Step 7 − You can download the trace file in Zip format and end tracing by clicking on Save Trace as Zip file and Stop Trace." }, { "code": null, "e": 44878, "s": 44800, "text": "This file can be uploaded to SAP portal and can be sent to SAP for debugging." }, { "code": null, "e": 44968, "s": 44878, "text": "To analyze the problem, you can also trace the data stream in SAP Web Application server." }, { "code": null, "e": 45069, "s": 44968, "text": "Step 1 − Use T-Code − SMICM. In the next window, click on GOTO → Trace File → Display file or start." }, { "code": null, "e": 45138, "s": 45069, "text": "You will see ICM trace result as shown in the following screenshot −" }, { "code": null, "e": 45267, "s": 45138, "text": "Step 2 − You can also increase the trace level from default level 1. To increase the trace level, GOTO → Trace Level → Increase." }, { "code": null, "e": 45377, "s": 45267, "text": "This is used to analyze the dynamic behavior of your code. This can be used as an alternative to ICM tracing." }, { "code": null, "e": 45454, "s": 45377, "text": "To use browser tracing, you need to install proxy tool on your local system." }, { "code": null, "e": 45616, "s": 45454, "text": "You can monitor Web Dynpro application using ABAP monitor. Information is stored about Web Dynpro application. You can view this information using T-code − RZ20." }, { "code": null, "e": 45685, "s": 45616, "text": "You can check the following information in Web Dynpro ABAP monitor −" }, { "code": null, "e": 45699, "s": 45685, "text": "Session Count" }, { "code": null, "e": 45717, "s": 45699, "text": "Application Count" }, { "code": null, "e": 45726, "s": 45717, "text": "CPU time" }, { "code": null, "e": 45731, "s": 45726, "text": "Data" }, { "code": null, "e": 45769, "s": 45731, "text": "To view the report, use T-code − RZ20" }, { "code": null, "e": 45811, "s": 45769, "text": "Step 1 − Go to SAP CCMS Monitor template." }, { "code": null, "e": 45854, "s": 45811, "text": "Step 2 − Click the sub node Entire System." }, { "code": null, "e": 45965, "s": 45854, "text": "Step 3 − Enter the system ID of the current SAP system where the application you want to monitor is installed." }, { "code": null, "e": 46001, "s": 45965, "text": "Step 4 − Select Application Server." }, { "code": null, "e": 46138, "s": 46001, "text": "Step 5 − Select the name of the relevant application server. For instance, select Web Dynpro ABAP as shown in the following screenshot −" } ]
Ruby | Random uuid() function
17 Dec, 2019 Random#uuid() : uuid() is a Random class method which checks returns a random v4 UUID (Universally Unique IDentifier). Syntax: Random.uuid() Parameter: Random values Return: a random v4 UUID (Universally Unique IDentifier). Example #1 : # Ruby code for Random.uuid() method # loading libraryrequire 'securerandom' # declaring Random valuedate_a = SecureRandom.uuid # declaring Random valuedate_b = SecureRandom.uuid # uuid valueputs "Random uuid form : #{date_a}\n\n" puts "Random uuid form : #{date_b}\n\n" Output : Random uuid form : 219474f0-60c5-43b4-8e7f-f91b5c5e1f38 Random uuid form : d6800817-c27b-4651-8d98-dc12eec46706 Example #2 : # Ruby code for Random.uuid() method # loading libraryrequire 'securerandom' # declaring Random valuedate_a = SecureRandom.uuid # declaring Random valuedate_b = SecureRandom.uuid # uuid valueputs "Random uuid form : #{date_a}\n\n" puts "Random uuid form : #{date_b}\n\n" Output : Random uuid form : f74b43f6-8b9c-4cd1-aff2-177f517b77aa Random uuid form : baba4612-6931-46a0-aa8b-7a105fd2f194 Ruby Random-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": "\n17 Dec, 2019" }, { "code": null, "e": 147, "s": 28, "text": "Random#uuid() : uuid() is a Random class method which checks returns a random v4 UUID (Universally Unique IDentifier)." }, { "code": null, "e": 169, "s": 147, "text": "Syntax: Random.uuid()" }, { "code": null, "e": 194, "s": 169, "text": "Parameter: Random values" }, { "code": null, "e": 252, "s": 194, "text": "Return: a random v4 UUID (Universally Unique IDentifier)." }, { "code": null, "e": 265, "s": 252, "text": "Example #1 :" }, { "code": "# Ruby code for Random.uuid() method # loading libraryrequire 'securerandom' # declaring Random valuedate_a = SecureRandom.uuid # declaring Random valuedate_b = SecureRandom.uuid # uuid valueputs \"Random uuid form : #{date_a}\\n\\n\" puts \"Random uuid form : #{date_b}\\n\\n\"", "e": 541, "s": 265, "text": null }, { "code": null, "e": 550, "s": 541, "text": "Output :" }, { "code": null, "e": 665, "s": 550, "text": "Random uuid form : 219474f0-60c5-43b4-8e7f-f91b5c5e1f38\n\nRandom uuid form : d6800817-c27b-4651-8d98-dc12eec46706\n\n" }, { "code": null, "e": 678, "s": 665, "text": "Example #2 :" }, { "code": "# Ruby code for Random.uuid() method # loading libraryrequire 'securerandom' # declaring Random valuedate_a = SecureRandom.uuid # declaring Random valuedate_b = SecureRandom.uuid # uuid valueputs \"Random uuid form : #{date_a}\\n\\n\" puts \"Random uuid form : #{date_b}\\n\\n\"", "e": 954, "s": 678, "text": null }, { "code": null, "e": 963, "s": 954, "text": "Output :" }, { "code": null, "e": 1078, "s": 963, "text": "Random uuid form : f74b43f6-8b9c-4cd1-aff2-177f517b77aa\n\nRandom uuid form : baba4612-6931-46a0-aa8b-7a105fd2f194\n\n" }, { "code": null, "e": 1096, "s": 1078, "text": "Ruby Random-class" }, { "code": null, "e": 1109, "s": 1096, "text": "Ruby-Methods" }, { "code": null, "e": 1114, "s": 1109, "text": "Ruby" } ]
How to add a pressed effect on button click in CSS?
30 Jul, 2021 In this tutorial, we are going to learn how to add a pressed effect on a button using CSS. This effect is a part of modern UI design and is used on many websites. This effect allows the user to experience an interaction with the button element as compared to the normal behavior. We’ll take advantage of the active pseudo class. This class is added to an HTML element automatically when it is clicked. Method 1:We can use CSS transform property to add a pressed effect on the button when it is active. CSS transform property allows us to scale, rotate, move and skew an element. Example 1: <!DOCTYPE html><html> <head> <style> /* Adding some basic styling to button */ .btn { text-decoration: none; border: none; padding: 12px 40px; font-size: 16px; background-color: green; color: #fff; border-radius: 5px; box-shadow: 7px 6px 28px 1px rgba(0, 0, 0, 0.24); cursor: pointer; outline: none; transition: 0.2s all; } /* Adding transformation when the button is active */ .btn:active { transform: scale(0.98); /* Scaling button to 0.98 to its original size */ box-shadow: 3px 2px 22px 1px rgba(0, 0, 0, 0.24); /* Lowering the shadow */ } </style></head> <body> <!-- Button with a class 'btn' --> <button class="btn">Button</button> </body> </html> Output: Method 2:For this method, we can play with the translate function in CSS. We’ll use translateY(length) function on active state of button. The translateY() function moves an element on y-axis to a given length (in px). Example 2: <!DOCTYPE html><html> <head> <style> /* Adding basic styling to a button */ .btn { padding: 15px 40px; font-size: 16px; text-align: center; cursor: pointer; outline: none; color: #fff; background-color: green; border: none; border-radius: 5px; box-shadow: box-shadow: 7px 6px 28px 1px rgba(0, 0, 0, 0.24); } /* Adding styles on 'active' state */ .btn:active { box-shadow: box-shadow: 7px 6px 28px 1px rgba(0, 0, 0, 0.24); transform: translateY(4px); /* Moving button 4px to y-axis */ } </style></head> <body> <button class="btn">Click Me</button> </body> </html> Output: You can play with other methods when the active pseudo-class is active to create your own effects when the button is clicked. CSS is the foundation of webpages, is used for webpage development by styling websites and web apps.You can learn CSS from the ground up by following this CSS Tutorial and CSS Examples. CSS-Misc CSS Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n30 Jul, 2021" }, { "code": null, "e": 332, "s": 52, "text": "In this tutorial, we are going to learn how to add a pressed effect on a button using CSS. This effect is a part of modern UI design and is used on many websites. This effect allows the user to experience an interaction with the button element as compared to the normal behavior." }, { "code": null, "e": 454, "s": 332, "text": "We’ll take advantage of the active pseudo class. This class is added to an HTML element automatically when it is clicked." }, { "code": null, "e": 631, "s": 454, "text": "Method 1:We can use CSS transform property to add a pressed effect on the button when it is active. CSS transform property allows us to scale, rotate, move and skew an element." }, { "code": null, "e": 642, "s": 631, "text": "Example 1:" }, { "code": "<!DOCTYPE html><html> <head> <style> /* Adding some basic styling to button */ .btn { text-decoration: none; border: none; padding: 12px 40px; font-size: 16px; background-color: green; color: #fff; border-radius: 5px; box-shadow: 7px 6px 28px 1px rgba(0, 0, 0, 0.24); cursor: pointer; outline: none; transition: 0.2s all; } /* Adding transformation when the button is active */ .btn:active { transform: scale(0.98); /* Scaling button to 0.98 to its original size */ box-shadow: 3px 2px 22px 1px rgba(0, 0, 0, 0.24); /* Lowering the shadow */ } </style></head> <body> <!-- Button with a class 'btn' --> <button class=\"btn\">Button</button> </body> </html>", "e": 1541, "s": 642, "text": null }, { "code": null, "e": 1549, "s": 1541, "text": "Output:" }, { "code": null, "e": 1768, "s": 1549, "text": "Method 2:For this method, we can play with the translate function in CSS. We’ll use translateY(length) function on active state of button. The translateY() function moves an element on y-axis to a given length (in px)." }, { "code": null, "e": 1779, "s": 1768, "text": "Example 2:" }, { "code": "<!DOCTYPE html><html> <head> <style> /* Adding basic styling to a button */ .btn { padding: 15px 40px; font-size: 16px; text-align: center; cursor: pointer; outline: none; color: #fff; background-color: green; border: none; border-radius: 5px; box-shadow: box-shadow: 7px 6px 28px 1px rgba(0, 0, 0, 0.24); } /* Adding styles on 'active' state */ .btn:active { box-shadow: box-shadow: 7px 6px 28px 1px rgba(0, 0, 0, 0.24); transform: translateY(4px); /* Moving button 4px to y-axis */ } </style></head> <body> <button class=\"btn\">Click Me</button> </body> </html>", "e": 2588, "s": 1779, "text": null }, { "code": null, "e": 2596, "s": 2588, "text": "Output:" }, { "code": null, "e": 2722, "s": 2596, "text": "You can play with other methods when the active pseudo-class is active to create your own effects when the button is clicked." }, { "code": null, "e": 2908, "s": 2722, "text": "CSS is the foundation of webpages, is used for webpage development by styling websites and web apps.You can learn CSS from the ground up by following this CSS Tutorial and CSS Examples." }, { "code": null, "e": 2917, "s": 2908, "text": "CSS-Misc" }, { "code": null, "e": 2921, "s": 2917, "text": "CSS" }, { "code": null, "e": 2938, "s": 2921, "text": "Web Technologies" } ]
pstree - Unix, Linux Command
pstree visually merges identical branches by putting them in square brackets and prefixing them with the repetition count, e.g. init-+-getty |-getty |-getty ‘-getty init-+-getty |-getty |-getty ‘-getty init---4*[getty] init---4*[getty] Child threads of a process are found under the parent process and are shown with the process name in curly braces, e.g. icecast2---13*[{icecast2}] icecast2---13*[{icecast2}] If pstree is called as pstree.x11 then it will prompt the user at the end of the line to press return and will not return until that has happened. This is useful for when pstree is run in a xterminal. /proc location of the proc file system
[ { "code": null, "e": 10841, "s": 10711, "text": "\npstree visually merges identical branches by putting them in square\nbrackets and prefixing them with the repetition count, e.g.\n" }, { "code": null, "e": 10912, "s": 10841, "text": "\n init-+-getty\n |-getty\n |-getty\n ‘-getty\n\n" }, { "code": null, "e": 10982, "s": 10912, "text": "\n init-+-getty\n |-getty\n |-getty\n ‘-getty\n" }, { "code": null, "e": 11008, "s": 10984, "text": "\n init---4*[getty]\n\n" }, { "code": null, "e": 11031, "s": 11008, "text": "\n init---4*[getty]\n" }, { "code": null, "e": 11157, "s": 11035, "text": "\nChild threads of a process are found under the parent process and are shown\nwith the process name in curly braces, e.g.\n" }, { "code": null, "e": 11191, "s": 11157, "text": "\n icecast2---13*[{icecast2}]\n\n" }, { "code": null, "e": 11224, "s": 11191, "text": "\n icecast2---13*[{icecast2}]\n" }, { "code": null, "e": 11429, "s": 11226, "text": "\nIf pstree is called as pstree.x11 then it will prompt the user\nat the end of the line to press return and will not return until that\nhas happened. This is useful for when pstree is run in a xterminal.\n" } ]
How to launch a program using C++ program?
Here we will see how to start some third-party application like notepad or anything using C++ program. This program is very simple, we can use command prompt command to do this task. We will pass the application name inside the system() function. This will open it accordingly. #include <iostream> using namespace std; int main() { cout >> "Opening Nodepad.exe" >> endl; system("notepad.exe"); }
[ { "code": null, "e": 1370, "s": 1187, "text": "Here we will see how to start some third-party application like notepad or anything using C++ program. This program is very simple, we can use command prompt command to do this task." }, { "code": null, "e": 1465, "s": 1370, "text": "We will pass the application name inside the system() function. This will open it accordingly." }, { "code": null, "e": 1589, "s": 1465, "text": "#include <iostream>\nusing namespace std;\nint main() {\n cout >> \"Opening Nodepad.exe\" >> endl;\n system(\"notepad.exe\");\n}" } ]
Difference between tilde ( ~ ) and caret ( ^ ) in package.json
25 Mar, 2022 When we open our package.json file and search for dependency property and in there we find the packages that are listed as a nested object of the dependency property package-name:package-version. Now look at the package version, we find some numbers separated by three dots (e.g. 2.6.2). NPM versions are written using three dots separated numbers the first number from the left shows the major release and the second number from the left shows the minor release and the third number shows the patch release of the package. Syntax: The syntax of the npm version looks like the following. Major.Minor.Patch Tilde (~) notation: It is used to match the most recent patch version. Tilde ~ notation freezes the major version and minor version. As we know patch updates are bug fixes that’s why we can say ~ notation allows us to automatically accept bug fixes. Example: The ~1.2.0 will update all the future patch updates. We have to write just ~1.2.0 and all the next patch update dependencies. For example, 1.2.1, 1.2.2, 1.2.5...............1.2.x. Note: Patch updates are very small security changes in a package that is why the ~version is approximately equivalent to the version. Caret (^) notation: It is used for automatically updating the minor updates along with patch updates. Example: The ^1.2.4 will update all the future Minor and patch updates, for example, ^1.2.4 will automatically change the dependency to 1.x.x if any update occurs. Using caret notation it is important to look at our code regularly if it is compatible with the newest version or not. Difference between tilde (~) and caret (^) in package.json: Tilde(~) notation Caret(^) notation References: https://docs.npmjs.com/about-semantic-versioning zinedinegithub Node-npm Node.js NodeJS-Questions Difference Between JavaScript Node.js Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Difference between var, let and const keywords in JavaScript Difference Between Method Overloading and Method Overriding in Java Similarities and Difference between Java and C++ Difference between Compile-time and Run-time Polymorphism in Java Difference between Internal and External fragmentation Difference between var, let and const keywords in JavaScript Differences between Functional Components and Class Components in React Remove elements from a JavaScript Array Hide or show elements in HTML using display property Difference Between PUT and PATCH Request
[ { "code": null, "e": 53, "s": 25, "text": "\n25 Mar, 2022" }, { "code": null, "e": 342, "s": 53, "text": "When we open our package.json file and search for dependency property and in there we find the packages that are listed as a nested object of the dependency property package-name:package-version. Now look at the package version, we find some numbers separated by three dots (e.g. 2.6.2). " }, { "code": null, "e": 578, "s": 342, "text": "NPM versions are written using three dots separated numbers the first number from the left shows the major release and the second number from the left shows the minor release and the third number shows the patch release of the package." }, { "code": null, "e": 642, "s": 578, "text": "Syntax: The syntax of the npm version looks like the following." }, { "code": null, "e": 660, "s": 642, "text": "Major.Minor.Patch" }, { "code": null, "e": 910, "s": 660, "text": "Tilde (~) notation: It is used to match the most recent patch version. Tilde ~ notation freezes the major version and minor version. As we know patch updates are bug fixes that’s why we can say ~ notation allows us to automatically accept bug fixes." }, { "code": null, "e": 1099, "s": 910, "text": "Example: The ~1.2.0 will update all the future patch updates. We have to write just ~1.2.0 and all the next patch update dependencies. For example, 1.2.1, 1.2.2, 1.2.5...............1.2.x." }, { "code": null, "e": 1233, "s": 1099, "text": "Note: Patch updates are very small security changes in a package that is why the ~version is approximately equivalent to the version." }, { "code": null, "e": 1336, "s": 1233, "text": "Caret (^) notation: It is used for automatically updating the minor updates along with patch updates. " }, { "code": null, "e": 1501, "s": 1336, "text": "Example: The ^1.2.4 will update all the future Minor and patch updates, for example, ^1.2.4 will automatically change the dependency to 1.x.x if any update occurs. " }, { "code": null, "e": 1620, "s": 1501, "text": "Using caret notation it is important to look at our code regularly if it is compatible with the newest version or not." }, { "code": null, "e": 1680, "s": 1620, "text": "Difference between tilde (~) and caret (^) in package.json:" }, { "code": null, "e": 1698, "s": 1680, "text": "Tilde(~) notation" }, { "code": null, "e": 1716, "s": 1698, "text": "Caret(^) notation" }, { "code": null, "e": 1777, "s": 1716, "text": "References: https://docs.npmjs.com/about-semantic-versioning" }, { "code": null, "e": 1792, "s": 1777, "text": "zinedinegithub" }, { "code": null, "e": 1801, "s": 1792, "text": "Node-npm" }, { "code": null, "e": 1809, "s": 1801, "text": "Node.js" }, { "code": null, "e": 1826, "s": 1809, "text": "NodeJS-Questions" }, { "code": null, "e": 1845, "s": 1826, "text": "Difference Between" }, { "code": null, "e": 1856, "s": 1845, "text": "JavaScript" }, { "code": null, "e": 1864, "s": 1856, "text": "Node.js" }, { "code": null, "e": 1881, "s": 1864, "text": "Web Technologies" }, { "code": null, "e": 1979, "s": 1881, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2040, "s": 1979, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 2108, "s": 2040, "text": "Difference Between Method Overloading and Method Overriding in Java" }, { "code": null, "e": 2157, "s": 2108, "text": "Similarities and Difference between Java and C++" }, { "code": null, "e": 2223, "s": 2157, "text": "Difference between Compile-time and Run-time Polymorphism in Java" }, { "code": null, "e": 2278, "s": 2223, "text": "Difference between Internal and External fragmentation" }, { "code": null, "e": 2339, "s": 2278, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 2411, "s": 2339, "text": "Differences between Functional Components and Class Components in React" }, { "code": null, "e": 2451, "s": 2411, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 2504, "s": 2451, "text": "Hide or show elements in HTML using display property" } ]
C++ Program to Find the GCD and LCM of n Numbers
This is the code to find out the GCD and LCM of n numbers. The GCD or Greatest Common Divisor of two or more integers, which are not all zero, is the largest positive integer that divides each of the integers. GCD is also known as Greatest Common Factor. The least common multiple (LCM) of two numbers is the smallest number (not zero) that is a multiple of both numbers. Begin Take two numbers as input Call the function gcd() two find out gcd of n numbers Call the function lcm() two find out lcm of n numbers gcd(number1, number2) Declare r, a, b Assign r=0 a = (number1 greater than number2)? number1: number2 b = (number1 less than number2)? number1: number2 r = b While (a mod b not equal to 0) Do r = a mod b a=b b=r Return r Done lcm(number1, number2) Declare a a=(number1 greater than number2)?number1:number2 While(true) do If (a mod number1 == 0 and a number2 == 0) Return a Increment a Done End #include<iostream> using namespace std; int gcd(int m, int n) { int r = 0, a, b; a = (m > n) ? m : n; b = (m < n) ? m : n; r = b; while (a % b != 0) { r = a % b; a = b; b = r; } return r; } int lcm(int m, int n) { int a; a = (m > n) ? m: n; while (true) { if (a % m == 0 && a % n == 0) return a; ++a; } } int main(int argc, char **argv) { cout << "Enter the two numbers: "; int m, n; cin >> m >> n; cout << "The GCD of two numbers is: " << gcd(m, n) << endl; cout << "The LCM of two numbers is: " << lcm(m, n) << endl; return 0; } Enter the two numbers: 7 6 The GCD of two numbers is: 1 The LCM of two numbers is: 42
[ { "code": null, "e": 1317, "s": 1062, "text": "This is the code to find out the GCD and LCM of n numbers. The GCD or Greatest Common Divisor of two or more integers, which are not all zero, is the largest positive integer that divides each of the integers. GCD is also known as Greatest Common Factor." }, { "code": null, "e": 1434, "s": 1317, "text": "The least common multiple (LCM) of two numbers is the smallest number (not zero) that is a multiple of both numbers." }, { "code": null, "e": 2077, "s": 1434, "text": "Begin\n Take two numbers as input\n Call the function gcd() two find out gcd of n numbers\n Call the function lcm() two find out lcm of n numbers\n gcd(number1, number2)\n Declare r, a, b\n Assign r=0\n a = (number1 greater than number2)? number1: number2\n b = (number1 less than number2)? number1: number2\n r = b\n While (a mod b not equal to 0)\n Do\n r = a mod b\n a=b\n b=r\n Return r\n Done\n lcm(number1, number2)\n Declare a\n a=(number1 greater than number2)?number1:number2\n While(true) do\n If\n (a mod number1 == 0 and a number2 == 0)\n Return a\n Increment a\n Done\nEnd" }, { "code": null, "e": 2701, "s": 2077, "text": "#include<iostream>\nusing namespace std;\nint gcd(int m, int n) {\n int r = 0, a, b;\n a = (m > n) ? m : n;\n b = (m < n) ? m : n;\n r = b;\n while (a % b != 0) {\n r = a % b;\n a = b;\n b = r;\n }\n return r;\n}\nint lcm(int m, int n) {\n int a;\n a = (m > n) ? m: n;\n while (true) {\n if (a % m == 0 && a % n == 0)\n return a;\n ++a;\n }\n}\nint main(int argc, char **argv) {\n cout << \"Enter the two numbers: \";\n int m, n;\n cin >> m >> n;\n cout << \"The GCD of two numbers is: \" << gcd(m, n) << endl;\n cout << \"The LCM of two numbers is: \" << lcm(m, n) << endl;\n return 0;\n}" }, { "code": null, "e": 2787, "s": 2701, "text": "Enter the two numbers:\n7\n6\nThe GCD of two numbers is: 1\nThe LCM of two numbers is: 42" } ]
Fastai - Disaster Prediction using ULMFiT | by Sachin Chaturvedi | Towards Data Science
Last month, I started the fastai MOOC(2019) - Deep Learning for Coders. It covers various topics like Computer Vision, Natural Language Processing, Collaborative Filtering, etc. The most fascinating part I found was the application of Transfer Learning in the field of Natural Language Processing. The approached used by fastai is Universal Language Model Fine-tuning (ULMFiT), which is a transfer learning methodology applied in the field of Natural Language Processing. course.fast.ai According to Wikipedia, Transfer learning (TL) is a research problem in machine learning (ML) that focuses on storing knowledge gained while solving one problem and applying it to a different but related problem. For example, knowledge gained while learning to recognize cars could apply when trying to recognize trucks. To show the use case of ULMFiT, I’ll apply the same on the Real or Not? NLP with Disaster Tweets competition on Kaggle. To give you an overview of the data, the data set contains two CSV files train.csv and test.csv representing the training data set and the test data set respectively. The training set contains the tweet data in text column and target value in target column, the value of which is 1 if it is a real disaster or 0 if it is not a real disaster. The test set contains only tweet data and no target values. The task is to predict whether a tweet represents a real disaster or not. The paragraph given below is taken from Understanding building blocks of ULMFiT: High level idea of ULMFiT is to train a language model using a very large corpus like Wikitext-103 (103M tokens), then to take this pre-trained model’s encoder and combine it with a custom head model, e.g. for classification, and to do the good old fine tuning using discriminative learning rates in multiple stages carefully. Architecture that ULMFiT uses for it’s language modeling task is an AWD-LSTM. The name is an abbreviation of ASGD Weight-Dropped LSTM. Refer to this paper written by Jeremy Howard and Sebastian Ruder if you want to read more about ULMFiT. In Computer Vision problems, transfer learning is used to help in classification directly but in the case of NLP, we first build a language model that basically predicts the next word of a sentence(the model has to understand the language in which the text is written(e.g., English, etc.)) and then build our classification model using the language model’s encoder and vocabulary. As mentioned in the paper, we will be using AWD-LSTM architecture pre-trained on Wikipedia. We could directly use this pre-trained language model to build our disaster tweet classifier but the gist here is that the English language of Wikipedia would be different from the English language of the tweets. So we will fine-tune our pre-trained language model using the tweet data and then build our classifier on top of that. As explained in the Deep Learning for Coders with Fastai and PyTorch book where they used the same pre-trained architecture on the IMDb Reviews data set to classify if the review is positive or negative. They explain that the IMDb Reviews English is more informal, contains names of movies, directors, actors, etc. than the regular Wikipedia English on which the architecture is pre-trained on. We import our test.csv and train.csv to get our training data set and test data set. I cannot share the data set as it is from a Kaggle Competition, you can download it yourself by logging into your account and adhering to the competition rules. # Importing Pandasimport pandas as pd# Importing fastai libraries for text and callbacksfrom fastai.text import *from fastai.callbacks import *train = pd.read_csv('train.csv')test = pd.read_csv('test.csv') I won’t be going into details on how the language model is built and you should really check out the MOOC and also the Deep Learning for Coders with Fastai and PyTorch book for further reading. The basic idea is that text data cannot be directly fed to the model and it needs to be converted to numbers so that we can apply our mathematical functions to it. This is done using Tokenization and Numericalization. In Tokenization, we convert the text into a list of tokens and in Numericalization we convert them into numbers based on their index. You should refer to the book if you want to dive deeper. We’ll be using the Data Block API that does the above for us under the hood and then we will feed the databunch created to our language model. data_lm = (TextList.from_df(pd.concat([train[['text']], test[['text']]], ignore_index=True, axis=0)) .split_by_rand_pct(0.15) .label_for_lm() .databunch(bs=128))data_lm.show_batch() We ignore the labels and take the text corpus from both training and test data. Remember that we are making a language model and not a classification model right now. We are just including text data as much as we can for our language model to predict the next word of a sentence. Next, we use our data_lm databunch to make our language model. learn = language_model_learner(data_lm, AWD_LSTM, drop_mult = 0.5)learn.lr_find()learn.recorder.plot(suggestion = True) learn.fit_one_cycle(1, 1e-2, moms=(0.8,0.7)) We’ll be unfreezing the model and we’ll fit more. We’ll use callbacks to select the best model. Better model found at epoch 0 with accuracy value: 0.4097544550895691.Better model found at epoch 1 with accuracy value: 0.4404464364051819.Better model found at epoch 2 with accuracy value: 0.4609375.Better model found at epoch 3 with accuracy value: 0.47495537996292114.Better model found at epoch 4 with accuracy value: 0.48810267448425293.Better model found at epoch 5 with accuracy value: 0.49515628814697266.Better model found at epoch 6 with accuracy value: 0.4975222945213318.Better model found at epoch 9 with accuracy value: 0.49756699800491333. We’ll select the best accuracy which is at epoch number 9. We’ll then save the language model and the encoder. learn.save('fine_tuned')learn.save_encoder('fine_tuned_enc') Next, we’ll make our classifier. For that, we’ll need to create a new databunch. We’ll take the validation set as 10% and we’ll keep our vocabulary same as the vocabulary of the language databunch. We’ll also add our test data in the separate add_test parameter. data_clas = (TextList.from_df(df, vocab=data_lm.vocab) .split_by_rand_pct(0.1) .label_from_df('target') .add_test(TextList.from_df(test['text'], vocab=data_lm.vocab)) .databunch(bs=128)) We’ll build the classifier using the same encoder as our language model. learn = text_classifier_learner(data_clas, AWD_LSTM, drop_mult=0.5, metrics=[accuracy, FBeta(beta=1)])learn.load_encoder('fine_tuned_enc') We’ll do a lr_find() check and then plot to see the graph. Let’s fit one cycle. We see that we get an accuracy of 77.66%. learn.fit_one_cycle(1, 1e-3, moms=(0.8,0.7)) Let’s unfreeze the last 2 layers and train for one cycle. Our accuracy increases to 79.5%. learn.freeze_to(-2)learn.fit_one_cycle(1, slice(1e-3/(2.6**4),1e-2), moms=(0.8,0.7)) We’ll unfreeze the last 3 layers now and train again for one more cyle. Our accuracy increases to 81.73%! learn.freeze_to(-3)learn.fit_one_cycle(1, slice(5e-3/(2.6**4),5e-3), moms=(0.8,0.7)) What we used here were discriminative learning rates which were introduced in ULMFiT. As explained in the article 10 New Things I Learnt from fast.ai v3: Discriminative learning rates for pre-trained modelsTrain earlier layer(s) with super low learning rate, and train later layers with higher learning rate. The idea is to not drastically alter the almost-perfect pre-trained weights except for minuscule amounts, and to be more aggressive with teaching the layers near the outputs. Discriminative learning rate was introduced in ULMFiT. We’ll unfreeze all layers, train, and use callbacks to select our best model. callbacks = SaveModelCallback(learn,monitor="accuracy", mode="max", name="best_classification_model") Better model found at epoch 0 with accuracy value: 0.8160315155982971.Better model found at epoch 1 with accuracy value: 0.8173456192016602.Better model found at epoch 2 with accuracy value: 0.822601854801178.Better model found at epoch 9 with accuracy value: 0.8239158987998962. We get an accuracy of 82.39%!! In Transfer Learning we use knowledge from a source and apply it to our target. Implementation of the same in the field of Natural Language Processing has provided an extraordinary state of the art results with minimal training as we use a pre-trained network. You can check out my notebook on Kaggle if you would like to see the code in action: NLP - Disaster Prediction ULMFiT Note: I have used fastai V1 here. The fastai V2 along with the new MOOC came out on 21st August. Check that out here
[ { "code": null, "e": 644, "s": 172, "text": "Last month, I started the fastai MOOC(2019) - Deep Learning for Coders. It covers various topics like Computer Vision, Natural Language Processing, Collaborative Filtering, etc. The most fascinating part I found was the application of Transfer Learning in the field of Natural Language Processing. The approached used by fastai is Universal Language Model Fine-tuning (ULMFiT), which is a transfer learning methodology applied in the field of Natural Language Processing." }, { "code": null, "e": 659, "s": 644, "text": "course.fast.ai" }, { "code": null, "e": 980, "s": 659, "text": "According to Wikipedia, Transfer learning (TL) is a research problem in machine learning (ML) that focuses on storing knowledge gained while solving one problem and applying it to a different but related problem. For example, knowledge gained while learning to recognize cars could apply when trying to recognize trucks." }, { "code": null, "e": 1576, "s": 980, "text": "To show the use case of ULMFiT, I’ll apply the same on the Real or Not? NLP with Disaster Tweets competition on Kaggle. To give you an overview of the data, the data set contains two CSV files train.csv and test.csv representing the training data set and the test data set respectively. The training set contains the tweet data in text column and target value in target column, the value of which is 1 if it is a real disaster or 0 if it is not a real disaster. The test set contains only tweet data and no target values. The task is to predict whether a tweet represents a real disaster or not." }, { "code": null, "e": 1657, "s": 1576, "text": "The paragraph given below is taken from Understanding building blocks of ULMFiT:" }, { "code": null, "e": 2119, "s": 1657, "text": "High level idea of ULMFiT is to train a language model using a very large corpus like Wikitext-103 (103M tokens), then to take this pre-trained model’s encoder and combine it with a custom head model, e.g. for classification, and to do the good old fine tuning using discriminative learning rates in multiple stages carefully. Architecture that ULMFiT uses for it’s language modeling task is an AWD-LSTM. The name is an abbreviation of ASGD Weight-Dropped LSTM." }, { "code": null, "e": 2223, "s": 2119, "text": "Refer to this paper written by Jeremy Howard and Sebastian Ruder if you want to read more about ULMFiT." }, { "code": null, "e": 2604, "s": 2223, "text": "In Computer Vision problems, transfer learning is used to help in classification directly but in the case of NLP, we first build a language model that basically predicts the next word of a sentence(the model has to understand the language in which the text is written(e.g., English, etc.)) and then build our classification model using the language model’s encoder and vocabulary." }, { "code": null, "e": 3423, "s": 2604, "text": "As mentioned in the paper, we will be using AWD-LSTM architecture pre-trained on Wikipedia. We could directly use this pre-trained language model to build our disaster tweet classifier but the gist here is that the English language of Wikipedia would be different from the English language of the tweets. So we will fine-tune our pre-trained language model using the tweet data and then build our classifier on top of that. As explained in the Deep Learning for Coders with Fastai and PyTorch book where they used the same pre-trained architecture on the IMDb Reviews data set to classify if the review is positive or negative. They explain that the IMDb Reviews English is more informal, contains names of movies, directors, actors, etc. than the regular Wikipedia English on which the architecture is pre-trained on." }, { "code": null, "e": 3669, "s": 3423, "text": "We import our test.csv and train.csv to get our training data set and test data set. I cannot share the data set as it is from a Kaggle Competition, you can download it yourself by logging into your account and adhering to the competition rules." }, { "code": null, "e": 3875, "s": 3669, "text": "# Importing Pandasimport pandas as pd# Importing fastai libraries for text and callbacksfrom fastai.text import *from fastai.callbacks import *train = pd.read_csv('train.csv')test = pd.read_csv('test.csv')" }, { "code": null, "e": 4478, "s": 3875, "text": "I won’t be going into details on how the language model is built and you should really check out the MOOC and also the Deep Learning for Coders with Fastai and PyTorch book for further reading. The basic idea is that text data cannot be directly fed to the model and it needs to be converted to numbers so that we can apply our mathematical functions to it. This is done using Tokenization and Numericalization. In Tokenization, we convert the text into a list of tokens and in Numericalization we convert them into numbers based on their index. You should refer to the book if you want to dive deeper." }, { "code": null, "e": 4621, "s": 4478, "text": "We’ll be using the Data Block API that does the above for us under the hood and then we will feed the databunch created to our language model." }, { "code": null, "e": 4833, "s": 4621, "text": "data_lm = (TextList.from_df(pd.concat([train[['text']], test[['text']]], ignore_index=True, axis=0)) .split_by_rand_pct(0.15) .label_for_lm() .databunch(bs=128))data_lm.show_batch()" }, { "code": null, "e": 5176, "s": 4833, "text": "We ignore the labels and take the text corpus from both training and test data. Remember that we are making a language model and not a classification model right now. We are just including text data as much as we can for our language model to predict the next word of a sentence. Next, we use our data_lm databunch to make our language model." }, { "code": null, "e": 5296, "s": 5176, "text": "learn = language_model_learner(data_lm, AWD_LSTM, drop_mult = 0.5)learn.lr_find()learn.recorder.plot(suggestion = True)" }, { "code": null, "e": 5341, "s": 5296, "text": "learn.fit_one_cycle(1, 1e-2, moms=(0.8,0.7))" }, { "code": null, "e": 5437, "s": 5341, "text": "We’ll be unfreezing the model and we’ll fit more. We’ll use callbacks to select the best model." }, { "code": null, "e": 5993, "s": 5437, "text": "Better model found at epoch 0 with accuracy value: 0.4097544550895691.Better model found at epoch 1 with accuracy value: 0.4404464364051819.Better model found at epoch 2 with accuracy value: 0.4609375.Better model found at epoch 3 with accuracy value: 0.47495537996292114.Better model found at epoch 4 with accuracy value: 0.48810267448425293.Better model found at epoch 5 with accuracy value: 0.49515628814697266.Better model found at epoch 6 with accuracy value: 0.4975222945213318.Better model found at epoch 9 with accuracy value: 0.49756699800491333." }, { "code": null, "e": 6104, "s": 5993, "text": "We’ll select the best accuracy which is at epoch number 9. We’ll then save the language model and the encoder." }, { "code": null, "e": 6165, "s": 6104, "text": "learn.save('fine_tuned')learn.save_encoder('fine_tuned_enc')" }, { "code": null, "e": 6428, "s": 6165, "text": "Next, we’ll make our classifier. For that, we’ll need to create a new databunch. We’ll take the validation set as 10% and we’ll keep our vocabulary same as the vocabulary of the language databunch. We’ll also add our test data in the separate add_test parameter." }, { "code": null, "e": 6663, "s": 6428, "text": "data_clas = (TextList.from_df(df, vocab=data_lm.vocab) .split_by_rand_pct(0.1) .label_from_df('target') .add_test(TextList.from_df(test['text'], vocab=data_lm.vocab)) .databunch(bs=128))" }, { "code": null, "e": 6736, "s": 6663, "text": "We’ll build the classifier using the same encoder as our language model." }, { "code": null, "e": 6875, "s": 6736, "text": "learn = text_classifier_learner(data_clas, AWD_LSTM, drop_mult=0.5, metrics=[accuracy, FBeta(beta=1)])learn.load_encoder('fine_tuned_enc')" }, { "code": null, "e": 6934, "s": 6875, "text": "We’ll do a lr_find() check and then plot to see the graph." }, { "code": null, "e": 6997, "s": 6934, "text": "Let’s fit one cycle. We see that we get an accuracy of 77.66%." }, { "code": null, "e": 7042, "s": 6997, "text": "learn.fit_one_cycle(1, 1e-3, moms=(0.8,0.7))" }, { "code": null, "e": 7133, "s": 7042, "text": "Let’s unfreeze the last 2 layers and train for one cycle. Our accuracy increases to 79.5%." }, { "code": null, "e": 7218, "s": 7133, "text": "learn.freeze_to(-2)learn.fit_one_cycle(1, slice(1e-3/(2.6**4),1e-2), moms=(0.8,0.7))" }, { "code": null, "e": 7324, "s": 7218, "text": "We’ll unfreeze the last 3 layers now and train again for one more cyle. Our accuracy increases to 81.73%!" }, { "code": null, "e": 7409, "s": 7324, "text": "learn.freeze_to(-3)learn.fit_one_cycle(1, slice(5e-3/(2.6**4),5e-3), moms=(0.8,0.7))" }, { "code": null, "e": 7563, "s": 7409, "text": "What we used here were discriminative learning rates which were introduced in ULMFiT. As explained in the article 10 New Things I Learnt from fast.ai v3:" }, { "code": null, "e": 7948, "s": 7563, "text": "Discriminative learning rates for pre-trained modelsTrain earlier layer(s) with super low learning rate, and train later layers with higher learning rate. The idea is to not drastically alter the almost-perfect pre-trained weights except for minuscule amounts, and to be more aggressive with teaching the layers near the outputs. Discriminative learning rate was introduced in ULMFiT." }, { "code": null, "e": 8026, "s": 7948, "text": "We’ll unfreeze all layers, train, and use callbacks to select our best model." }, { "code": null, "e": 8128, "s": 8026, "text": "callbacks = SaveModelCallback(learn,monitor=\"accuracy\", mode=\"max\", name=\"best_classification_model\")" }, { "code": null, "e": 8408, "s": 8128, "text": "Better model found at epoch 0 with accuracy value: 0.8160315155982971.Better model found at epoch 1 with accuracy value: 0.8173456192016602.Better model found at epoch 2 with accuracy value: 0.822601854801178.Better model found at epoch 9 with accuracy value: 0.8239158987998962." }, { "code": null, "e": 8439, "s": 8408, "text": "We get an accuracy of 82.39%!!" }, { "code": null, "e": 8818, "s": 8439, "text": "In Transfer Learning we use knowledge from a source and apply it to our target. Implementation of the same in the field of Natural Language Processing has provided an extraordinary state of the art results with minimal training as we use a pre-trained network. You can check out my notebook on Kaggle if you would like to see the code in action: NLP - Disaster Prediction ULMFiT" } ]
Metasploit - Exploit
After vulnerability scanning and vulnerability validation, we have to run and test some scripts (called exploits) in order to gain access to a machine and do what we are planning to do. We have several methods to use exploits. The first and foremost method is to use Armitage GUI which will connect with Metasploit to perform automated exploit testing called HAIL MARY. Let’s see how it works. Open Kali distribution → Application → Exploit Tools → Armitage. Next, go to Attacks → Hail Mary and click Yes. You will see the following screen which would show all the exploits that are being tested. Next, you will see the icon of the exploitable system (i.e., the system on which the exploit worked) will turn red in color with a thunderstorm pattern over it. At the console, you will see which exploit was successful, with its respective session ID. Now you can interact with the machine. The second way (and probably a little professional way) to use an Exploit is by the Command Prompt. From the Vulnerability Scanner, we found that the Linux machine that we have for test is vulnerable to FTP service. Now we will use an exploit that can work for us. The command is − msf > use “exploit path” Next, use the following command in order to see what parameters you have to set to make it functional. msf > show options This exploit shows that we have to set RHOST “target IP” Next, use the commands − msf > set RHOST 192.168.1.101 msf > set RPORT 21 Next, use the command − msf > run If the exploit is successful, then you will see one session opened, as shown in the following screenshot. Now, you can interact with this system. Print Add Notes Bookmark this page
[ { "code": null, "e": 2357, "s": 2171, "text": "After vulnerability scanning and vulnerability validation, we have to run and test some scripts (called exploits) in order to gain access to a machine and do what we are planning to do." }, { "code": null, "e": 2565, "s": 2357, "text": "We have several methods to use exploits. The first and foremost method is to use Armitage GUI which will connect with Metasploit to perform automated exploit testing called HAIL MARY. Let’s see how it works." }, { "code": null, "e": 2630, "s": 2565, "text": "Open Kali distribution → Application → Exploit Tools → Armitage." }, { "code": null, "e": 2677, "s": 2630, "text": "Next, go to Attacks → Hail Mary and click Yes." }, { "code": null, "e": 2768, "s": 2677, "text": "You will see the following screen which would show all the exploits that are being tested." }, { "code": null, "e": 3020, "s": 2768, "text": "Next, you will see the icon of the exploitable system (i.e., the system on which the exploit worked) will turn red in color with a thunderstorm pattern over it. At the console, you will see which exploit was successful, with its respective session ID." }, { "code": null, "e": 3059, "s": 3020, "text": "Now you can interact with the machine." }, { "code": null, "e": 3159, "s": 3059, "text": "The second way (and probably a little professional way) to use an Exploit is by the Command Prompt." }, { "code": null, "e": 3341, "s": 3159, "text": "From the Vulnerability Scanner, we found that the Linux machine that we have for test is vulnerable to FTP service. Now we will use an exploit that can work for us. The command is −" }, { "code": null, "e": 3369, "s": 3341, "text": "msf > use “exploit path” \n" }, { "code": null, "e": 3472, "s": 3369, "text": "Next, use the following command in order to see what parameters you have to set to make it functional." }, { "code": null, "e": 3492, "s": 3472, "text": "msf > show options\n" }, { "code": null, "e": 3549, "s": 3492, "text": "This exploit shows that we have to set RHOST “target IP”" }, { "code": null, "e": 3574, "s": 3549, "text": "Next, use the commands −" }, { "code": null, "e": 3627, "s": 3574, "text": "msf > set RHOST 192.168.1.101 \nmsf > set RPORT 21\n" }, { "code": null, "e": 3651, "s": 3627, "text": "Next, use the command −" }, { "code": null, "e": 3662, "s": 3651, "text": "msf > run\n" }, { "code": null, "e": 3768, "s": 3662, "text": "If the exploit is successful, then you will see one session opened, as shown in the following screenshot." }, { "code": null, "e": 3808, "s": 3768, "text": "Now, you can interact with this system." }, { "code": null, "e": 3815, "s": 3808, "text": " Print" }, { "code": null, "e": 3826, "s": 3815, "text": " Add Notes" } ]
Contact Tracing Using Less Than 30 Lines of Python Code | by Sara A. Metwalli | Towards Data Science
Contact tracing is the name of the process used to identify those who come into contact with people who have tested positive for contagious diseases — such as measles, HIV, and COVID-19. During a pandemic, performing contact tracing correctly can help reduce the number of people to get infected or speed up the process of treating infected people. Doing so can help save many lives. Technology can help automate the process of contact tracing, producing more efficient and accurate results than if the procedure was performed manually. One technology that can help this process is Machine Learning. More precisely, clustering. Clustering is a subclass of Machine Learning algorithms used to divide data that share some characteristics in different clusters based on these characteristics. towardsdatascience.com There are various types of clustering algorithms, such as K-means, Mean-Shift, Spectral Clustering, BIRCH, DBSCAN, and so much more. These different algorithms can be divided into three categories: Density-based Clustering: Clusters are formed based on the density of the region — examples of this type: DBSCAN (Density-Based Spatial Clustering of Applications with Noise) and OPTICS (Ordering Points to Identify Clustering Structure).Hierarchal-based Clustering: Clusters are formed using a tree-type structure. Some clusters are predefined and then used to create new clusters — examples of this type: CURE (Clustering Using Representatives), BIRCH (Balanced Iterative Reducing Clustering, and using Hierarchies).Partitioning-based Clustering: Clusters are formed by partitioning the input data into k clusters — examples of this type: K-means, CLARANS (Clustering Large Applications based upon Randomized Search). Density-based Clustering: Clusters are formed based on the density of the region — examples of this type: DBSCAN (Density-Based Spatial Clustering of Applications with Noise) and OPTICS (Ordering Points to Identify Clustering Structure). Hierarchal-based Clustering: Clusters are formed using a tree-type structure. Some clusters are predefined and then used to create new clusters — examples of this type: CURE (Clustering Using Representatives), BIRCH (Balanced Iterative Reducing Clustering, and using Hierarchies). Partitioning-based Clustering: Clusters are formed by partitioning the input data into k clusters — examples of this type: K-means, CLARANS (Clustering Large Applications based upon Randomized Search). For contact tracing, we need to use a density-based clustering algorithm. The reason is, diseases are transferred when an infected person comes in contact with others. So, more crowded — dense — areas will have more cases than less crowded ones. To trace the movement of infected people, scientists often use GPS datasets that contain information about the time and location of a person in any given timeframe. The location data is often represented as longitude and latitude coordinates. In order to build a contact tracing algorithm, we need to do three steps: Get location data of different users within a specific time and place.Apply a density-based clustering algorithm on the data.Use the clusters to predict infected people. Get location data of different users within a specific time and place. Apply a density-based clustering algorithm on the data. Use the clusters to predict infected people. So, let’s get started... We will write a Python code that uses the DBSCAN clustering algorithm to predict who might get infected because they came in contact with an infected person. Unfortunately, we can’t obtain real-life data from GPS locations. So, we will build a mock dataset to apply our algorithm on. For this article, I used a Mock Data Generator to generate a JSON dataset containing 100 entries of the locations of 10 users. If you want to try another dataset, make sure the following conditions apply: There is more than one entry for each user.The users are close in the distance to each other and within a timeframe (for example, a day or a specific number of hours). There is more than one entry for each user. The users are close in the distance to each other and within a timeframe (for example, a day or a specific number of hours). First, let’s import all the libraries that we will use. We will need Pandas and Sklearn to process the data and Pygal to display it. import pandas as pdimport pygalfrom sklearn.cluster import DBSCAN Note: in case you don’t have one of these libraries, you can use pip to install each of them from the command line. Moreover, if you're using Jupyter Notebook, you need to add this cell to display Pygal plots: from IPython.display import display, HTMLbase_html = """<!DOCTYPE html><html> <head> <script type="text/javascript" src="http://kozea.github.com/pygal.js/javascripts/svg.jquery.js"></script> <script type="text/javascript" src="https://kozea.github.io/pygal.js/2.0.x/pygal-tooltips.min.js""></script> </head> <body> <figure> {rendered_chart} </figure> </body></html>""" Now, we can load our dataset and show the first 5 rows to understand how it is built. dataFrame = pd.read_json(r"Location_Of_Your_Dataset\MOCK_DATA.json")dataFrame.head() To understand the data more, we will plot it using the Pygal scatter plot. We can extract the different locations of each user and store that in a dictionary and then use this dictionary to plot the data. disp_dict = {}for index, row in dataFram.iterrows(): if row['User'] not in disp_dict.keys(): disp_dict[row['User']] = [(row['Latitude'], row['Longitude'])] else: disp_dict[row['User']].append((row['Latitude'], row['Longitude']))xy_chart = pygal.XY(stroke=False)[xy_chart.add(k,v) for k,v in sorted(disp_dict.items())]display(HTML(base_html.format(rendered_chart=xy_chart.render(is_unicode=True)))) Running this code, we get... Awesome. Now that we have our dataset, we can apply the clustering algorithm on it and then use that to predict potential infections. To accomplish that, we will use the DBSCAN algorithm. The DBSCAN algorithm views clusters as areas of high density separated by regions of low density. Because of this, clusters found by DBSCAN can be of any shape, as opposed to k-means, which assumes that all clusters are convex shaped. Sklearn had a predefined DBSCAN algorithm; all you need to do to use it is know three parameters: eps: This factor indicates the distance between the different points in the same cluster. In our case, we will use the recommended distance by the CDC, which is 6 feet (or 0.0018288 kilometers).min_samples: The minimum number of samples in the cluster. In the case of large, noisy datasets, increase this number.metric: This sets the distance metric between the data points. Sklearn has many distance metrics, such as euclidean, manhattan, and Minkowski. For our case, however, we need a distance measure that describes distance on a cipher (The Earth). The metric for that is called haversine. eps: This factor indicates the distance between the different points in the same cluster. In our case, we will use the recommended distance by the CDC, which is 6 feet (or 0.0018288 kilometers). min_samples: The minimum number of samples in the cluster. In the case of large, noisy datasets, increase this number. metric: This sets the distance metric between the data points. Sklearn has many distance metrics, such as euclidean, manhattan, and Minkowski. For our case, however, we need a distance measure that describes distance on a cipher (The Earth). The metric for that is called haversine. We can now apply our model to the dataset. safe_distance = 0.0018288 # a radial distance of 6 feet in kilometersmodel = DBSCAN(eps=safe_distance, min_samples=2, metric='haversine').fit(dataFram[['Latitude', 'Longitude']])core_samples_mask = np.zeros_like(model.labels_, dtype=bool)core_samples_mask[model.core_sample_indices_] = Truelabels = model.labels_dataFram['Cluster'] = model.labels_.tolist() Applying the model with these parameters leads to 18 clusters. We can display these clusters using this piece of code... disp_dict_clust = {}for index, row in dataFram.iterrows(): if row['Cluster'] not in disp_dict_clust.keys(): disp_dict_clust[row['Cluster']] = [(row['Latitude'], row['Longitude'])] else: disp_dict_clust[row['Cluster']].append((row['Latitude'], row['Longitude']))print(len(disp_dict_clust.keys()))from pygal.style import LightenStyledark_lighten_style = LightenStyle('#F35548')xy_chart = pygal.XY(stroke=False, style=dark_lighten_style)[xy_chart.add(str(k),v) for k,v in disp_dict_clust.items()]display(HTML(base_html.format(rendered_chart=xy_chart.render(is_unicode=True)))) After the algorithm is done, if there were any data points without a cluster, they will be clustered as noise or cluster -1. Often, you will find that all users in this data set will be part of the -1 cluster in addition to other clusters. If we have the name of an infected person, we can use that to get all clusters this person is a part of. From there, we can see other people in these clusters. These people will have a higher probability of getting infected than those who are not. Obtain all clusters a specific person belongs to Given a name inputName for example, William, we want all clusters that William is a part of. inputName = "William"inputNameClusters = set() for i in range(len(dataFrame)): if dataFrame['User'][i] == inputName: inputNameClusters.add(dataFrame['Cluster'][i]) After executing this code, the inputNameCluster will become {2, 4, 5, -1}. Get people within a specific cluster. Now, we want other people who belong to this specific set of clusters. infected = set() for cluster in inputNameClusters: if cluster != -1: namesInCluster = dataFrame.loc[dataFrame['Cluster'] == cluster, 'User'] for i in range(len(namesInCluster)): name = namesInCluster.iloc[i] if name != inputName: infected.add(name) In both these sections, I am using sets to avoid having extra if-else statements when the inputName is in each cluster's names list. Voilà, the code will return {‘Doreen’, ‘James’, ‘John’}, which means, those three people are potentially infected because they came into contact with William at some point in time and place. I have put the core code into a function that takes a dataframe and a user’s name and perform contact tracing of this user and finally print potentially infected people. The function will first check if the inputName is valid; if not, it will raise an assertion error. On top of that, it's less than 30 lines of code!! The full code for the contact tracing function: Contact Tracing is one of the ways we can use technology to save people’s lives and provide them treatment as soon as possible. Government and medical personals often have access to GPS locations of some patients. The process we walked through in this article, is fundamentally the same as the one they follow to obtain potential infections. Luckily, thanks to libraries like Sklearn, we can use predefined models on our datasets and obtain results with few lines of code. [1] “A Density-Based Algorithm for Discovering Clusters in Large Spatial Databases with Noise” Ester, M., H. P. Kriegel, J. Sander, and X. Xu, In Proceedings of the 2nd International Conference on Knowledge Discovery and Data Mining, Portland, OR, AAAI Press, pp. 226–231. 1996 [2] “DBSCAN revisited, revisited: why and how you should (still) use DBSCAN. Schubert, E., Sander, J., Ester, M., Kriegel, H. P., & Xu, X. (2017). In ACM Transactions on Database Systems (TODS), 42(3), 19. [3] Sklearn Documentation.
[ { "code": null, "e": 556, "s": 172, "text": "Contact tracing is the name of the process used to identify those who come into contact with people who have tested positive for contagious diseases — such as measles, HIV, and COVID-19. During a pandemic, performing contact tracing correctly can help reduce the number of people to get infected or speed up the process of treating infected people. Doing so can help save many lives." }, { "code": null, "e": 962, "s": 556, "text": "Technology can help automate the process of contact tracing, producing more efficient and accurate results than if the procedure was performed manually. One technology that can help this process is Machine Learning. More precisely, clustering. Clustering is a subclass of Machine Learning algorithms used to divide data that share some characteristics in different clusters based on these characteristics." }, { "code": null, "e": 985, "s": 962, "text": "towardsdatascience.com" }, { "code": null, "e": 1183, "s": 985, "text": "There are various types of clustering algorithms, such as K-means, Mean-Shift, Spectral Clustering, BIRCH, DBSCAN, and so much more. These different algorithms can be divided into three categories:" }, { "code": null, "e": 1902, "s": 1183, "text": "Density-based Clustering: Clusters are formed based on the density of the region — examples of this type: DBSCAN (Density-Based Spatial Clustering of Applications with Noise) and OPTICS (Ordering Points to Identify Clustering Structure).Hierarchal-based Clustering: Clusters are formed using a tree-type structure. Some clusters are predefined and then used to create new clusters — examples of this type: CURE (Clustering Using Representatives), BIRCH (Balanced Iterative Reducing Clustering, and using Hierarchies).Partitioning-based Clustering: Clusters are formed by partitioning the input data into k clusters — examples of this type: K-means, CLARANS (Clustering Large Applications based upon Randomized Search)." }, { "code": null, "e": 2140, "s": 1902, "text": "Density-based Clustering: Clusters are formed based on the density of the region — examples of this type: DBSCAN (Density-Based Spatial Clustering of Applications with Noise) and OPTICS (Ordering Points to Identify Clustering Structure)." }, { "code": null, "e": 2421, "s": 2140, "text": "Hierarchal-based Clustering: Clusters are formed using a tree-type structure. Some clusters are predefined and then used to create new clusters — examples of this type: CURE (Clustering Using Representatives), BIRCH (Balanced Iterative Reducing Clustering, and using Hierarchies)." }, { "code": null, "e": 2623, "s": 2421, "text": "Partitioning-based Clustering: Clusters are formed by partitioning the input data into k clusters — examples of this type: K-means, CLARANS (Clustering Large Applications based upon Randomized Search)." }, { "code": null, "e": 2869, "s": 2623, "text": "For contact tracing, we need to use a density-based clustering algorithm. The reason is, diseases are transferred when an infected person comes in contact with others. So, more crowded — dense — areas will have more cases than less crowded ones." }, { "code": null, "e": 3112, "s": 2869, "text": "To trace the movement of infected people, scientists often use GPS datasets that contain information about the time and location of a person in any given timeframe. The location data is often represented as longitude and latitude coordinates." }, { "code": null, "e": 3186, "s": 3112, "text": "In order to build a contact tracing algorithm, we need to do three steps:" }, { "code": null, "e": 3356, "s": 3186, "text": "Get location data of different users within a specific time and place.Apply a density-based clustering algorithm on the data.Use the clusters to predict infected people." }, { "code": null, "e": 3427, "s": 3356, "text": "Get location data of different users within a specific time and place." }, { "code": null, "e": 3483, "s": 3427, "text": "Apply a density-based clustering algorithm on the data." }, { "code": null, "e": 3528, "s": 3483, "text": "Use the clusters to predict infected people." }, { "code": null, "e": 3553, "s": 3528, "text": "So, let’s get started..." }, { "code": null, "e": 3711, "s": 3553, "text": "We will write a Python code that uses the DBSCAN clustering algorithm to predict who might get infected because they came in contact with an infected person." }, { "code": null, "e": 4042, "s": 3711, "text": "Unfortunately, we can’t obtain real-life data from GPS locations. So, we will build a mock dataset to apply our algorithm on. For this article, I used a Mock Data Generator to generate a JSON dataset containing 100 entries of the locations of 10 users. If you want to try another dataset, make sure the following conditions apply:" }, { "code": null, "e": 4210, "s": 4042, "text": "There is more than one entry for each user.The users are close in the distance to each other and within a timeframe (for example, a day or a specific number of hours)." }, { "code": null, "e": 4254, "s": 4210, "text": "There is more than one entry for each user." }, { "code": null, "e": 4379, "s": 4254, "text": "The users are close in the distance to each other and within a timeframe (for example, a day or a specific number of hours)." }, { "code": null, "e": 4512, "s": 4379, "text": "First, let’s import all the libraries that we will use. We will need Pandas and Sklearn to process the data and Pygal to display it." }, { "code": null, "e": 4578, "s": 4512, "text": "import pandas as pdimport pygalfrom sklearn.cluster import DBSCAN" }, { "code": null, "e": 4788, "s": 4578, "text": "Note: in case you don’t have one of these libraries, you can use pip to install each of them from the command line. Moreover, if you're using Jupyter Notebook, you need to add this cell to display Pygal plots:" }, { "code": null, "e": 5174, "s": 4788, "text": "from IPython.display import display, HTMLbase_html = \"\"\"<!DOCTYPE html><html> <head> <script type=\"text/javascript\" src=\"http://kozea.github.com/pygal.js/javascripts/svg.jquery.js\"></script> <script type=\"text/javascript\" src=\"https://kozea.github.io/pygal.js/2.0.x/pygal-tooltips.min.js\"\"></script> </head> <body> <figure> {rendered_chart} </figure> </body></html>\"\"\"" }, { "code": null, "e": 5260, "s": 5174, "text": "Now, we can load our dataset and show the first 5 rows to understand how it is built." }, { "code": null, "e": 5345, "s": 5260, "text": "dataFrame = pd.read_json(r\"Location_Of_Your_Dataset\\MOCK_DATA.json\")dataFrame.head()" }, { "code": null, "e": 5550, "s": 5345, "text": "To understand the data more, we will plot it using the Pygal scatter plot. We can extract the different locations of each user and store that in a dictionary and then use this dictionary to plot the data." }, { "code": null, "e": 5968, "s": 5550, "text": "disp_dict = {}for index, row in dataFram.iterrows(): if row['User'] not in disp_dict.keys(): disp_dict[row['User']] = [(row['Latitude'], row['Longitude'])] else: disp_dict[row['User']].append((row['Latitude'], row['Longitude']))xy_chart = pygal.XY(stroke=False)[xy_chart.add(k,v) for k,v in sorted(disp_dict.items())]display(HTML(base_html.format(rendered_chart=xy_chart.render(is_unicode=True))))" }, { "code": null, "e": 5997, "s": 5968, "text": "Running this code, we get..." }, { "code": null, "e": 6185, "s": 5997, "text": "Awesome. Now that we have our dataset, we can apply the clustering algorithm on it and then use that to predict potential infections. To accomplish that, we will use the DBSCAN algorithm." }, { "code": null, "e": 6420, "s": 6185, "text": "The DBSCAN algorithm views clusters as areas of high density separated by regions of low density. Because of this, clusters found by DBSCAN can be of any shape, as opposed to k-means, which assumes that all clusters are convex shaped." }, { "code": null, "e": 6518, "s": 6420, "text": "Sklearn had a predefined DBSCAN algorithm; all you need to do to use it is know three parameters:" }, { "code": null, "e": 7113, "s": 6518, "text": "eps: This factor indicates the distance between the different points in the same cluster. In our case, we will use the recommended distance by the CDC, which is 6 feet (or 0.0018288 kilometers).min_samples: The minimum number of samples in the cluster. In the case of large, noisy datasets, increase this number.metric: This sets the distance metric between the data points. Sklearn has many distance metrics, such as euclidean, manhattan, and Minkowski. For our case, however, we need a distance measure that describes distance on a cipher (The Earth). The metric for that is called haversine." }, { "code": null, "e": 7308, "s": 7113, "text": "eps: This factor indicates the distance between the different points in the same cluster. In our case, we will use the recommended distance by the CDC, which is 6 feet (or 0.0018288 kilometers)." }, { "code": null, "e": 7427, "s": 7308, "text": "min_samples: The minimum number of samples in the cluster. In the case of large, noisy datasets, increase this number." }, { "code": null, "e": 7710, "s": 7427, "text": "metric: This sets the distance metric between the data points. Sklearn has many distance metrics, such as euclidean, manhattan, and Minkowski. For our case, however, we need a distance measure that describes distance on a cipher (The Earth). The metric for that is called haversine." }, { "code": null, "e": 7753, "s": 7710, "text": "We can now apply our model to the dataset." }, { "code": null, "e": 8110, "s": 7753, "text": "safe_distance = 0.0018288 # a radial distance of 6 feet in kilometersmodel = DBSCAN(eps=safe_distance, min_samples=2, metric='haversine').fit(dataFram[['Latitude', 'Longitude']])core_samples_mask = np.zeros_like(model.labels_, dtype=bool)core_samples_mask[model.core_sample_indices_] = Truelabels = model.labels_dataFram['Cluster'] = model.labels_.tolist()" }, { "code": null, "e": 8231, "s": 8110, "text": "Applying the model with these parameters leads to 18 clusters. We can display these clusters using this piece of code..." }, { "code": null, "e": 8825, "s": 8231, "text": "disp_dict_clust = {}for index, row in dataFram.iterrows(): if row['Cluster'] not in disp_dict_clust.keys(): disp_dict_clust[row['Cluster']] = [(row['Latitude'], row['Longitude'])] else: disp_dict_clust[row['Cluster']].append((row['Latitude'], row['Longitude']))print(len(disp_dict_clust.keys()))from pygal.style import LightenStyledark_lighten_style = LightenStyle('#F35548')xy_chart = pygal.XY(stroke=False, style=dark_lighten_style)[xy_chart.add(str(k),v) for k,v in disp_dict_clust.items()]display(HTML(base_html.format(rendered_chart=xy_chart.render(is_unicode=True))))" }, { "code": null, "e": 9065, "s": 8825, "text": "After the algorithm is done, if there were any data points without a cluster, they will be clustered as noise or cluster -1. Often, you will find that all users in this data set will be part of the -1 cluster in addition to other clusters." }, { "code": null, "e": 9313, "s": 9065, "text": "If we have the name of an infected person, we can use that to get all clusters this person is a part of. From there, we can see other people in these clusters. These people will have a higher probability of getting infected than those who are not." }, { "code": null, "e": 9362, "s": 9313, "text": "Obtain all clusters a specific person belongs to" }, { "code": null, "e": 9455, "s": 9362, "text": "Given a name inputName for example, William, we want all clusters that William is a part of." }, { "code": null, "e": 9640, "s": 9455, "text": "inputName = \"William\"inputNameClusters = set() for i in range(len(dataFrame)): if dataFrame['User'][i] == inputName: inputNameClusters.add(dataFrame['Cluster'][i])" }, { "code": null, "e": 9715, "s": 9640, "text": "After executing this code, the inputNameCluster will become {2, 4, 5, -1}." }, { "code": null, "e": 9753, "s": 9715, "text": "Get people within a specific cluster." }, { "code": null, "e": 9824, "s": 9753, "text": "Now, we want other people who belong to this specific set of clusters." }, { "code": null, "e": 10154, "s": 9824, "text": "infected = set() for cluster in inputNameClusters: if cluster != -1: namesInCluster = dataFrame.loc[dataFrame['Cluster'] == cluster, 'User'] for i in range(len(namesInCluster)): name = namesInCluster.iloc[i] if name != inputName: infected.add(name)" }, { "code": null, "e": 10287, "s": 10154, "text": "In both these sections, I am using sets to avoid having extra if-else statements when the inputName is in each cluster's names list." }, { "code": null, "e": 10479, "s": 10287, "text": "Voilà, the code will return {‘Doreen’, ‘James’, ‘John’}, which means, those three people are potentially infected because they came into contact with William at some point in time and place." }, { "code": null, "e": 10798, "s": 10479, "text": "I have put the core code into a function that takes a dataframe and a user’s name and perform contact tracing of this user and finally print potentially infected people. The function will first check if the inputName is valid; if not, it will raise an assertion error. On top of that, it's less than 30 lines of code!!" }, { "code": null, "e": 10846, "s": 10798, "text": "The full code for the contact tracing function:" }, { "code": null, "e": 11319, "s": 10846, "text": "Contact Tracing is one of the ways we can use technology to save people’s lives and provide them treatment as soon as possible. Government and medical personals often have access to GPS locations of some patients. The process we walked through in this article, is fundamentally the same as the one they follow to obtain potential infections. Luckily, thanks to libraries like Sklearn, we can use predefined models on our datasets and obtain results with few lines of code." }, { "code": null, "e": 11597, "s": 11319, "text": "[1] “A Density-Based Algorithm for Discovering Clusters in Large Spatial Databases with Noise” Ester, M., H. P. Kriegel, J. Sander, and X. Xu, In Proceedings of the 2nd International Conference on Knowledge Discovery and Data Mining, Portland, OR, AAAI Press, pp. 226–231. 1996" }, { "code": null, "e": 11803, "s": 11597, "text": "[2] “DBSCAN revisited, revisited: why and how you should (still) use DBSCAN. Schubert, E., Sander, J., Ester, M., Kriegel, H. P., & Xu, X. (2017). In ACM Transactions on Database Systems (TODS), 42(3), 19." } ]
Sort an array according to the order defined by another array in C++
In this section we will see another sorting problem. Suppose we have two arrays A1 and A2. We have to sort A1 in such a way that the relative order among the elements will be same as those are in A2. If some elements are not present in A2, then they will be appended after the sorted elements. Suppose A1 and A2 are the following − A1 = {2, 1, 2, 1, 7, 5, 9, 3, 8, 6, 8} A2 = {2, 1, 8, 3} After the sorting A1 will be like below − A1 = {2, 2, 1, 1, 8, 8, 3, 5, 6, 7, 9} To solve this problem, we will create our custom compare method. That method will compare and place the elements in the array. The comparison logic will be like below − if num1 and num2 both are in A2, then number with the lower index in A2 will be treated as smaller than the other number If either num1 or num2 is present in A2, then that number will be treated as smaller, than the other, which is does not present in A2. If both are not present in A2, then natural ordering will be used. compare(num1, num2): Begin if both num1 and num2 are present in A2, then return index of num1 – index of num2 else if num1 is not in A2, then return -1 else if num2 is not in A1, then return 1 else num1 – num2 End Live Demo #include<iostream> #include<algorithm> using namespace std; int size = 5; int A2[5]; //global A2 will be used in compare function int search_index(int key){ int index = 0; for(int i = 0; i < size; i++){ if(A2[i] == key) return i; } return -1; } int compare(const void *num1, const void *num2){ int index1 = search_index(*(int*)num1); int index2 = search_index(*(int*)num2); if (index1 != -1 && index2 != -1) return index1 - index2; else if (index1 != -1) return -1; else if (index2 != -1) return 1; else return (*(int*)num1 - *(int*)num2); } main(){ int data[] = {2, 1, 2, 1, 7, 5, 9, 3, 8, 6, 8}; int n = sizeof(data)/sizeof(data[0]); int a2[] = {2, 1, 8, 3}; int n2 = sizeof(a2)/sizeof(a2[0]); for(int i = 0; i<n2; i++){ A2[i] = a2[i]; } qsort(data, n, sizeof(int), compare); for(int i = 0; i<n; i++){ cout << data[i] << " "; } } 2 2 1 1 8 8 3 5 6 7 9
[ { "code": null, "e": 1394, "s": 1062, "text": "In this section we will see another sorting problem. Suppose we have two arrays A1 and A2. We have to sort A1 in such a way that the relative order among the elements will be same as those are in A2. If some elements are not present in A2, then they will be appended after the sorted elements. Suppose A1 and A2 are the following −" }, { "code": null, "e": 1451, "s": 1394, "text": "A1 = {2, 1, 2, 1, 7, 5, 9, 3, 8, 6, 8}\nA2 = {2, 1, 8, 3}" }, { "code": null, "e": 1493, "s": 1451, "text": "After the sorting A1 will be like below −" }, { "code": null, "e": 1532, "s": 1493, "text": "A1 = {2, 2, 1, 1, 8, 8, 3, 5, 6, 7, 9}" }, { "code": null, "e": 1701, "s": 1532, "text": "To solve this problem, we will create our custom compare method. That method will compare and place the elements in the array. The comparison logic will be like below −" }, { "code": null, "e": 1822, "s": 1701, "text": "if num1 and num2 both are in A2, then number with the lower index in A2 will be treated as smaller than the other number" }, { "code": null, "e": 1957, "s": 1822, "text": "If either num1 or num2 is present in A2, then that number will be treated as smaller, than the other, which is does not present in A2." }, { "code": null, "e": 2024, "s": 1957, "text": "If both are not present in A2, then natural ordering will be used." }, { "code": null, "e": 2274, "s": 2024, "text": "compare(num1, num2):\nBegin\n if both num1 and num2 are present in A2, then\n return index of num1 – index of num2\n else if num1 is not in A2, then\n return -1\n else if num2 is not in A1, then\n return 1\n else\n num1 – num2\nEnd" }, { "code": null, "e": 2285, "s": 2274, "text": " Live Demo" }, { "code": null, "e": 3219, "s": 2285, "text": "#include<iostream>\n#include<algorithm>\nusing namespace std;\nint size = 5;\nint A2[5]; //global A2 will be used in compare function\nint search_index(int key){\n int index = 0;\n for(int i = 0; i < size; i++){\n if(A2[i] == key)\n return i;\n }\n return -1;\n}\nint compare(const void *num1, const void *num2){\n int index1 = search_index(*(int*)num1);\n int index2 = search_index(*(int*)num2);\n if (index1 != -1 && index2 != -1)\n return index1 - index2;\n else if (index1 != -1)\n return -1;\n else if (index2 != -1)\n return 1;\n else\n return (*(int*)num1 - *(int*)num2);\n}\nmain(){\n int data[] = {2, 1, 2, 1, 7, 5, 9, 3, 8, 6, 8};\n int n = sizeof(data)/sizeof(data[0]);\n int a2[] = {2, 1, 8, 3};\n int n2 = sizeof(a2)/sizeof(a2[0]);\n for(int i = 0; i<n2; i++){\n A2[i] = a2[i];\n }\n qsort(data, n, sizeof(int), compare);\n for(int i = 0; i<n; i++){\n cout << data[i] << \" \";\n }\n}" }, { "code": null, "e": 3241, "s": 3219, "text": "2 2 1 1 8 8 3 5 6 7 9" } ]
How can Matplotlib be used to create 3 dimensional contour plot using Python?
Matplotlib is a popular Python package that is used for data visualization. Visualizing data is a key step since it helps understand what is going on in the data without actually looking at the numbers and performing complicated computations. It helps in communicating the quantitative insights to the audience effectively. Matplotlib is used to create 2 dimensional plots with the data. It comes with an object oriented API that helps in embedding the plots in Python applications. Matplotlib can be used with IPython shells, Jupyter notebook, Spyder IDE and so on. It is written in Python. It is created using Numpy, which is the Numerical Python package in Python. Python can be installed on Windows using the below command − pip install matplotlib The dependencies of Matplotlib are − Python ( greater than or equal to version 3.4) NumPy Setuptools Pyparsing Libpng Pytz Free type Six Cycler Dateutil Three dimensional plots are created to view the x−, y− and z−axes of the data points. It can also be used to understand how the gradient descent function works, and to find the optimal values for coefficients for an algorithm. Let us understand how Matplotlib can be used to create three−dimensional contour plot − from mpl_toolkits import mplot3d import numpy as np import matplotlib.pyplot as plt def fun(x, y): return np.sin(np.sqrt(x ** 2 + y ** 2)) x = np.linspace(−5, 5, 30) y = np.linspace(−5, 5, 30) X, Y = np.meshgrid(x, y) Z = fun (X, Y) fig = plt.figure() ax = plt.axes(projection='3d') ax.contour3D(X, Y, Z, 50, cmap='binary') ax.set_ylabel("Y−axis") ax.set_xlabel("X−axis") ax.set_zlabel("Z−axis") ax.set_title('A sample 3D contour plot') plt.show() The required packages are imported and its alias is defined for ease of use. The required packages are imported and its alias is defined for ease of use. A function ‘fun’ is created that generates data using the ‘sin’ function using two variables. A function ‘fun’ is created that generates data using the ‘sin’ function using two variables. The data values are created using the NumPy library. The data values are created using the NumPy library. An empty figure is created using the ‘figure’ function. An empty figure is created using the ‘figure’ function. The ‘axes’ function is used to create an axis to plot the graph. The ‘axes’ function is used to create an axis to plot the graph. The ‘contour3D’ is used to specify that a 3−dimensional contour plot is being visualized with the data that has been created. The ‘contour3D’ is used to specify that a 3−dimensional contour plot is being visualized with the data that has been created. The set_xlabel, set_ylabel, ‘z_label’ and set_title functions are used to provide labels for ‘X’ axis, ‘Y’ axis, Z-axis and title. The set_xlabel, set_ylabel, ‘z_label’ and set_title functions are used to provide labels for ‘X’ axis, ‘Y’ axis, Z-axis and title. It is shown on the console using the ‘show’ function. It is shown on the console using the ‘show’ function.
[ { "code": null, "e": 1386, "s": 1062, "text": "Matplotlib is a popular Python package that is used for data visualization. Visualizing data is a key step since it helps understand what is going on in the data without actually looking at the numbers and performing complicated computations. It helps in communicating the quantitative insights to the audience effectively." }, { "code": null, "e": 1629, "s": 1386, "text": "Matplotlib is used to create 2 dimensional plots with the data. It comes with an object oriented API that helps in embedding the plots in Python applications. Matplotlib can be used with IPython shells, Jupyter notebook, Spyder IDE and so on." }, { "code": null, "e": 1730, "s": 1629, "text": "It is written in Python. It is created using Numpy, which is the Numerical Python package in Python." }, { "code": null, "e": 1791, "s": 1730, "text": "Python can be installed on Windows using the below command −" }, { "code": null, "e": 1814, "s": 1791, "text": "pip install matplotlib" }, { "code": null, "e": 1851, "s": 1814, "text": "The dependencies of Matplotlib are −" }, { "code": null, "e": 1967, "s": 1851, "text": "Python ( greater than or equal to version 3.4)\nNumPy\nSetuptools\nPyparsing\nLibpng\nPytz\nFree type\nSix\nCycler\nDateutil" }, { "code": null, "e": 2194, "s": 1967, "text": "Three dimensional plots are created to view the x−, y− and z−axes of the data points. It can also be used to understand how the gradient descent function works, and to find the optimal values for coefficients for an algorithm." }, { "code": null, "e": 2282, "s": 2194, "text": "Let us understand how Matplotlib can be used to create three−dimensional contour plot −" }, { "code": null, "e": 2734, "s": 2282, "text": "from mpl_toolkits import mplot3d\nimport numpy as np\nimport matplotlib.pyplot as plt\ndef fun(x, y):\nreturn np.sin(np.sqrt(x ** 2 + y ** 2))\n\nx = np.linspace(−5, 5, 30)\ny = np.linspace(−5, 5, 30)\n\nX, Y = np.meshgrid(x, y)\nZ = fun (X, Y)\n\nfig = plt.figure()\nax = plt.axes(projection='3d')\nax.contour3D(X, Y, Z, 50, cmap='binary')\nax.set_ylabel(\"Y−axis\")\nax.set_xlabel(\"X−axis\")\nax.set_zlabel(\"Z−axis\")\n\nax.set_title('A sample 3D contour plot')\nplt.show()" }, { "code": null, "e": 2811, "s": 2734, "text": "The required packages are imported and its alias is defined for ease of use." }, { "code": null, "e": 2888, "s": 2811, "text": "The required packages are imported and its alias is defined for ease of use." }, { "code": null, "e": 2982, "s": 2888, "text": "A function ‘fun’ is created that generates data using the ‘sin’ function using two variables." }, { "code": null, "e": 3076, "s": 2982, "text": "A function ‘fun’ is created that generates data using the ‘sin’ function using two variables." }, { "code": null, "e": 3129, "s": 3076, "text": "The data values are created using the NumPy library." }, { "code": null, "e": 3182, "s": 3129, "text": "The data values are created using the NumPy library." }, { "code": null, "e": 3238, "s": 3182, "text": "An empty figure is created using the ‘figure’ function." }, { "code": null, "e": 3294, "s": 3238, "text": "An empty figure is created using the ‘figure’ function." }, { "code": null, "e": 3359, "s": 3294, "text": "The ‘axes’ function is used to create an axis to plot the graph." }, { "code": null, "e": 3424, "s": 3359, "text": "The ‘axes’ function is used to create an axis to plot the graph." }, { "code": null, "e": 3550, "s": 3424, "text": "The ‘contour3D’ is used to specify that a 3−dimensional contour plot is being visualized with the data that has been created." }, { "code": null, "e": 3676, "s": 3550, "text": "The ‘contour3D’ is used to specify that a 3−dimensional contour plot is being visualized with the data that has been created." }, { "code": null, "e": 3807, "s": 3676, "text": "The set_xlabel, set_ylabel, ‘z_label’ and set_title functions are used to provide labels for ‘X’ axis, ‘Y’ axis, Z-axis and title." }, { "code": null, "e": 3938, "s": 3807, "text": "The set_xlabel, set_ylabel, ‘z_label’ and set_title functions are used to provide labels for ‘X’ axis, ‘Y’ axis, Z-axis and title." }, { "code": null, "e": 3992, "s": 3938, "text": "It is shown on the console using the ‘show’ function." }, { "code": null, "e": 4046, "s": 3992, "text": "It is shown on the console using the ‘show’ function." } ]
What is HMAC(Hash based Message Authentication Code)? - GeeksforGeeks
31 Aug, 2021 HMAC (Hash-based Message Authentication Code) is a type of a message authentication code (MAC) that is acquired by executing a cryptographic hash function on the data (that is) to be authenticated and a secret shared key. Like any of the MAC, it is used for both data integrity and authentication. Checking data integrity is necessary for the parties involved in communication. HTTPS, SFTP, FTPS, and other transfer protocols use HMAC. The cryptographic hash function may be MD-5, SHA-1, or SHA-256. Digital signatures are nearly similar to HMACs i.e they both employ a hash function and a shared key. The difference lies in the keys i.e HMACs use symmetric key(same copy) while Signatures use asymmetric (two different keys). Processes and decisions pertinent to business are greatly dependent on integrity. If attackers tamper this data, it may affect the processes and business decisions. So while working online over the internet, care must be taken to ensure integrity or least know if the data is changed. That is when HMAC comes into use. Applications Verification of e-mail address during activation or creation of an account. Authentication of form data that is sent to the client browser and then submitted back. HMACs can be used for Internet of things (IoT) due to less cost. Whenever there is a need to reset the password, a link that can be used once is sent without adding a server state. It can take a message of any length and convert it into a fixed-length message digest. That is even if you got a long message, the message digest will be small and thus permits maximizing bandwidth. HMACs provides client and server with a shared private key that is known only to them. The client makes a unique hash (HMAC) for every request. When the client requests the server, it hashes the requested data with a private key and sends it as a part of the request. Both the message and key are hashed in separate steps making it secure. When the server receives the request, it makes its own HMAC. Both the HMACS are compared and if both are equal, the client is considered legitimate. The formula for HMAC: HMAC = hashFunc(secret key + message) There are three types of authentication functions. They are message encryption, message authentication code, and hash functions. The major difference between MAC and hash (HMAC here) is the dependence of a key. In HMAC we have to apply the hash function along with a key on the plain text. The hash function will be applied to the plain text message. But before applying, we have to compute S bits and then append it to plain text and after that apply the hash function. For generating those S bits we make use of a key that is shared between the sender and receiver. Using key K (0 < K < b), K+ is generated by padding O’s on left side of key K until length becomes b bits. The reason why it’s not padded on right is change(increase) in the length of key. b bits because it is the block size of plain text. There are two predefined padding bits called ipad and opad. All this is done before applying hash function to the plain text message. ipad - 00110110 opad - 01011100 Now we have to calculate S bits K+ is EXORed with ipad and the result is S1 bits which is equivalent to b bits since both K+ and ipad are b bits. We have to append S1 with plain text messages. Let P be the plain text message. S1, p0, p1 upto Pm each is b bits. m is the number of plain text blocks. P0 is plain text block and b is plain text block size. After appending S1 to Plain text we have to apply HASH algorithm (any variant). Simultaneously we have to apply initialization vector (IV) which is a buffer of size n-bits. The result produced is therefore n-bit hashcode i.e H( S1 || M ). Similarly, n-bits are padded to b-bits And K+ is EXORed with opad producing output S2 bits. S2 is appended to the b-bits and once again hash function is applied with IV to the block. This further results into n-bit hashcode which is H( S2 || H( S1 || M )). Summary: Select K. If K < b, pad 0’s on left until k=b. K is between 0 and b ( 0 < K < b )EXOR K+ with ipad equivalent to b bits producing S1 bits.Append S1 with plain text MApply SHA-512 on ( S1 || M )Pad n-bits until length is equal to b-bitsEXOR K+ with opad equivalent to b bits producing S2 bits.Append S2 with output of step 5.Apply SHA-512 on step 7 to output n-bit hashcode. Select K. If K < b, pad 0’s on left until k=b. K is between 0 and b ( 0 < K < b ) EXOR K+ with ipad equivalent to b bits producing S1 bits. Append S1 with plain text M Apply SHA-512 on ( S1 || M ) Pad n-bits until length is equal to b-bits EXOR K+ with opad equivalent to b bits producing S2 bits. Append S2 with output of step 5. Apply SHA-512 on step 7 to output n-bit hashcode. HMACs are ideal for high-performance systems like routers due to the use of hash functions which are calculated and verified quickly unlike the public key systems. Digital signatures are larger than HMACs, yet the HMACs provide comparably higher security. HMACs are used in administrations where public key systems are prohibited. HMACs uses shared key which may lead to non-repudiation. If either sender or receiver’s key is compromised then it will be easy for attackers to create unauthorized messages. chhabradhanvi Picked Computer Networks Computer Networks Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. TCP Server-Client implementation in C Differences between TCP and UDP Socket Programming in Python Types of Network Topology UDP Server-Client implementation in C Types of Transmission Media TCP 3-Way Handshake Process Error Detection in Computer Networks Differences between IPv4 and IPv6 Hamming Code in Computer Network
[ { "code": null, "e": 24514, "s": 24486, "text": "\n31 Aug, 2021" }, { "code": null, "e": 25242, "s": 24514, "text": "HMAC (Hash-based Message Authentication Code) is a type of a message authentication code (MAC) that is acquired by executing a cryptographic hash function on the data (that is) to be authenticated and a secret shared key. Like any of the MAC, it is used for both data integrity and authentication. Checking data integrity is necessary for the parties involved in communication. HTTPS, SFTP, FTPS, and other transfer protocols use HMAC. The cryptographic hash function may be MD-5, SHA-1, or SHA-256. Digital signatures are nearly similar to HMACs i.e they both employ a hash function and a shared key. The difference lies in the keys i.e HMACs use symmetric key(same copy) while Signatures use asymmetric (two different keys). " }, { "code": null, "e": 25564, "s": 25244, "text": "Processes and decisions pertinent to business are greatly dependent on integrity. If attackers tamper this data, it may affect the processes and business decisions. So while working online over the internet, care must be taken to ensure integrity or least know if the data is changed. That is when HMAC comes into use. " }, { "code": null, "e": 25578, "s": 25564, "text": " Applications" }, { "code": null, "e": 25654, "s": 25578, "text": "Verification of e-mail address during activation or creation of an account." }, { "code": null, "e": 25742, "s": 25654, "text": "Authentication of form data that is sent to the client browser and then submitted back." }, { "code": null, "e": 25807, "s": 25742, "text": "HMACs can be used for Internet of things (IoT) due to less cost." }, { "code": null, "e": 25923, "s": 25807, "text": "Whenever there is a need to reset the password, a link that can be used once is sent without adding a server state." }, { "code": null, "e": 26122, "s": 25923, "text": "It can take a message of any length and convert it into a fixed-length message digest. That is even if you got a long message, the message digest will be small and thus permits maximizing bandwidth." }, { "code": null, "e": 26612, "s": 26122, "text": "HMACs provides client and server with a shared private key that is known only to them. The client makes a unique hash (HMAC) for every request. When the client requests the server, it hashes the requested data with a private key and sends it as a part of the request. Both the message and key are hashed in separate steps making it secure. When the server receives the request, it makes its own HMAC. Both the HMACS are compared and if both are equal, the client is considered legitimate. " }, { "code": null, "e": 26636, "s": 26612, "text": "The formula for HMAC: " }, { "code": null, "e": 26676, "s": 26636, "text": " HMAC = hashFunc(secret key + message) " }, { "code": null, "e": 27246, "s": 26676, "text": "There are three types of authentication functions. They are message encryption, message authentication code, and hash functions. The major difference between MAC and hash (HMAC here) is the dependence of a key. In HMAC we have to apply the hash function along with a key on the plain text. The hash function will be applied to the plain text message. But before applying, we have to compute S bits and then append it to plain text and after that apply the hash function. For generating those S bits we make use of a key that is shared between the sender and receiver. " }, { "code": null, "e": 27622, "s": 27246, "text": "Using key K (0 < K < b), K+ is generated by padding O’s on left side of key K until length becomes b bits. The reason why it’s not padded on right is change(increase) in the length of key. b bits because it is the block size of plain text. There are two predefined padding bits called ipad and opad. All this is done before applying hash function to the plain text message. " }, { "code": null, "e": 27657, "s": 27622, "text": " ipad - 00110110 \n opad - 01011100" }, { "code": null, "e": 28508, "s": 27657, "text": "Now we have to calculate S bits K+ is EXORed with ipad and the result is S1 bits which is equivalent to b bits since both K+ and ipad are b bits. We have to append S1 with plain text messages. Let P be the plain text message. S1, p0, p1 upto Pm each is b bits. m is the number of plain text blocks. P0 is plain text block and b is plain text block size. After appending S1 to Plain text we have to apply HASH algorithm (any variant). Simultaneously we have to apply initialization vector (IV) which is a buffer of size n-bits. The result produced is therefore n-bit hashcode i.e H( S1 || M ). Similarly, n-bits are padded to b-bits And K+ is EXORed with opad producing output S2 bits. S2 is appended to the b-bits and once again hash function is applied with IV to the block. This further results into n-bit hashcode which is H( S2 || H( S1 || M )). " }, { "code": null, "e": 28519, "s": 28508, "text": "Summary: " }, { "code": null, "e": 28893, "s": 28519, "text": "Select K. If K < b, pad 0’s on left until k=b. K is between 0 and b ( 0 < K < b )EXOR K+ with ipad equivalent to b bits producing S1 bits.Append S1 with plain text MApply SHA-512 on ( S1 || M )Pad n-bits until length is equal to b-bitsEXOR K+ with opad equivalent to b bits producing S2 bits.Append S2 with output of step 5.Apply SHA-512 on step 7 to output n-bit hashcode." }, { "code": null, "e": 28975, "s": 28893, "text": "Select K. If K < b, pad 0’s on left until k=b. K is between 0 and b ( 0 < K < b )" }, { "code": null, "e": 29033, "s": 28975, "text": "EXOR K+ with ipad equivalent to b bits producing S1 bits." }, { "code": null, "e": 29061, "s": 29033, "text": "Append S1 with plain text M" }, { "code": null, "e": 29090, "s": 29061, "text": "Apply SHA-512 on ( S1 || M )" }, { "code": null, "e": 29133, "s": 29090, "text": "Pad n-bits until length is equal to b-bits" }, { "code": null, "e": 29191, "s": 29133, "text": "EXOR K+ with opad equivalent to b bits producing S2 bits." }, { "code": null, "e": 29224, "s": 29191, "text": "Append S2 with output of step 5." }, { "code": null, "e": 29274, "s": 29224, "text": "Apply SHA-512 on step 7 to output n-bit hashcode." }, { "code": null, "e": 29438, "s": 29274, "text": "HMACs are ideal for high-performance systems like routers due to the use of hash functions which are calculated and verified quickly unlike the public key systems." }, { "code": null, "e": 29530, "s": 29438, "text": "Digital signatures are larger than HMACs, yet the HMACs provide comparably higher security." }, { "code": null, "e": 29605, "s": 29530, "text": "HMACs are used in administrations where public key systems are prohibited." }, { "code": null, "e": 29780, "s": 29605, "text": "HMACs uses shared key which may lead to non-repudiation. If either sender or receiver’s key is compromised then it will be easy for attackers to create unauthorized messages." }, { "code": null, "e": 29796, "s": 29782, "text": "chhabradhanvi" }, { "code": null, "e": 29803, "s": 29796, "text": "Picked" }, { "code": null, "e": 29821, "s": 29803, "text": "Computer Networks" }, { "code": null, "e": 29839, "s": 29821, "text": "Computer Networks" }, { "code": null, "e": 29937, "s": 29839, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29975, "s": 29937, "text": "TCP Server-Client implementation in C" }, { "code": null, "e": 30007, "s": 29975, "text": "Differences between TCP and UDP" }, { "code": null, "e": 30036, "s": 30007, "text": "Socket Programming in Python" }, { "code": null, "e": 30062, "s": 30036, "text": "Types of Network Topology" }, { "code": null, "e": 30100, "s": 30062, "text": "UDP Server-Client implementation in C" }, { "code": null, "e": 30128, "s": 30100, "text": "Types of Transmission Media" }, { "code": null, "e": 30156, "s": 30128, "text": "TCP 3-Way Handshake Process" }, { "code": null, "e": 30193, "s": 30156, "text": "Error Detection in Computer Networks" }, { "code": null, "e": 30227, "s": 30193, "text": "Differences between IPv4 and IPv6" } ]
semctl() - Unix, Linux System Call
Unix - Home Unix - Getting Started Unix - File Management Unix - Directories Unix - File Permission Unix - Environment Unix - Basic Utilities Unix - Pipes & Filters Unix - Processes Unix - Communication Unix - The vi Editor Unix - What is Shell? Unix - Using Variables Unix - Special Variables Unix - Using Arrays Unix - Basic Operators Unix - Decision Making Unix - Shell Loops Unix - Loop Control Unix - Shell Substitutions Unix - Quoting Mechanisms Unix - IO Redirections Unix - Shell Functions Unix - Manpage Help Unix - Regular Expressions Unix - File System Basics Unix - User Administration Unix - System Performance Unix - System Logging Unix - Signals and Traps Unix - Useful Commands Unix - Quick Guide Unix - Builtin Functions Unix - System Calls Unix - Commands List Unix Useful Resources Computer Glossary Who is Who Copyright © 2014 by tutorialspoint #include <sys/types.h> #include <sys/ipc.h> #include <sys/sem.h> int semctl(int semid, int semnum, int cmd, ...); int semctl(int semid, int semnum, int cmd, ...); This function has three or four arguments, depending on cmd. When there are four, the fourth has the type union semun. The calling program must define this union as follows: union semun { int val; /* Value for SETVAL */ struct semid_ds *buf; /* Buffer for IPC_STAT, IPC_SET */ unsigned short *array; /* Array for GETALL, SETALL */ struct seminfo *__buf; /* Buffer for IPC_INFO (Linux specific) */ }; The semid_ds data structure is defined in <sys/sem.h> as follows: struct semid_ds { struct ipc_perm sem_perm; /* Ownership and permissions time_t sem_otime; /* Last semop time */ time_t sem_ctime; /* Last change time */ unsigned short sem_nsems; /* No. of semaphores in set */ }; struct semid_ds { struct ipc_perm sem_perm; /* Ownership and permissions time_t sem_otime; /* Last semop time */ time_t sem_ctime; /* Last change time */ unsigned short sem_nsems; /* No. of semaphores in set */ }; The ipc_perm structure is defined in <sys/ipc.h> as follows (the highlighted fields are settable using IPC_SET): struct ipc_perm { key_t key; /* Key supplied to semget() */ uid_t uid; /* Effective UID of owner */ gid_t gid; /* Effective GID of owner */ uid_t cuid; /* Effective UID of creator */ gid_t cgid; /* Effective GID of creator */ unsigned short mode; /* Permissions */ unsigned short seq; /* Sequence number */ }; Valid values for cmd are: struct seminfo { int semmap; /* # of entries in semaphore map; unused */ int semmni; /* Max. # of semaphore sets */ int semmns; /* Max. # of semaphores in all semaphore sets */ int semmnu; /* System-wide max. # of undo structures; unused */ int semmsl; /* Max. # of semaphores in a set */ int semopm; /* Max. # of operations for semop() */ int semume; /* Max. # of undo entries per process; unused */ int semusz; /* size of struct sem_undo */ int semvmx; /* Maximum semaphore value */ int semaem; /* Max. value that can be recorded for semaphore adjustment (SEM_UNDO) */ }; struct seminfo { int semmap; /* # of entries in semaphore map; unused */ int semmni; /* Max. # of semaphore sets */ int semmns; /* Max. # of semaphores in all semaphore sets */ int semmnu; /* System-wide max. # of undo structures; unused */ int semmsl; /* Max. # of semaphores in a set */ int semopm; /* Max. # of operations for semop() */ int semume; /* Max. # of undo entries per process; unused */ int semusz; /* size of struct sem_undo */ int semvmx; /* Maximum semaphore value */ int semaem; /* Max. value that can be recorded for semaphore adjustment (SEM_UNDO) */ }; Otherwise the system call returns a nonnegative value depending on cmd as follows: Various fields in a struct semid_ds were shorts under Linux 2.2 and have become longs under Linux 2.4. To take advantage of this, a recompilation under glibc-2.1.91 or later should suffice. (The kernel distinguishes old and new calls by an IPC_64 flag in cmd.) In some earlier versions of glibc, the semun union was defined in <sys/sem.h>, but POSIX.1-2001 requires that the caller define this union. On versions of glibc where this union is not defined, the macro _SEM_SEMUN_UNDEFINED is defined in <sys/sem.h>. The following system limit on semaphore sets affects a semctl() call: Under Linux, semctl() is not a system call, but is implemented via the system call ipc(2). ipc (2) ipc (2) semget (2) semget (2) semop (2) semop (2) Advertisements 129 Lectures 23 hours Eduonix Learning Solutions 5 Lectures 4.5 hours Frahaan Hussain 35 Lectures 2 hours Pradeep D 41 Lectures 2.5 hours Musab Zayadneh 46 Lectures 4 hours GUHARAJANM 6 Lectures 4 hours Uplatz Print Add Notes Bookmark this page
[ { "code": null, "e": 1466, "s": 1454, "text": "Unix - Home" }, { "code": null, "e": 1489, "s": 1466, "text": "Unix - Getting Started" }, { "code": null, "e": 1512, "s": 1489, "text": "Unix - File Management" }, { "code": null, "e": 1531, "s": 1512, "text": "Unix - Directories" }, { "code": null, "e": 1554, "s": 1531, "text": "Unix - File Permission" }, { "code": null, "e": 1573, "s": 1554, "text": "Unix - Environment" }, { "code": null, "e": 1596, "s": 1573, "text": "Unix - Basic Utilities" }, { "code": null, "e": 1619, "s": 1596, "text": "Unix - Pipes & Filters" }, { "code": null, "e": 1636, "s": 1619, "text": "Unix - Processes" }, { "code": null, "e": 1657, "s": 1636, "text": "Unix - Communication" }, { "code": null, "e": 1678, "s": 1657, "text": "Unix - The vi Editor" }, { "code": null, "e": 1700, "s": 1678, "text": "Unix - What is Shell?" }, { "code": null, "e": 1723, "s": 1700, "text": "Unix - Using Variables" }, { "code": null, "e": 1748, "s": 1723, "text": "Unix - Special Variables" }, { "code": null, "e": 1768, "s": 1748, "text": "Unix - Using Arrays" }, { "code": null, "e": 1791, "s": 1768, "text": "Unix - Basic Operators" }, { "code": null, "e": 1814, "s": 1791, "text": "Unix - Decision Making" }, { "code": null, "e": 1833, "s": 1814, "text": "Unix - Shell Loops" }, { "code": null, "e": 1853, "s": 1833, "text": "Unix - Loop Control" }, { "code": null, "e": 1880, "s": 1853, "text": "Unix - Shell Substitutions" }, { "code": null, "e": 1906, "s": 1880, "text": "Unix - Quoting Mechanisms" }, { "code": null, "e": 1929, "s": 1906, "text": "Unix - IO Redirections" }, { "code": null, "e": 1952, "s": 1929, "text": "Unix - Shell Functions" }, { "code": null, "e": 1972, "s": 1952, "text": "Unix - Manpage Help" }, { "code": null, "e": 1999, "s": 1972, "text": "Unix - Regular Expressions" }, { "code": null, "e": 2025, "s": 1999, "text": "Unix - File System Basics" }, { "code": null, "e": 2052, "s": 2025, "text": "Unix - User Administration" }, { "code": null, "e": 2078, "s": 2052, "text": "Unix - System Performance" }, { "code": null, "e": 2100, "s": 2078, "text": "Unix - System Logging" }, { "code": null, "e": 2125, "s": 2100, "text": "Unix - Signals and Traps" }, { "code": null, "e": 2148, "s": 2125, "text": "Unix - Useful Commands" }, { "code": null, "e": 2167, "s": 2148, "text": "Unix - Quick Guide" }, { "code": null, "e": 2192, "s": 2167, "text": "Unix - Builtin Functions" }, { "code": null, "e": 2212, "s": 2192, "text": "Unix - System Calls" }, { "code": null, "e": 2233, "s": 2212, "text": "Unix - Commands List" }, { "code": null, "e": 2255, "s": 2233, "text": "Unix Useful Resources" }, { "code": null, "e": 2273, "s": 2255, "text": "Computer Glossary" }, { "code": null, "e": 2284, "s": 2273, "text": "Who is Who" }, { "code": null, "e": 2319, "s": 2284, "text": "Copyright © 2014 by tutorialspoint" }, { "code": null, "e": 2439, "s": 2319, "text": "#include <sys/types.h> \n#include <sys/ipc.h> \n#include <sys/sem.h> \n\nint semctl(int semid, int semnum, int cmd, ...); \n" }, { "code": null, "e": 2491, "s": 2439, "text": "\nint semctl(int semid, int semnum, int cmd, ...); \n" }, { "code": null, "e": 2667, "s": 2491, "text": "\nThis function has three or four arguments, depending on\ncmd. When there are four, the fourth has the type\nunion semun. The calling program must define this union as follows:\n" }, { "code": null, "e": 2969, "s": 2669, "text": "\nunion semun {\n int val; /* Value for SETVAL */\n struct semid_ds *buf; /* Buffer for IPC_STAT, IPC_SET */\n unsigned short *array; /* Array for GETALL, SETALL */\n struct seminfo *__buf; /* Buffer for IPC_INFO\n (Linux specific) */\n};\n\n" }, { "code": null, "e": 3037, "s": 2969, "text": "\nThe\nsemid_ds data structure is defined in <sys/sem.h> as follows:\n" }, { "code": null, "e": 3291, "s": 3037, "text": "\n\nstruct semid_ds {\n struct ipc_perm sem_perm; /* Ownership and permissions\n time_t sem_otime; /* Last semop time */\n time_t sem_ctime; /* Last change time */\n unsigned short sem_nsems; /* No. of semaphores in set */\n};\n\n" }, { "code": null, "e": 3544, "s": 3291, "text": "\nstruct semid_ds {\n struct ipc_perm sem_perm; /* Ownership and permissions\n time_t sem_otime; /* Last semop time */\n time_t sem_ctime; /* Last change time */\n unsigned short sem_nsems; /* No. of semaphores in set */\n};\n\n" }, { "code": null, "e": 3659, "s": 3544, "text": "\nThe\nipc_perm structure is defined in <sys/ipc.h> as follows\n(the highlighted fields are settable using\nIPC_SET): " }, { "code": null, "e": 4058, "s": 3661, "text": "\nstruct ipc_perm {\n key_t key; /* Key supplied to semget() */\n uid_t uid; /* Effective UID of owner */\n gid_t gid; /* Effective GID of owner */\n uid_t cuid; /* Effective UID of creator */\n gid_t cgid; /* Effective GID of creator */\n unsigned short mode; /* Permissions */\n unsigned short seq; /* Sequence number */\n};\n\n" }, { "code": null, "e": 4086, "s": 4058, "text": "\nValid values for\ncmd are:\n" }, { "code": null, "e": 4816, "s": 4086, "text": "\n\nstruct seminfo {\n int semmap; /* # of entries in semaphore map;\n unused */\n int semmni; /* Max. # of semaphore sets */\n int semmns; /* Max. # of semaphores in all\n semaphore sets */\n int semmnu; /* System-wide max. # of undo\n structures; unused */\n int semmsl; /* Max. # of semaphores in a set */\n int semopm; /* Max. # of operations for semop() */\n int semume; /* Max. # of undo entries per\n process; unused */\n int semusz; /* size of struct sem_undo */\n int semvmx; /* Maximum semaphore value */\n int semaem; /* Max. value that can be recorded for\n semaphore adjustment (SEM_UNDO) */\n};\n\n\n" }, { "code": null, "e": 5543, "s": 4816, "text": "\nstruct seminfo {\n int semmap; /* # of entries in semaphore map;\n unused */\n int semmni; /* Max. # of semaphore sets */\n int semmns; /* Max. # of semaphores in all\n semaphore sets */\n int semmnu; /* System-wide max. # of undo\n structures; unused */\n int semmsl; /* Max. # of semaphores in a set */\n int semopm; /* Max. # of operations for semop() */\n int semume; /* Max. # of undo entries per\n process; unused */\n int semusz; /* size of struct sem_undo */\n int semvmx; /* Maximum semaphore value */\n int semaem; /* Max. value that can be recorded for\n semaphore adjustment (SEM_UNDO) */\n};\n" }, { "code": null, "e": 5631, "s": 5546, "text": "\nOtherwise the system call returns a nonnegative value depending on\ncmd as follows:\n" }, { "code": null, "e": 5894, "s": 5631, "text": "\nVarious fields in a struct semid_ds were shorts under Linux 2.2\nand have become longs under Linux 2.4. To take advantage of this,\na recompilation under glibc-2.1.91 or later should suffice.\n(The kernel distinguishes old and new calls by an IPC_64 flag in\ncmd.) " }, { "code": null, "e": 6148, "s": 5894, "text": "\nIn some earlier versions of glibc, the\nsemun union was defined in <sys/sem.h>, but POSIX.1-2001 requires\nthat the caller define this union.\nOn versions of glibc where this union is not defined,\nthe macro\n_SEM_SEMUN_UNDEFINED is defined in <sys/sem.h>.\n" }, { "code": null, "e": 6220, "s": 6148, "text": "\nThe following system limit on semaphore sets affects a\nsemctl() call:\n" }, { "code": null, "e": 6313, "s": 6220, "text": "\nUnder Linux,\nsemctl() is not a system call, but is implemented via the system call\nipc(2).\n" }, { "code": null, "e": 6321, "s": 6313, "text": "ipc (2)" }, { "code": null, "e": 6329, "s": 6321, "text": "ipc (2)" }, { "code": null, "e": 6340, "s": 6329, "text": "semget (2)" }, { "code": null, "e": 6351, "s": 6340, "text": "semget (2)" }, { "code": null, "e": 6361, "s": 6351, "text": "semop (2)" }, { "code": null, "e": 6371, "s": 6361, "text": "semop (2)" }, { "code": null, "e": 6388, "s": 6371, "text": "\nAdvertisements\n" }, { "code": null, "e": 6423, "s": 6388, "text": "\n 129 Lectures \n 23 hours \n" }, { "code": null, "e": 6451, "s": 6423, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 6485, "s": 6451, "text": "\n 5 Lectures \n 4.5 hours \n" }, { "code": null, "e": 6502, "s": 6485, "text": " Frahaan Hussain" }, { "code": null, "e": 6535, "s": 6502, "text": "\n 35 Lectures \n 2 hours \n" }, { "code": null, "e": 6546, "s": 6535, "text": " Pradeep D" }, { "code": null, "e": 6581, "s": 6546, "text": "\n 41 Lectures \n 2.5 hours \n" }, { "code": null, "e": 6597, "s": 6581, "text": " Musab Zayadneh" }, { "code": null, "e": 6630, "s": 6597, "text": "\n 46 Lectures \n 4 hours \n" }, { "code": null, "e": 6642, "s": 6630, "text": " GUHARAJANM" }, { "code": null, "e": 6674, "s": 6642, "text": "\n 6 Lectures \n 4 hours \n" }, { "code": null, "e": 6682, "s": 6674, "text": " Uplatz" }, { "code": null, "e": 6689, "s": 6682, "text": " Print" }, { "code": null, "e": 6700, "s": 6689, "text": " Add Notes" } ]
File lastModified() method in Java with Examples - GeeksforGeeks
28 Jan, 2019 The lastModified() function is a part of File class in Java . This function returns the time denoted by the this abstract pathname was last modified.The function returns long value measured in milliseconds, representing the time the file was last modified else returns 0L if the file does not exists or if an exception occurs. Function signature: public long lastModified() Syntax: long valr = file.lastModified(); Parameters: This method does not accept any parameter. Return TypeThis function returns long data type representing the time the file was last modified or 0L if the file does not exist. Exception: This method throws Security Exception if the write access to the file is denied Below programs illustrates the use of lastModified() function: Example 1: The file “F:\\program.txt” is a existing file in F: Directory. // Java program to demonstrate// lastModified() method of File Class import java.io.*; public class solution { public static void main(String args[]) { // Get the file File f = new File("F:\\program.txt"); // Get the last modified time of the file System.out.println("Last modified: " + f.lastModified()); }} Output: Last modified: 1542654265978 Example 2: The file “F:\\program1.txt” does not exist // Java program to demonstrate// lastModified() method of File Class import java.io.*; public class solution { public static void main(String args[]) { // Get the file File f = new File("F:\\program.txt"); // Get the last modified time of the file System.out.println("Last modified: " + f.lastModified()); }} Output: Last modified: 0 Note: The programs might not run in an online IDE. Please use an offline IDE and set the path of the file. Java-File Class Java-Functions Java-IO package Java Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments How to Iterate HashMap in Java? Iterate Over the Characters of a String in Java How to Get Elements By Index from HashSet in Java? Java Program to Write into a File How to Write Data into Excel Sheet using Java? SHA-1 Hash Java Program to Convert String to String Array Modulo or Remainder Operator in Java How to Replace a Element in Java ArrayList? How to convert Date to String in Java
[ { "code": null, "e": 24904, "s": 24876, "text": "\n28 Jan, 2019" }, { "code": null, "e": 25231, "s": 24904, "text": "The lastModified() function is a part of File class in Java . This function returns the time denoted by the this abstract pathname was last modified.The function returns long value measured in milliseconds, representing the time the file was last modified else returns 0L if the file does not exists or if an exception occurs." }, { "code": null, "e": 25251, "s": 25231, "text": "Function signature:" }, { "code": null, "e": 25278, "s": 25251, "text": "public long lastModified()" }, { "code": null, "e": 25286, "s": 25278, "text": "Syntax:" }, { "code": null, "e": 25319, "s": 25286, "text": "long valr = file.lastModified();" }, { "code": null, "e": 25374, "s": 25319, "text": "Parameters: This method does not accept any parameter." }, { "code": null, "e": 25505, "s": 25374, "text": "Return TypeThis function returns long data type representing the time the file was last modified or 0L if the file does not exist." }, { "code": null, "e": 25596, "s": 25505, "text": "Exception: This method throws Security Exception if the write access to the file is denied" }, { "code": null, "e": 25659, "s": 25596, "text": "Below programs illustrates the use of lastModified() function:" }, { "code": null, "e": 25733, "s": 25659, "text": "Example 1: The file “F:\\\\program.txt” is a existing file in F: Directory." }, { "code": "// Java program to demonstrate// lastModified() method of File Class import java.io.*; public class solution { public static void main(String args[]) { // Get the file File f = new File(\"F:\\\\program.txt\"); // Get the last modified time of the file System.out.println(\"Last modified: \" + f.lastModified()); }}", "e": 26111, "s": 25733, "text": null }, { "code": null, "e": 26119, "s": 26111, "text": "Output:" }, { "code": null, "e": 26148, "s": 26119, "text": "Last modified: 1542654265978" }, { "code": null, "e": 26202, "s": 26148, "text": "Example 2: The file “F:\\\\program1.txt” does not exist" }, { "code": "// Java program to demonstrate// lastModified() method of File Class import java.io.*; public class solution { public static void main(String args[]) { // Get the file File f = new File(\"F:\\\\program.txt\"); // Get the last modified time of the file System.out.println(\"Last modified: \" + f.lastModified()); }}", "e": 26580, "s": 26202, "text": null }, { "code": null, "e": 26588, "s": 26580, "text": "Output:" }, { "code": null, "e": 26605, "s": 26588, "text": "Last modified: 0" }, { "code": null, "e": 26712, "s": 26605, "text": "Note: The programs might not run in an online IDE. Please use an offline IDE and set the path of the file." }, { "code": null, "e": 26728, "s": 26712, "text": "Java-File Class" }, { "code": null, "e": 26743, "s": 26728, "text": "Java-Functions" }, { "code": null, "e": 26759, "s": 26743, "text": "Java-IO package" }, { "code": null, "e": 26773, "s": 26759, "text": "Java Programs" }, { "code": null, "e": 26871, "s": 26773, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26880, "s": 26871, "text": "Comments" }, { "code": null, "e": 26893, "s": 26880, "text": "Old Comments" }, { "code": null, "e": 26925, "s": 26893, "text": "How to Iterate HashMap in Java?" }, { "code": null, "e": 26973, "s": 26925, "text": "Iterate Over the Characters of a String in Java" }, { "code": null, "e": 27024, "s": 26973, "text": "How to Get Elements By Index from HashSet in Java?" }, { "code": null, "e": 27058, "s": 27024, "text": "Java Program to Write into a File" }, { "code": null, "e": 27105, "s": 27058, "text": "How to Write Data into Excel Sheet using Java?" }, { "code": null, "e": 27116, "s": 27105, "text": "SHA-1 Hash" }, { "code": null, "e": 27163, "s": 27116, "text": "Java Program to Convert String to String Array" }, { "code": null, "e": 27200, "s": 27163, "text": "Modulo or Remainder Operator in Java" }, { "code": null, "e": 27244, "s": 27200, "text": "How to Replace a Element in Java ArrayList?" } ]
Number of Simple Graph with N Vertices and M Edges - GeeksforGeeks
25 May, 2021 Given two integers N and M, the task is to count the number of simple undirected graphs that can be drawn with N vertices and M edges. A simple graph is a graph that does not contain multiple edges and self-loops. Examples: Input: N = 3, M = 1 Output: 3 The 3 graphs are {1-2, 3}, {2-3, 1}, {1-3, 2}. Input: N = 5, M = 1 Output: 10 Approach: The N vertices are numbered from 1 to N. As there are no self-loops or multiple edges, the edge must be present between two different vertices. So the number of ways we can choose two different vertices is NC2 which is equal to (N * (N – 1)) / 2. Assume it P. Now M edges must be used with these pairs of vertices, so the number of ways to choose M pairs of vertices between P pairs will be PCM. If P < M then the answer will be 0 as the extra edges can not be left alone. Below is the implementation of the above approach: C++ Java Python 3 C# PHP Javascript // C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Function to return the value of// Binomial Coefficient C(n, k)int binomialCoeff(int n, int k){ if (k > n) return 0; int res = 1; // Since C(n, k) = C(n, n-k) if (k > n - k) k = n - k; // Calculate the value of // [n * (n - 1) *---* (n - k + 1)] / [k * (k - 1) * ... * 1] for (int i = 0; i < k; ++i) { res *= (n - i); res /= (i + 1); } return res;} // Driver Codeint main(){ int N = 5, M = 1; int P = (N * (N - 1)) / 2; cout << binomialCoeff(P, M); return 0;} // Java implementation of the approachclass GFG{ // Function to return the value of // Binomial Coefficient C(n, k) static int binomialCoeff(int n, int k) { if (k > n) return 0; int res = 1; // Since C(n, k) = C(n, n-k) if (k > n - k) k = n - k; // Calculate the value of // [n * (n - 1) *---* (n - k + 1)] / // [k * (k - 1) * ... * 1] for (int i = 0; i < k; ++i) { res *= (n - i); res /= (i + 1); } return res; } // Driver Codepublic static void main(String[] args){ int N = 5, M = 1; int P = (N * (N - 1)) / 2; System.out.println(binomialCoeff(P, M));}} // This code is contributed by Shivi_Aggarwal # Python 3 implementation of the approach # Function to return the value of# Binomial Coefficient C(n, k)def binomialCoeff(n, k): if (k > n): return 0 res = 1 # Since C(n, k) = C(n, n-k) if (k > n - k): k = n - k # Calculate the value of # [n * (n - 1) *---* (n - k + 1)] / # [k * (k - 1) * ... * 1] for i in range( k): res *= (n - i) res //= (i + 1) return res # Driver Codeif __name__=="__main__": N = 5 M = 1 P = (N * (N - 1)) // 2 print(binomialCoeff(P, M)) # This code is contributed by ita_c // C# implementation of the approachusing System; class GFG{// Function to return the value of// Binomial Coefficient C(n, k)static int binomialCoeff(int n, int k){ if (k > n) return 0; int res = 1; // Since C(n, k) = C(n, n-k) if (k > n - k) k = n - k; // Calculate the value of // [n * (n - 1) *---* (n - k + 1)] / // [k * (k - 1) * ... * 1] for (int i = 0; i < k; ++i) { res *= (n - i); res /= (i + 1); } return res;} // Driver Codepublic static void Main(){ int N = 5, M = 1; int P = (N * (N - 1)) / 2; Console.Write(binomialCoeff(P, M));}} // This code is contributed// by Akanksha Rai <?php// PHP implementation of the approach // Function to return the value of// Binomial Coefficient C(n, k)function binomialCoeff($n, $k){ if ($k > $n) return 0; $res = 1; // Since C(n, k) = C(n, n-k) if ($k > $n - $k) $k = $n - $k; // Calculate the value of // [n * (n - 1) *---* (n - k + 1)] / // [k * (k - 1) * ... * 1] for ($i = 0; $i < $k; ++$i) { $res *= ($n - $i); $res /= ($i + 1); } return $res;} // Driver Code$N = 5;$M = 1; $P = floor(($N * ($N - 1)) / 2); echo binomialCoeff($P, $M); // This code is contributed by Ryuga?> <script> // Javascript implementation of the approach // Function to return the value of// Binomial Coefficient C(n, k)function binomialCoeff(n, k){ if (k > n) return 0; var res = 1; // Since C(n, k) = C(n, n-k) if (k > n - k) k = n - k; // Calculate the value of // [n * (n - 1) *---* (n - k + 1)] / [k * (k - 1) * ... * 1] for (var i = 0; i < k; ++i) { res *= (n - i); res /= (i + 1); } return res;} // Driver Codevar N = 5, M = 1;var P = (N * (N - 1)) / 2;document.write( binomialCoeff(P, M)); </script> 10 ankthon ukasp Akanksha_Rai Shivi_Aggarwal rutvik_56 Combinatorial Graph Mathematical Mathematical Graph Combinatorial Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Combinational Sum Count ways to reach the nth stair using step 1, 2 or 3 Count of subsets with sum equal to X Python program to get all subsets of given size of a set Print all possible strings of length k that can be formed from a set of n characters Dijkstra's shortest path algorithm | Greedy Algo-7 Kruskal’s Minimum Spanning Tree Algorithm | Greedy Algo-2 Prim’s Minimum Spanning Tree (MST) | Greedy Algo-5 Graph and its representations
[ { "code": null, "e": 25218, "s": 25190, "text": "\n25 May, 2021" }, { "code": null, "e": 25432, "s": 25218, "text": "Given two integers N and M, the task is to count the number of simple undirected graphs that can be drawn with N vertices and M edges. A simple graph is a graph that does not contain multiple edges and self-loops." }, { "code": null, "e": 25443, "s": 25432, "text": "Examples: " }, { "code": null, "e": 25520, "s": 25443, "text": "Input: N = 3, M = 1 Output: 3 The 3 graphs are {1-2, 3}, {2-3, 1}, {1-3, 2}." }, { "code": null, "e": 25552, "s": 25520, "text": "Input: N = 5, M = 1 Output: 10 " }, { "code": null, "e": 26035, "s": 25552, "text": "Approach: The N vertices are numbered from 1 to N. As there are no self-loops or multiple edges, the edge must be present between two different vertices. So the number of ways we can choose two different vertices is NC2 which is equal to (N * (N – 1)) / 2. Assume it P. Now M edges must be used with these pairs of vertices, so the number of ways to choose M pairs of vertices between P pairs will be PCM. If P < M then the answer will be 0 as the extra edges can not be left alone." }, { "code": null, "e": 26087, "s": 26035, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 26091, "s": 26087, "text": "C++" }, { "code": null, "e": 26096, "s": 26091, "text": "Java" }, { "code": null, "e": 26105, "s": 26096, "text": "Python 3" }, { "code": null, "e": 26108, "s": 26105, "text": "C#" }, { "code": null, "e": 26112, "s": 26108, "text": "PHP" }, { "code": null, "e": 26123, "s": 26112, "text": "Javascript" }, { "code": "// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Function to return the value of// Binomial Coefficient C(n, k)int binomialCoeff(int n, int k){ if (k > n) return 0; int res = 1; // Since C(n, k) = C(n, n-k) if (k > n - k) k = n - k; // Calculate the value of // [n * (n - 1) *---* (n - k + 1)] / [k * (k - 1) * ... * 1] for (int i = 0; i < k; ++i) { res *= (n - i); res /= (i + 1); } return res;} // Driver Codeint main(){ int N = 5, M = 1; int P = (N * (N - 1)) / 2; cout << binomialCoeff(P, M); return 0;}", "e": 26742, "s": 26123, "text": null }, { "code": "// Java implementation of the approachclass GFG{ // Function to return the value of // Binomial Coefficient C(n, k) static int binomialCoeff(int n, int k) { if (k > n) return 0; int res = 1; // Since C(n, k) = C(n, n-k) if (k > n - k) k = n - k; // Calculate the value of // [n * (n - 1) *---* (n - k + 1)] / // [k * (k - 1) * ... * 1] for (int i = 0; i < k; ++i) { res *= (n - i); res /= (i + 1); } return res; } // Driver Codepublic static void main(String[] args){ int N = 5, M = 1; int P = (N * (N - 1)) / 2; System.out.println(binomialCoeff(P, M));}} // This code is contributed by Shivi_Aggarwal", "e": 27495, "s": 26742, "text": null }, { "code": "# Python 3 implementation of the approach # Function to return the value of# Binomial Coefficient C(n, k)def binomialCoeff(n, k): if (k > n): return 0 res = 1 # Since C(n, k) = C(n, n-k) if (k > n - k): k = n - k # Calculate the value of # [n * (n - 1) *---* (n - k + 1)] / # [k * (k - 1) * ... * 1] for i in range( k): res *= (n - i) res //= (i + 1) return res # Driver Codeif __name__==\"__main__\": N = 5 M = 1 P = (N * (N - 1)) // 2 print(binomialCoeff(P, M)) # This code is contributed by ita_c", "e": 28072, "s": 27495, "text": null }, { "code": "// C# implementation of the approachusing System; class GFG{// Function to return the value of// Binomial Coefficient C(n, k)static int binomialCoeff(int n, int k){ if (k > n) return 0; int res = 1; // Since C(n, k) = C(n, n-k) if (k > n - k) k = n - k; // Calculate the value of // [n * (n - 1) *---* (n - k + 1)] / // [k * (k - 1) * ... * 1] for (int i = 0; i < k; ++i) { res *= (n - i); res /= (i + 1); } return res;} // Driver Codepublic static void Main(){ int N = 5, M = 1; int P = (N * (N - 1)) / 2; Console.Write(binomialCoeff(P, M));}} // This code is contributed// by Akanksha Rai", "e": 28740, "s": 28072, "text": null }, { "code": "<?php// PHP implementation of the approach // Function to return the value of// Binomial Coefficient C(n, k)function binomialCoeff($n, $k){ if ($k > $n) return 0; $res = 1; // Since C(n, k) = C(n, n-k) if ($k > $n - $k) $k = $n - $k; // Calculate the value of // [n * (n - 1) *---* (n - k + 1)] / // [k * (k - 1) * ... * 1] for ($i = 0; $i < $k; ++$i) { $res *= ($n - $i); $res /= ($i + 1); } return $res;} // Driver Code$N = 5;$M = 1; $P = floor(($N * ($N - 1)) / 2); echo binomialCoeff($P, $M); // This code is contributed by Ryuga?>", "e": 29341, "s": 28740, "text": null }, { "code": "<script> // Javascript implementation of the approach // Function to return the value of// Binomial Coefficient C(n, k)function binomialCoeff(n, k){ if (k > n) return 0; var res = 1; // Since C(n, k) = C(n, n-k) if (k > n - k) k = n - k; // Calculate the value of // [n * (n - 1) *---* (n - k + 1)] / [k * (k - 1) * ... * 1] for (var i = 0; i < k; ++i) { res *= (n - i); res /= (i + 1); } return res;} // Driver Codevar N = 5, M = 1;var P = (N * (N - 1)) / 2;document.write( binomialCoeff(P, M)); </script>", "e": 29908, "s": 29341, "text": null }, { "code": null, "e": 29911, "s": 29908, "text": "10" }, { "code": null, "e": 29921, "s": 29913, "text": "ankthon" }, { "code": null, "e": 29927, "s": 29921, "text": "ukasp" }, { "code": null, "e": 29940, "s": 29927, "text": "Akanksha_Rai" }, { "code": null, "e": 29955, "s": 29940, "text": "Shivi_Aggarwal" }, { "code": null, "e": 29965, "s": 29955, "text": "rutvik_56" }, { "code": null, "e": 29979, "s": 29965, "text": "Combinatorial" }, { "code": null, "e": 29985, "s": 29979, "text": "Graph" }, { "code": null, "e": 29998, "s": 29985, "text": "Mathematical" }, { "code": null, "e": 30011, "s": 29998, "text": "Mathematical" }, { "code": null, "e": 30017, "s": 30011, "text": "Graph" }, { "code": null, "e": 30031, "s": 30017, "text": "Combinatorial" }, { "code": null, "e": 30129, "s": 30031, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30147, "s": 30129, "text": "Combinational Sum" }, { "code": null, "e": 30202, "s": 30147, "text": "Count ways to reach the nth stair using step 1, 2 or 3" }, { "code": null, "e": 30239, "s": 30202, "text": "Count of subsets with sum equal to X" }, { "code": null, "e": 30296, "s": 30239, "text": "Python program to get all subsets of given size of a set" }, { "code": null, "e": 30381, "s": 30296, "text": "Print all possible strings of length k that can be formed from a set of n characters" }, { "code": null, "e": 30432, "s": 30381, "text": "Dijkstra's shortest path algorithm | Greedy Algo-7" }, { "code": null, "e": 30490, "s": 30432, "text": "Kruskal’s Minimum Spanning Tree Algorithm | Greedy Algo-2" }, { "code": null, "e": 30541, "s": 30490, "text": "Prim’s Minimum Spanning Tree (MST) | Greedy Algo-5" } ]
Longest subsequence-1 | Practice | GeeksforGeeks
Given an array A[] of size N, find the longest subsequence such that difference between adjacent elements is one. Example 1: Input: N = 7 A[] = {10, 9, 4, 5, 4, 8, 6} Output: 3 Explaination: The three possible subsequences {10, 9, 8} , {4, 5, 4} and {4, 5, 6}. Example 2: Input: N = 5 A[] = {1, 2, 3, 4, 5} Output: 5 Explaination: All the elements can be included in the subsequence. Your Task: You do not need to read input. Your task is to complete the function longestSubseq() which takes N and A[] as input parameters and returns the length of the longest such subsequence. Expected Time Complexity: O(N2) Expected Auxiliary Space: O(N) Constraints: 1 ≤ N ≤ 103 1 ≤ A[i] ≤ 103 0 somyadebsarkar3634 days ago whats wrong in this?? int ans=0; for(int j=i-1;j>=0;--j){ if(A[i]==A[j]+1 || A[i]==A[j]-1){ ans=max(ans,solve(j,A)+1); } return ans; } } int longestSubsequence(int N, int A[]) { int ans=0; for(int i=N-1;i>=1;--i){ ans=max(ans,solve(i,A)); } return ans; // code here } +1 himanshu0719cse192 weeks ago Number format exception at 3rd test casee?? 0 milindprajapatmst192 weeks ago class Solution{ public: unordered_map<int, int> M; int longestSubsequence(int n, int arr[]) { for (int i = 0; i < n; i++) { M[arr[i]] = max(M[arr[i]], 1); for (auto& itr : M) { if (abs(itr.first - arr[i]) == 1) M[arr[i]] = max(M[arr[i]], itr.second + 1); } } int result = 0; for (auto& itr : M) result = max(result, itr.second); return result; } }; 0 maheshahirwar2043 weeks ago Java Solution TC - O(N^2) SC - O(N) static int longestSubsequence(int N, int A[]) { int[]dp=new int[N]; int ans=1; for(int i=0;i<N;i++){ dp[i]=1; for(int j=0;j<i;j++){ if(Math.abs(A[i]-A[j])==1&&dp[i]<dp[j]+1){ dp[i]=dp[j]+1; } } ans=Math.max(dp[i],ans); } return ans; } 0 jainmuskan5653 weeks ago int ls1(int prev,int curr, int A[], int N, vector<vector<int>> &dp){ if(curr==N){ return 0; } if(dp[prev+1][curr]!= -1){ return dp[prev+1][curr]; } int len= 0+ ls1(prev,curr+1,A,N,dp); if(prev==-1 || abs(A[prev]-A[curr])==1){ len= max(len, 1+ls1(curr,curr+1,A,N,dp)); } return dp[prev+1][curr]= len; } int longestSubsequence(int N, int A[]) { vector<vector<int>> dp(N+1,vector<int>(N+1,-1)); return ls1(-1,0,A,N,dp); }}; 0 officialshivaji0071 month ago class Solution{ int ans = INT_MIN; void solve(int a[],int cur, int n,vector<int> &v){ int m = v.size(); if(cur == n){ ans = max(ans,m); return; } if(m==0 || abs(v[m-1] - a[cur])==1){ v.push_back(a[cur]); solve(a,cur+1,n,v); v.pop_back(); } solve(a,cur+1,n,v); }public: int longestSubsequence(int N, int A[]) { // code here vector<int> v; solve(A,0,N,v); return ans; }}; 0 khushiaggarwal09021 month ago int dp[1001][1001]; int solve(int n,int prev,int i,int a[]) { if(n==0||i==n) return 0; if(prev==-1) { return dp[i][prev]=1+solve(n,i,i+1,a); } if(dp[i][prev]!=-1) return dp[i][prev]; if(abs(a[i]-a[prev])==1) { return dp[i][prev]=max(1+solve(n,i,i+1,a),solve(n,prev,i+1,a)); } else { return dp[i][prev]=solve(n,prev,i+1,a); } } int longestSubsequence(int n, int a[]) { memset(dp,-1,sizeof(dp)); return solve(n,-1,0,a); } 0 harrypotter01 month ago class Solution: def longestSubsequence(self, n, a): dp = [1 for i in range(n+1)] for i in range(1,n+1): for j in range(0,i): if abs(a[i-1]-a[j-1])==1: dp[i] = max(dp[i], dp[j]+1) return max(dp) +1 aloksinghbais022 months ago C++ solution having time complexity as O(N*N) and space complexity as O(N) is as follows :- Execution Time :- 0.0 / 1.2 sec int longestSubsequence(int n, int a[]){ int dp[n]; for(int i = 0; i < n; i++) dp[i] = 1; for(int i = 1; i < n; i++){ for(int j = 0; j < i; j++){ if(abs(a[j]-a[i]) == 1){ dp[i] = max(dp[i],dp[j] + 1); } } } return *max_element(dp,dp+n); } 0 muskankushwah2 months ago Variant of Longest Increasing Subsequence int dp[n]; int ans=1; for(int i=0;i<n;i++){ dp[i]=1; for(int j=0;j<i;j++){ if(abs(A[i]-A[j])==1&&dp[i]<dp[j]+1) dp[i]=dp[j]+1; } ans=max(dp[i],ans); } return ans; 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": 352, "s": 238, "text": "Given an array A[] of size N, find the longest subsequence such that difference between adjacent elements is one." }, { "code": null, "e": 364, "s": 352, "text": "\nExample 1:" }, { "code": null, "e": 501, "s": 364, "text": "Input: N = 7\nA[] = {10, 9, 4, 5, 4, 8, 6}\nOutput: 3\nExplaination: The three possible subsequences \n{10, 9, 8} , {4, 5, 4} and {4, 5, 6}." }, { "code": null, "e": 513, "s": 501, "text": "\nExample 2:" }, { "code": null, "e": 626, "s": 513, "text": "Input: N = 5\nA[] = {1, 2, 3, 4, 5}\nOutput: 5\nExplaination: All the elements can be \nincluded in the subsequence." }, { "code": null, "e": 821, "s": 626, "text": "\nYour Task:\nYou do not need to read input. Your task is to complete the function longestSubseq() which takes N and A[] as input parameters and returns the length of the longest such subsequence." }, { "code": null, "e": 885, "s": 821, "text": "\nExpected Time Complexity: O(N2)\nExpected Auxiliary Space: O(N)" }, { "code": null, "e": 926, "s": 885, "text": "\nConstraints:\n1 ≤ N ≤ 103\n1 ≤ A[i] ≤ 103" }, { "code": null, "e": 928, "s": 926, "text": "0" }, { "code": null, "e": 956, "s": 928, "text": "somyadebsarkar3634 days ago" }, { "code": null, "e": 978, "s": 956, "text": "whats wrong in this??" }, { "code": null, "e": 1328, "s": 980, "text": "int ans=0; for(int j=i-1;j>=0;--j){ if(A[i]==A[j]+1 || A[i]==A[j]-1){ ans=max(ans,solve(j,A)+1); } return ans; } } int longestSubsequence(int N, int A[]) { int ans=0; for(int i=N-1;i>=1;--i){ ans=max(ans,solve(i,A)); } return ans; // code here }" }, { "code": null, "e": 1331, "s": 1328, "text": "+1" }, { "code": null, "e": 1360, "s": 1331, "text": "himanshu0719cse192 weeks ago" }, { "code": null, "e": 1404, "s": 1360, "text": "Number format exception at 3rd test casee??" }, { "code": null, "e": 1408, "s": 1406, "text": "0" }, { "code": null, "e": 1439, "s": 1408, "text": "milindprajapatmst192 weeks ago" }, { "code": null, "e": 1888, "s": 1439, "text": "class Solution{\n\tpublic:\n\tunordered_map<int, int> M;\n\tint longestSubsequence(int n, int arr[]) { \n\t for (int i = 0; i < n; i++) {\n\t M[arr[i]] = max(M[arr[i]], 1);\n\t for (auto& itr : M) {\n\t if (abs(itr.first - arr[i]) == 1) \n\t M[arr[i]] = max(M[arr[i]], itr.second + 1);\n\t }\n\t }\n\t int result = 0;\n\t for (auto& itr : M)\n\t result = max(result, itr.second);\n\t return result;\n\t} \n};" }, { "code": null, "e": 1890, "s": 1888, "text": "0" }, { "code": null, "e": 1918, "s": 1890, "text": "maheshahirwar2043 weeks ago" }, { "code": null, "e": 1955, "s": 1918, "text": "Java Solution TC - O(N^2) SC - O(N)" }, { "code": null, "e": 2301, "s": 1957, "text": " static int longestSubsequence(int N, int A[]) { int[]dp=new int[N]; int ans=1; for(int i=0;i<N;i++){ dp[i]=1; for(int j=0;j<i;j++){ if(Math.abs(A[i]-A[j])==1&&dp[i]<dp[j]+1){ dp[i]=dp[j]+1; } } ans=Math.max(dp[i],ans); } return ans; }" }, { "code": null, "e": 2303, "s": 2301, "text": "0" }, { "code": null, "e": 2328, "s": 2303, "text": "jainmuskan5653 weeks ago" }, { "code": null, "e": 2847, "s": 2328, "text": "int ls1(int prev,int curr, int A[], int N, vector<vector<int>> &dp){ if(curr==N){ return 0; } if(dp[prev+1][curr]!= -1){ return dp[prev+1][curr]; } int len= 0+ ls1(prev,curr+1,A,N,dp); if(prev==-1 || abs(A[prev]-A[curr])==1){ len= max(len, 1+ls1(curr,curr+1,A,N,dp)); } return dp[prev+1][curr]= len; } int longestSubsequence(int N, int A[]) { vector<vector<int>> dp(N+1,vector<int>(N+1,-1)); return ls1(-1,0,A,N,dp); }};" }, { "code": null, "e": 2849, "s": 2847, "text": "0" }, { "code": null, "e": 2879, "s": 2849, "text": "officialshivaji0071 month ago" }, { "code": null, "e": 3392, "s": 2879, "text": "class Solution{ int ans = INT_MIN; void solve(int a[],int cur, int n,vector<int> &v){ int m = v.size(); if(cur == n){ ans = max(ans,m); return; } if(m==0 || abs(v[m-1] - a[cur])==1){ v.push_back(a[cur]); solve(a,cur+1,n,v); v.pop_back(); } solve(a,cur+1,n,v); }public: int longestSubsequence(int N, int A[]) { // code here vector<int> v; solve(A,0,N,v); return ans; }};" }, { "code": null, "e": 3394, "s": 3392, "text": "0" }, { "code": null, "e": 3424, "s": 3394, "text": "khushiaggarwal09021 month ago" }, { "code": null, "e": 3930, "s": 3424, "text": "int dp[1001][1001]; int solve(int n,int prev,int i,int a[]) { if(n==0||i==n) return 0; if(prev==-1) { return dp[i][prev]=1+solve(n,i,i+1,a); } if(dp[i][prev]!=-1) return dp[i][prev]; if(abs(a[i]-a[prev])==1) { return dp[i][prev]=max(1+solve(n,i,i+1,a),solve(n,prev,i+1,a)); } else { return dp[i][prev]=solve(n,prev,i+1,a); } }" }, { "code": null, "e": 4063, "s": 3932, "text": " int longestSubsequence(int n, int a[]) { memset(dp,-1,sizeof(dp)); return solve(n,-1,0,a); }" }, { "code": null, "e": 4065, "s": 4063, "text": "0" }, { "code": null, "e": 4089, "s": 4065, "text": "harrypotter01 month ago" }, { "code": null, "e": 4353, "s": 4089, "text": "class Solution: def longestSubsequence(self, n, a): dp = [1 for i in range(n+1)] for i in range(1,n+1): for j in range(0,i): if abs(a[i-1]-a[j-1])==1: dp[i] = max(dp[i], dp[j]+1) return max(dp) " }, { "code": null, "e": 4356, "s": 4353, "text": "+1" }, { "code": null, "e": 4384, "s": 4356, "text": "aloksinghbais022 months ago" }, { "code": null, "e": 4477, "s": 4384, "text": "C++ solution having time complexity as O(N*N) and space complexity as O(N) is as follows :- " }, { "code": null, "e": 4511, "s": 4479, "text": "Execution Time :- 0.0 / 1.2 sec" }, { "code": null, "e": 4873, "s": 4513, "text": "int longestSubsequence(int n, int a[]){ int dp[n]; for(int i = 0; i < n; i++) dp[i] = 1; for(int i = 1; i < n; i++){ for(int j = 0; j < i; j++){ if(abs(a[j]-a[i]) == 1){ dp[i] = max(dp[i],dp[j] + 1); } } } return *max_element(dp,dp+n); }" }, { "code": null, "e": 4875, "s": 4873, "text": "0" }, { "code": null, "e": 4901, "s": 4875, "text": "muskankushwah2 months ago" }, { "code": null, "e": 4943, "s": 4901, "text": "Variant of Longest Increasing Subsequence" }, { "code": null, "e": 5199, "s": 4943, "text": "int dp[n]; int ans=1; for(int i=0;i<n;i++){ dp[i]=1; for(int j=0;j<i;j++){ if(abs(A[i]-A[j])==1&&dp[i]<dp[j]+1) dp[i]=dp[j]+1; } ans=max(dp[i],ans); } return ans;" }, { "code": null, "e": 5345, "s": 5199, "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": 5381, "s": 5345, "text": " Login to access your submissions. " }, { "code": null, "e": 5391, "s": 5381, "text": "\nProblem\n" }, { "code": null, "e": 5401, "s": 5391, "text": "\nContest\n" }, { "code": null, "e": 5464, "s": 5401, "text": "Reset the IDE using the second button on the top right corner." }, { "code": null, "e": 5612, "s": 5464, "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": 5820, "s": 5612, "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": 5926, "s": 5820, "text": "You can access the hints to get an idea about what is expected of you as well as the final solution code." } ]
Scikit Learn - Randomized Decision Trees
This chapter will help you in understanding randomized decision trees in Sklearn. As we know that a DT is usually trained by recursively splitting the data, but being prone to overfit, they have been transformed to random forests by training many trees over various subsamples of the data. The sklearn.ensemble module is having following two algorithms based on randomized decision trees − For each feature under consideration, it computes the locally optimal feature/split combination. In Random forest, each decision tree in the ensemble is built from a sample drawn with replacement from the training set and then gets the prediction from each of them and finally selects the best solution by means of voting. It can be used for both classification as well as regression tasks. For creating a random forest classifier, the Scikit-learn module provides sklearn.ensemble.RandomForestClassifier. While building random forest classifier, the main parameters this module uses are ‘max_features’ and ‘n_estimators’. Here, ‘max_features’ is the size of the random subsets of features to consider when splitting a node. If we choose this parameter’s value to none then it will consider all the features rather than a random subset. On the other hand, n_estimators are the number of trees in the forest. The higher the number of trees, the better the result will be. But it will take longer to compute also. In the following example, we are building a random forest classifier by using sklearn.ensemble.RandomForestClassifier and also checking its accuracy also by using cross_val_score module. from sklearn.model_selection import cross_val_score from sklearn.datasets import make_blobs from sklearn.ensemble import RandomForestClassifier X, y = make_blobs(n_samples = 10000, n_features = 10, centers = 100,random_state = 0) RFclf = RandomForestClassifier(n_estimators = 10,max_depth = None,min_samples_split = 2, random_state = 0) scores = cross_val_score(RFclf, X, y, cv = 5) scores.mean() 0.9997 We can also use the sklearn dataset to build Random Forest classifier. As in the following example we are using iris dataset. We will also find its accuracy score and confusion matrix. import numpy as np import pandas as pd from sklearn.model_selection import train_test_split from sklearn.ensemble import RandomForestClassifier from sklearn.metrics import classification_report, confusion_matrix, accuracy_score path = "https://archive.ics.uci.edu/ml/machine-learning-database s/iris/iris.data" headernames = ['sepal-length', 'sepal-width', 'petal-length', 'petal-width', 'Class'] dataset = pd.read_csv(path, names = headernames) X = dataset.iloc[:, :-1].values y = dataset.iloc[:, 4].values X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.30) RFclf = RandomForestClassifier(n_estimators = 50) RFclf.fit(X_train, y_train) y_pred = RFclf.predict(X_test) result = confusion_matrix(y_test, y_pred) print("Confusion Matrix:") print(result) result1 = classification_report(y_test, y_pred) print("Classification Report:",) print (result1) result2 = accuracy_score(y_test,y_pred) print("Accuracy:",result2) Confusion Matrix: [[14 0 0] [ 0 18 1] [ 0 0 12]] Classification Report: precision recall f1-score support Iris-setosa 1.00 1.00 1.00 14 Iris-versicolor 1.00 0.95 0.97 19 Iris-virginica 0.92 1.00 0.96 12 micro avg 0.98 0.98 0.98 45 macro avg 0.97 0.98 0.98 45 weighted avg 0.98 0.98 0.98 45 Accuracy: 0.9777777777777777 For creating a random forest regression, the Scikit-learn module provides sklearn.ensemble.RandomForestRegressor. While building random forest regressor, it will use the same parameters as used by sklearn.ensemble.RandomForestClassifier. In the following example, we are building a random forest regressor by using sklearn.ensemble.RandomForestregressor and also predicting for new values by using predict() method. from sklearn.ensemble import RandomForestRegressor from sklearn.datasets import make_regression X, y = make_regression(n_features = 10, n_informative = 2,random_state = 0, shuffle = False) RFregr = RandomForestRegressor(max_depth = 10,random_state = 0,n_estimators = 100) RFregr.fit(X, y) RandomForestRegressor( bootstrap = True, criterion = 'mse', max_depth = 10, max_features = 'auto', max_leaf_nodes = None, min_impurity_decrease = 0.0, min_impurity_split = None, min_samples_leaf = 1, min_samples_split = 2, min_weight_fraction_leaf = 0.0, n_estimators = 100, n_jobs = None, oob_score = False, random_state = 0, verbose = 0, warm_start = False ) Once fitted we can predict from regression model as follows − print(RFregr.predict([[0, 2, 3, 0, 1, 1, 1, 1, 2, 2]])) [98.47729198] For each feature under consideration, it selects a random value for the split. The benefit of using extra tree methods is that it allows to reduce the variance of the model a bit more. The disadvantage of using these methods is that it slightly increases the bias. For creating a classifier using Extra-tree method, the Scikit-learn module provides sklearn.ensemble.ExtraTreesClassifier. It uses the same parameters as used by sklearn.ensemble.RandomForestClassifier. The only difference is in the way, discussed above, they build trees. In the following example, we are building a random forest classifier by using sklearn.ensemble.ExtraTreeClassifier and also checking its accuracy by using cross_val_score module. from sklearn.model_selection import cross_val_score from sklearn.datasets import make_blobs from sklearn.ensemble import ExtraTreesClassifier X, y = make_blobs(n_samples = 10000, n_features = 10, centers=100,random_state = 0) ETclf = ExtraTreesClassifier(n_estimators = 10,max_depth = None,min_samples_split = 10, random_state = 0) scores = cross_val_score(ETclf, X, y, cv = 5) scores.mean() 1.0 We can also use the sklearn dataset to build classifier using Extra-Tree method. As in the following example we are using Pima-Indian dataset. from pandas import read_csv from sklearn.model_selection import KFold from sklearn.model_selection import cross_val_score from sklearn.ensemble import ExtraTreesClassifier path = r"C:\pima-indians-diabetes.csv" headernames = ['preg', 'plas', 'pres', 'skin', 'test', 'mass', 'pedi', 'age', 'class'] data = read_csv(path, names=headernames) array = data.values X = array[:,0:8] Y = array[:,8] seed = 7 kfold = KFold(n_splits=10, random_state=seed) num_trees = 150 max_features = 5 ETclf = ExtraTreesClassifier(n_estimators=num_trees, max_features=max_features) results = cross_val_score(ETclf, X, Y, cv=kfold) print(results.mean()) 0.7551435406698566 For creating a Extra-Tree regression, the Scikit-learn module provides sklearn.ensemble.ExtraTreesRegressor. While building random forest regressor, it will use the same parameters as used by sklearn.ensemble.ExtraTreesClassifier. In the following example, we are applying sklearn.ensemble.ExtraTreesregressor and on the same data as we used while creating random forest regressor. Let’s see the difference in the Output from sklearn.ensemble import ExtraTreesRegressor from sklearn.datasets import make_regression X, y = make_regression(n_features = 10, n_informative = 2,random_state = 0, shuffle = False) ETregr = ExtraTreesRegressor(max_depth = 10,random_state = 0,n_estimators = 100) ETregr.fit(X, y) ExtraTreesRegressor(bootstrap = False, criterion = 'mse', max_depth = 10, max_features = 'auto', max_leaf_nodes = None, min_impurity_decrease = 0.0, min_impurity_split = None, min_samples_leaf = 1, min_samples_split = 2, min_weight_fraction_leaf = 0.0, n_estimators = 100, n_jobs = None, oob_score = False, random_state = 0, verbose = 0, warm_start = False) Once fitted we can predict from regression model as follows − print(ETregr.predict([[0, 2, 3, 0, 1, 1, 1, 1, 2, 2]])) [85.50955817] 11 Lectures 2 hours PARTHA MAJUMDAR Print Add Notes Bookmark this page
[ { "code": null, "e": 2303, "s": 2221, "text": "This chapter will help you in understanding randomized decision trees in Sklearn." }, { "code": null, "e": 2611, "s": 2303, "text": "As we know that a DT is usually trained by recursively splitting the data, but being prone to overfit, they have been transformed to random forests by training many trees over various subsamples of the data. The sklearn.ensemble module is having following two algorithms based on randomized decision trees −" }, { "code": null, "e": 3002, "s": 2611, "text": "For each feature under consideration, it computes the locally optimal feature/split combination. In Random forest, each decision tree in the ensemble is built from a sample drawn with replacement from the training set and then gets the prediction from each of them and finally selects the best solution by means of voting. It can be used for both classification as well as regression tasks." }, { "code": null, "e": 3234, "s": 3002, "text": "For creating a random forest classifier, the Scikit-learn module provides sklearn.ensemble.RandomForestClassifier. While building random forest classifier, the main parameters this module uses are ‘max_features’ and ‘n_estimators’." }, { "code": null, "e": 3623, "s": 3234, "text": "Here, ‘max_features’ is the size of the random subsets of features to consider when splitting a node. If we choose this parameter’s value to none then it will consider all the features rather than a random subset. On the other hand, n_estimators are the number of trees in the forest. The higher the number of trees, the better the result will be. But it will take longer to compute also." }, { "code": null, "e": 3810, "s": 3623, "text": "In the following example, we are building a random forest classifier by using sklearn.ensemble.RandomForestClassifier and also checking its accuracy also by using cross_val_score module." }, { "code": null, "e": 4207, "s": 3810, "text": "from sklearn.model_selection import cross_val_score\nfrom sklearn.datasets import make_blobs\nfrom sklearn.ensemble import RandomForestClassifier\nX, y = make_blobs(n_samples = 10000, n_features = 10, centers = 100,random_state = 0) RFclf = RandomForestClassifier(n_estimators = 10,max_depth = None,min_samples_split = 2, random_state = 0)\nscores = cross_val_score(RFclf, X, y, cv = 5)\nscores.mean()" }, { "code": null, "e": 4215, "s": 4207, "text": "0.9997\n" }, { "code": null, "e": 4400, "s": 4215, "text": "We can also use the sklearn dataset to build Random Forest classifier. As in the following example we are using iris dataset. We will also find its accuracy score and confusion matrix." }, { "code": null, "e": 5339, "s": 4400, "text": "import numpy as np\nimport pandas as pd\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.ensemble import RandomForestClassifier\nfrom sklearn.metrics import classification_report, confusion_matrix, accuracy_score\n\npath = \"https://archive.ics.uci.edu/ml/machine-learning-database\ns/iris/iris.data\"\nheadernames = ['sepal-length', 'sepal-width', 'petal-length', 'petal-width', 'Class']\ndataset = pd.read_csv(path, names = headernames)\nX = dataset.iloc[:, :-1].values\ny = dataset.iloc[:, 4].values\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.30)\nRFclf = RandomForestClassifier(n_estimators = 50)\nRFclf.fit(X_train, y_train)\ny_pred = RFclf.predict(X_test)\nresult = confusion_matrix(y_test, y_pred)\nprint(\"Confusion Matrix:\")\nprint(result)\nresult1 = classification_report(y_test, y_pred)\nprint(\"Classification Report:\",)\nprint (result1)\nresult2 = accuracy_score(y_test,y_pred)\nprint(\"Accuracy:\",result2)" }, { "code": null, "e": 5783, "s": 5339, "text": "Confusion Matrix:\n[[14 0 0]\n[ 0 18 1]\n[ 0 0 12]]\nClassification Report:\n precision recall f1-score support\nIris-setosa 1.00 1.00 1.00 14\nIris-versicolor 1.00 0.95 0.97 19\nIris-virginica 0.92 1.00 0.96 12\n\nmicro avg 0.98 0.98 0.98 45\nmacro avg 0.97 0.98 0.98 45\nweighted avg 0.98 0.98 0.98 45\n\nAccuracy: 0.9777777777777777\n" }, { "code": null, "e": 6021, "s": 5783, "text": "For creating a random forest regression, the Scikit-learn module provides sklearn.ensemble.RandomForestRegressor. While building random forest regressor, it will use the same parameters as used by sklearn.ensemble.RandomForestClassifier." }, { "code": null, "e": 6199, "s": 6021, "text": "In the following example, we are building a random forest regressor by using sklearn.ensemble.RandomForestregressor and also predicting for new values by using predict() method." }, { "code": null, "e": 6488, "s": 6199, "text": "from sklearn.ensemble import RandomForestRegressor\nfrom sklearn.datasets import make_regression\nX, y = make_regression(n_features = 10, n_informative = 2,random_state = 0, shuffle = False)\nRFregr = RandomForestRegressor(max_depth = 10,random_state = 0,n_estimators = 100)\nRFregr.fit(X, y)" }, { "code": null, "e": 6868, "s": 6488, "text": "RandomForestRegressor(\n bootstrap = True, criterion = 'mse', max_depth = 10,\n max_features = 'auto', max_leaf_nodes = None,\n min_impurity_decrease = 0.0, min_impurity_split = None,\n min_samples_leaf = 1, min_samples_split = 2,\n min_weight_fraction_leaf = 0.0, n_estimators = 100, n_jobs = None,\n oob_score = False, random_state = 0, verbose = 0, warm_start = False\n)\n" }, { "code": null, "e": 6930, "s": 6868, "text": "Once fitted we can predict from regression model as follows −" }, { "code": null, "e": 6986, "s": 6930, "text": "print(RFregr.predict([[0, 2, 3, 0, 1, 1, 1, 1, 2, 2]]))" }, { "code": null, "e": 7001, "s": 6986, "text": "[98.47729198]\n" }, { "code": null, "e": 7266, "s": 7001, "text": "For each feature under consideration, it selects a random value for the split. The benefit of using extra tree methods is that it allows to reduce the variance of the model a bit more. The disadvantage of using these methods is that it slightly increases the bias." }, { "code": null, "e": 7539, "s": 7266, "text": "For creating a classifier using Extra-tree method, the Scikit-learn module provides sklearn.ensemble.ExtraTreesClassifier. It uses the same parameters as used by sklearn.ensemble.RandomForestClassifier. The only difference is in the way, discussed above, they build trees." }, { "code": null, "e": 7718, "s": 7539, "text": "In the following example, we are building a random forest classifier by using sklearn.ensemble.ExtraTreeClassifier and also checking its accuracy by using cross_val_score module." }, { "code": null, "e": 8110, "s": 7718, "text": "from sklearn.model_selection import cross_val_score\nfrom sklearn.datasets import make_blobs\nfrom sklearn.ensemble import ExtraTreesClassifier\nX, y = make_blobs(n_samples = 10000, n_features = 10, centers=100,random_state = 0)\nETclf = ExtraTreesClassifier(n_estimators = 10,max_depth = None,min_samples_split = 10, random_state = 0)\nscores = cross_val_score(ETclf, X, y, cv = 5)\nscores.mean()" }, { "code": null, "e": 8115, "s": 8110, "text": "1.0\n" }, { "code": null, "e": 8258, "s": 8115, "text": "We can also use the sklearn dataset to build classifier using Extra-Tree method. As in the following example we are using Pima-Indian dataset." }, { "code": null, "e": 8889, "s": 8258, "text": "from pandas import read_csv\n\nfrom sklearn.model_selection import KFold\nfrom sklearn.model_selection import cross_val_score\nfrom sklearn.ensemble import ExtraTreesClassifier\npath = r\"C:\\pima-indians-diabetes.csv\"\nheadernames = ['preg', 'plas', 'pres', 'skin', 'test', 'mass', 'pedi', 'age', 'class']\ndata = read_csv(path, names=headernames)\narray = data.values\nX = array[:,0:8]\nY = array[:,8]\nseed = 7\nkfold = KFold(n_splits=10, random_state=seed)\nnum_trees = 150\nmax_features = 5\nETclf = ExtraTreesClassifier(n_estimators=num_trees, max_features=max_features)\nresults = cross_val_score(ETclf, X, Y, cv=kfold)\nprint(results.mean())" }, { "code": null, "e": 8909, "s": 8889, "text": "0.7551435406698566\n" }, { "code": null, "e": 9140, "s": 8909, "text": "For creating a Extra-Tree regression, the Scikit-learn module provides sklearn.ensemble.ExtraTreesRegressor. While building random forest regressor, it will use the same parameters as used by sklearn.ensemble.ExtraTreesClassifier." }, { "code": null, "e": 9330, "s": 9140, "text": "In the following example, we are applying sklearn.ensemble.ExtraTreesregressor and on the same data as we used while creating random forest regressor. Let’s see the difference in the Output" }, { "code": null, "e": 9615, "s": 9330, "text": "from sklearn.ensemble import ExtraTreesRegressor\nfrom sklearn.datasets import make_regression\nX, y = make_regression(n_features = 10, n_informative = 2,random_state = 0, shuffle = False)\nETregr = ExtraTreesRegressor(max_depth = 10,random_state = 0,n_estimators = 100)\nETregr.fit(X, y)" }, { "code": null, "e": 9989, "s": 9615, "text": "ExtraTreesRegressor(bootstrap = False, criterion = 'mse', max_depth = 10,\n max_features = 'auto', max_leaf_nodes = None,\n min_impurity_decrease = 0.0, min_impurity_split = None,\n min_samples_leaf = 1, min_samples_split = 2,\n min_weight_fraction_leaf = 0.0, n_estimators = 100, n_jobs = None,\n oob_score = False, random_state = 0, verbose = 0, warm_start = False)\n" }, { "code": null, "e": 10051, "s": 9989, "text": "Once fitted we can predict from regression model as follows −" }, { "code": null, "e": 10107, "s": 10051, "text": "print(ETregr.predict([[0, 2, 3, 0, 1, 1, 1, 1, 2, 2]]))" }, { "code": null, "e": 10122, "s": 10107, "text": "[85.50955817]\n" }, { "code": null, "e": 10155, "s": 10122, "text": "\n 11 Lectures \n 2 hours \n" }, { "code": null, "e": 10172, "s": 10155, "text": " PARTHA MAJUMDAR" }, { "code": null, "e": 10179, "s": 10172, "text": " Print" }, { "code": null, "e": 10190, "s": 10179, "text": " Add Notes" } ]
Entity Framework - Inheritance
Inheritance makes it possible to create complex models that better reflect how developers think and also reduce the work required to interact with those models. Inheritance used with entities serves the same purpose as inheritance used with classes, so developers already know the basics of how this feature works. Let’s take a look at the following example and by creating a new console application project. Step 1 − Add ADO.NET Entity Data Model by right-clicking on project name and select Add → New Item... Step 2 − Add one entity and name it Person by following all the steps mentioned in the chapter Model First approach. Step 3 − Add some scalar properties as shown in the following image. Step 4 − We will add two more entities Student and Teacher, which will inherit the properties from Person Table. Step 5 − Now add Student entity and select Person from the Base type combobox as shown in the following image. Step 6 − Similarly add Teacher entity. Step 7 − Now add EnrollmentDate scalar property to student entity and HireDate property to Teacher entity. Step 8 − Let's go ahead and generate the database. Step 9 − Right click on the design surface and select Generate Database from Model... Step 10 − To create new Database click on New Connection...The following dialog will open. Click OK. Step 11 − Click Finish. This will add *.edmx.sql file in the project. You can execute DDL scripts in Visual Studio by opening .sql file. Now right-click and select Execute. Step 12 − Go to the server explorer you will see that the database is created with three tables which are specified. Step 13 − You can also see that the following domain classes are also generated automatically. public partial class Person { public int ID { get; set; } public string FirstMidName { get; set; } public string LastName { get; set; } } public partial class Student : Person { public System.DateTime EnrollmentDate { get; set; } } public partial class Teacher : Person { public System.DateTime HireDate { get; set; } } Following is the Context class. public partial class InheritanceModelContainer : DbContext { public InheritanceModelContainer() : base("name = InheritanceModelContainer") {} protected override void OnModelCreating(DbModelBuilder modelBuilder) { throw new UnintentionalCodeFirstException(); } public virtual DbSet<Person> People { get; set; } } Let’s add some Students and Teachers to the database and then retrieve it from the database. class Program { static void Main(string[] args) { using (var context = new InheritanceModelContainer()) { var student = new Student { FirstMidName = "Meredith", LastName = "Alonso", EnrollmentDate = DateTime.Parse(DateTime.Today.ToString()) }; context.People.Add(student); var student1 = new Student { FirstMidName = "Arturo", LastName = "Anand", EnrollmentDate = DateTime.Parse(DateTime.Today.ToString()) }; context.People.Add(student1); var techaer = new Teacher { FirstMidName = "Peggy", LastName = "Justice", HireDate = DateTime.Parse(DateTime.Today.ToString()) }; context.People.Add(techaer); var techaer1 = new Teacher { FirstMidName = "Yan", LastName = "Li", HireDate = DateTime.Parse(DateTime.Today.ToString()) }; context.People.Add(techaer1); context.SaveChanges(); } } } Students and teachers are added in the database. NTo retrieve students and teacher, the OfType method needs to be used, which will return Student and Teacher related to the specified department. Console.WriteLine("All students in database"); Console.WriteLine(""); foreach (var student in context.People.OfType<Student>()) { string name = student.FirstMidName + " " + student.LastName; Console.WriteLine("ID: {0}, Name: {1}, \tEnrollment Date {2} ", student.ID, name, student.EnrollmentDate.ToString()); } Console.WriteLine(""); Console.WriteLine("************************************************************ *****"); Console.WriteLine(""); Console.WriteLine("All teachers in database"); Console.WriteLine(""); foreach (var teacher in context.People.OfType<Teacher>()) { string name = teacher.FirstMidName + " " + teacher.LastName; Console.WriteLine("ID: {0}, Name: {1}, \tHireDate {2} ", teacher.ID, name, teacher.HireDate.ToString()); } Console.WriteLine(""); Console.WriteLine("************************************************************ *****"); Console.ReadKey(); In the first query, when you use OfType<Student>() then you will not be able to access HireDate because HireDate property is part of Teacher Entity and similarly EnrollmentDate property will not be accessible when you use OfType<Teacher>() When the above code is executed, you will receive the following output − All students in database ID: 1, Name: Meredith Alonso, Enrollment Date 10/30/2015 12:00:00 AM ID: 2, Name: Arturo Anand, Enrollment Date 10/30/2015 12:00:00 AM ***************************************************************** All teachers in database ID: 3, Name: Peggy Justice, HireDate 10/30/2015 12:00:00 AM ID: 4, Name: Yan Li, HireDate 10/30/2015 12:00:00 AM ***************************************************************** We recommend that you execute the above example in a step-by-step manner for better understanding. 19 Lectures 5 hours Trevoir Williams 33 Lectures 3.5 hours Nilay Mehta 21 Lectures 2.5 hours TELCOMA Global 89 Lectures 7.5 hours Mustafa Radaideh Print Add Notes Bookmark this page
[ { "code": null, "e": 3347, "s": 3032, "text": "Inheritance makes it possible to create complex models that better reflect how developers think and also reduce the work required to interact with those models. Inheritance used with entities serves the same purpose as inheritance used with classes, so developers already know the basics of how this feature works." }, { "code": null, "e": 3441, "s": 3347, "text": "Let’s take a look at the following example and by creating a new console application project." }, { "code": null, "e": 3543, "s": 3441, "text": "Step 1 − Add ADO.NET Entity Data Model by right-clicking on project name and select Add → New Item..." }, { "code": null, "e": 3660, "s": 3543, "text": "Step 2 − Add one entity and name it Person by following all the steps mentioned in the chapter Model First approach." }, { "code": null, "e": 3729, "s": 3660, "text": "Step 3 − Add some scalar properties as shown in the following image." }, { "code": null, "e": 3842, "s": 3729, "text": "Step 4 − We will add two more entities Student and Teacher, which will inherit the properties from Person Table." }, { "code": null, "e": 3953, "s": 3842, "text": "Step 5 − Now add Student entity and select Person from the Base type combobox as shown in the following image." }, { "code": null, "e": 3992, "s": 3953, "text": "Step 6 − Similarly add Teacher entity." }, { "code": null, "e": 4099, "s": 3992, "text": "Step 7 − Now add EnrollmentDate scalar property to student entity and HireDate property to Teacher entity." }, { "code": null, "e": 4150, "s": 4099, "text": "Step 8 − Let's go ahead and generate the database." }, { "code": null, "e": 4236, "s": 4150, "text": "Step 9 − Right click on the design surface and select Generate Database from Model..." }, { "code": null, "e": 4337, "s": 4236, "text": "Step 10 − To create new Database click on New Connection...The following dialog will open. Click OK." }, { "code": null, "e": 4510, "s": 4337, "text": "Step 11 − Click Finish. This will add *.edmx.sql file in the project. You can execute DDL scripts in Visual Studio by opening .sql file. Now right-click and select Execute." }, { "code": null, "e": 4627, "s": 4510, "text": "Step 12 − Go to the server explorer you will see that the database is created with three tables which are specified." }, { "code": null, "e": 4722, "s": 4627, "text": "Step 13 − You can also see that the following domain classes are also generated automatically." }, { "code": null, "e": 5059, "s": 4722, "text": "public partial class Person {\n public int ID { get; set; }\n public string FirstMidName { get; set; }\n public string LastName { get; set; }\n}\n\npublic partial class Student : Person {\n public System.DateTime EnrollmentDate { get; set; }\n}\n\npublic partial class Teacher : Person {\n public System.DateTime HireDate { get; set; }\n}" }, { "code": null, "e": 5091, "s": 5059, "text": "Following is the Context class." }, { "code": null, "e": 5431, "s": 5091, "text": "public partial class InheritanceModelContainer : DbContext {\n\n public InheritanceModelContainer() : \n base(\"name = InheritanceModelContainer\") {}\n\n protected override void OnModelCreating(DbModelBuilder modelBuilder) {\n throw new UnintentionalCodeFirstException();\n }\n\n public virtual DbSet<Person> People { get; set; }\n}" }, { "code": null, "e": 5524, "s": 5431, "text": "Let’s add some Students and Teachers to the database and then retrieve it from the database." }, { "code": null, "e": 6602, "s": 5524, "text": "class Program {\n\n static void Main(string[] args) {\n\n using (var context = new InheritanceModelContainer()) {\n\n var student = new Student {\n FirstMidName = \"Meredith\", \n LastName = \"Alonso\", \n EnrollmentDate = DateTime.Parse(DateTime.Today.ToString())\n };\n\n context.People.Add(student);\n\n var student1 = new Student {\n FirstMidName = \"Arturo\", \n LastName = \"Anand\", \n EnrollmentDate = DateTime.Parse(DateTime.Today.ToString())\n };\n\n context.People.Add(student1);\n\n var techaer = new Teacher {\n FirstMidName = \"Peggy\", \n LastName = \"Justice\", \n HireDate = DateTime.Parse(DateTime.Today.ToString())\n };\n\n context.People.Add(techaer);\n\n var techaer1 = new Teacher {\n FirstMidName = \"Yan\", \n LastName = \"Li\", \n HireDate = DateTime.Parse(DateTime.Today.ToString())\n };\n\n context.People.Add(techaer1);\n context.SaveChanges();\n }\n }\n}" }, { "code": null, "e": 6797, "s": 6602, "text": "Students and teachers are added in the database. NTo retrieve students and teacher, the OfType method needs to be used, which will return Student and Teacher related to the specified department." }, { "code": null, "e": 7704, "s": 6797, "text": "Console.WriteLine(\"All students in database\"); \nConsole.WriteLine(\"\");\n\nforeach (var student in context.People.OfType<Student>()) {\n string name = student.FirstMidName + \" \" + student.LastName;\n Console.WriteLine(\"ID: {0}, Name: {1}, \\tEnrollment Date {2} \", \n student.ID, name, student.EnrollmentDate.ToString());\n}\n\nConsole.WriteLine(\"\");\nConsole.WriteLine(\"************************************************************ *****\");\nConsole.WriteLine(\"\");\nConsole.WriteLine(\"All teachers in database\");\nConsole.WriteLine(\"\");\n\nforeach (var teacher in context.People.OfType<Teacher>()) {\n string name = teacher.FirstMidName + \" \" + teacher.LastName;\n Console.WriteLine(\"ID: {0}, Name: {1}, \\tHireDate {2} \", \n teacher.ID, name, teacher.HireDate.ToString()); \n}\n\nConsole.WriteLine(\"\");\nConsole.WriteLine(\"************************************************************ *****\");\nConsole.ReadKey();" }, { "code": null, "e": 7944, "s": 7704, "text": "In the first query, when you use OfType<Student>() then you will not be able to access HireDate because HireDate property is part of Teacher Entity and similarly EnrollmentDate property will not be accessible when you use OfType<Teacher>()" }, { "code": null, "e": 8017, "s": 7944, "text": "When the above code is executed, you will receive the following output −" }, { "code": null, "e": 8464, "s": 8017, "text": "All students in database\nID: 1, Name: Meredith Alonso, Enrollment Date 10/30/2015 12:00:00 AM\nID: 2, Name: Arturo Anand, Enrollment Date 10/30/2015 12:00:00 AM\n***************************************************************** \nAll teachers in database\nID: 3, Name: Peggy Justice, HireDate 10/30/2015 12:00:00 AM\nID: 4, Name: Yan Li, HireDate 10/30/2015 12:00:00 AM\n*****************************************************************\n" }, { "code": null, "e": 8563, "s": 8464, "text": "We recommend that you execute the above example in a step-by-step manner for better understanding." }, { "code": null, "e": 8596, "s": 8563, "text": "\n 19 Lectures \n 5 hours \n" }, { "code": null, "e": 8614, "s": 8596, "text": " Trevoir Williams" }, { "code": null, "e": 8649, "s": 8614, "text": "\n 33 Lectures \n 3.5 hours \n" }, { "code": null, "e": 8662, "s": 8649, "text": " Nilay Mehta" }, { "code": null, "e": 8697, "s": 8662, "text": "\n 21 Lectures \n 2.5 hours \n" }, { "code": null, "e": 8713, "s": 8697, "text": " TELCOMA Global" }, { "code": null, "e": 8748, "s": 8713, "text": "\n 89 Lectures \n 7.5 hours \n" }, { "code": null, "e": 8766, "s": 8748, "text": " Mustafa Radaideh" }, { "code": null, "e": 8773, "s": 8766, "text": " Print" }, { "code": null, "e": 8784, "s": 8773, "text": " Add Notes" } ]
How to find the less than probability using normal distribution in R?
The less than probability using normal distribution is the cumulative probability which can be found by using cumulative distribution function of the normal distribution. In R, we have pnorm function that directly calculates the less than probability for a normally distributed random variable that takes Z score, mean and standard deviation. Live Demo pnorm(0.95,1,0) pnorm(0.95,0,1) pnorm(0.10,0,1) pnorm(0.10,1,5) pnorm(0.10,1,50) pnorm(0.10,25,50) pnorm(0.12,25,50) pnorm(0.12,2,0.004) pnorm(0.12,2,0.5) pnorm(1,2,0.5) pnorm(12,20,3) pnorm(12,12,3) pnorm(12,15,3) pnorm(200,15,3) pnorm(200,201,3) pnorm(200,201,5) pnorm(20,25,5) [1] 0 [1] 0.8289439 [1] 0.5398278 [1] 0.4285763 [1] 0.4928194 [1] 0.309242 [1] 0.309383 [1] 0 [1] 8.495668e-05 [1] 0.02275013 [1] 0.003830381 [1] 0.5 [1] 0.1586553 [1] 1 [1] 0.3694413 [1] 0.4207403 [1] 0.1586553
[ { "code": null, "e": 1405, "s": 1062, "text": "The less than probability using normal distribution is the cumulative probability which can be found by using cumulative distribution function of the normal distribution. In R, we have pnorm function that directly calculates the less than probability for a normally distributed random variable that takes Z score, mean and standard deviation." }, { "code": null, "e": 1415, "s": 1405, "text": "Live Demo" }, { "code": null, "e": 1695, "s": 1415, "text": "pnorm(0.95,1,0)\npnorm(0.95,0,1)\npnorm(0.10,0,1)\npnorm(0.10,1,5)\npnorm(0.10,1,50)\npnorm(0.10,25,50)\npnorm(0.12,25,50)\npnorm(0.12,2,0.004)\npnorm(0.12,2,0.5)\npnorm(1,2,0.5)\npnorm(12,20,3)\npnorm(12,12,3)\npnorm(12,15,3)\npnorm(200,15,3)\npnorm(200,201,3)\npnorm(200,201,5)\npnorm(20,25,5)" }, { "code": null, "e": 1907, "s": 1695, "text": "[1] 0\n[1] 0.8289439\n[1] 0.5398278\n[1] 0.4285763\n[1] 0.4928194\n[1] 0.309242\n[1] 0.309383\n[1] 0\n[1] 8.495668e-05\n[1] 0.02275013\n[1] 0.003830381\n[1] 0.5\n[1] 0.1586553\n[1] 1\n[1] 0.3694413\n[1] 0.4207403\n[1] 0.1586553" } ]
The 5 Feature Selection Algorithms every Data Scientist should know | by Rahul Agarwal | Towards Data Science
Data Science is the study of algorithms. I grapple through with many algorithms on a day to day basis, so I thought of listing some of the most common and most used algorithms one will end up using in this new DS Algorithm series. How many times it has happened when you create a lot of features and then you need to come up with ways to reduce the number of features. We sometimes end up using correlation or tree-based methods to find out the important features. Can we add some structure to it? This post is about some of the most common feature selection techniques one can use while working with data. Before we proceed, we need to answer this question. Why don’t we give all the features to the ML algorithm and let it decide which feature is important? So there are three reasons why we don’t: If we have more columns in the data than the number of rows, we will be able to fit our training data perfectly, but that won’t generalize to the new samples. And thus we learn absolutely nothing. We want our models to be simple and explainable. We lose explainability when we have a lot of features. Most of the times, we will have many non-informative features. For Example, Name or ID variables. Poor-quality input will produce Poor-Quality output. Also, a large number of features make a model bulky, time-taking, and harder to implement in production. We select only useful features. Fortunately, Scikit-learn has made it pretty much easy for us to make the feature selection. There are a lot of ways in which we can think of feature selection, but most feature selection methods can be divided into three major buckets Filter based: We specify some metric and based on that filter features. An example of such a metric could be correlation/chi-square. Wrapper-based: Wrapper methods consider the selection of a set of features as a search problem. Example: Recursive Feature Elimination Embedded: Embedded methods use algorithms that have built-in feature selection methods. For instance, Lasso and RF have their own feature selection methods. So enough of theory let us start with our five feature selection methods. We will try to do this using a dataset to understand it better. I am going to be using a football player dataset to find out what makes a good player great? Don’t worry if you don’t understand football terminologies. I will try to keep it at a minimum. Here is the Kaggle Kernel with the code to try out yourself. We have done some basic preprocessing such as removing Nulls and one hot encoding. And converting the problem to a classification problem using: y = traindf['Overall']>=87 Here we use High Overall as a proxy for a great player. Our dataset(X) looks like below and has 223 columns. This is a filter-based method. We check the absolute value of the Pearson’s correlation between the target and numerical features in our dataset. We keep the top n features based on this criterion. This is another filter-based method. In this method, we calculate the chi-square metric between the target and the numerical variable and only select the variable with the maximum chi-squared values. Let us create a small example of how we calculate the chi-squared statistic for a sample. So let’s say we have 75 Right-Forwards in our dataset and 25 Non-Right-Forwards. We observe that 40 of the Right-Forwards are good, and 35 are not good. Does this signify that the player being right forward affects the overall performance? We calculate the chi-squared value: To do this, we first find out the values we would expect to be falling in each bucket if there was indeed independence between the two categorical variables. This is simple. We multiply the row sum and the column sum for each cell and divide it by total observations. so Good and NotRightforward Bucket Expected value= 25(Row Sum)*60(Column Sum)/100(Total Observations) Why is this expected? Since there are 25% notRightforwards in the data, we would expect 25% of the 60 good players we observed in that cell. Thus 15 players. Then we could just use the below formula to sum over all the 4 cells: I won’t show it here, but the chi-squared statistic also works in a hand-wavy way with non-negative numerical and categorical features. We can get chi-squared features from our dataset as: This is a wrapper based method. As I said before, wrapper methods consider the selection of a set of features as a search problem. From sklearn Documentation: The goal of recursive feature elimination (RFE) is to select features by recursively considering smaller and smaller sets of features. First, the estimator is trained on the initial set of features and the importance of each feature is obtained either through a coef_ attribute or through a feature_importances_ attribute. Then, the least important features are pruned from current set of features. That procedure is recursively repeated on the pruned set until the desired number of features to select is eventually reached. As you would have guessed, we could use any estimator with the method. In this case, we use LogisticRegression , and the RFE observes the coef_ attribute of the LogisticRegression object This is an Embedded method. As said before, Embedded methods use algorithms that have built-in feature selection methods. For example, Lasso and RF have their own feature selection methods. Lasso Regularizer forces a lot of feature weights to be zero. Here we use Lasso to select variables. This is an Embedded method. As said before, Embedded methods use algorithms that have built-in feature selection methods. We can also use RandomForest to select features based on feature importance. We calculate feature importance using node impurities in each decision tree. In Random forest, the final feature importance is the average of all decision tree feature importance. We could also have used a LightGBM. Or an XGBoost object as long it has a feature_importances_ attribute. Why use one, when we can have all? The answer is sometimes it won’t be possible with a lot of data and time crunch. But whenever possible, why not do this? We check if we get a feature based on all the methods. In this case, as we can see Reactions and LongPassing are excellent attributes to have in a high rated player. And as expected Ballcontrol and Finishing occupy the top spot too. Feature engineering and feature selection are critical parts of any machine learning pipeline. We strive for accuracy in our models, and one cannot get to a good accuracy without revisiting these pieces again and again. In this article, I tried to explain some of the most used feature selection techniques as well as my workflow when it comes to feature selection. I also tried to provide some intuition into these methods, but you should probably try to see more into it and try to incorporate these methods into your work. Do read my post on feature engineering too if you are interested. If you want to learn more about Data Science, I would like to call out this excellent course by Andrew Ng. This was the one that got me started. Do check it out. Thanks for the read. I am going to be writing more beginner-friendly posts in the future too. Follow me up at Medium or Subscribe to my blog to be informed about them. As always, I welcome feedback and constructive criticism and can be reached on Twitter @mlwhiz.
[ { "code": null, "e": 213, "s": 172, "text": "Data Science is the study of algorithms." }, { "code": null, "e": 403, "s": 213, "text": "I grapple through with many algorithms on a day to day basis, so I thought of listing some of the most common and most used algorithms one will end up using in this new DS Algorithm series." }, { "code": null, "e": 541, "s": 403, "text": "How many times it has happened when you create a lot of features and then you need to come up with ways to reduce the number of features." }, { "code": null, "e": 637, "s": 541, "text": "We sometimes end up using correlation or tree-based methods to find out the important features." }, { "code": null, "e": 670, "s": 637, "text": "Can we add some structure to it?" }, { "code": null, "e": 779, "s": 670, "text": "This post is about some of the most common feature selection techniques one can use while working with data." }, { "code": null, "e": 932, "s": 779, "text": "Before we proceed, we need to answer this question. Why don’t we give all the features to the ML algorithm and let it decide which feature is important?" }, { "code": null, "e": 973, "s": 932, "text": "So there are three reasons why we don’t:" }, { "code": null, "e": 1170, "s": 973, "text": "If we have more columns in the data than the number of rows, we will be able to fit our training data perfectly, but that won’t generalize to the new samples. And thus we learn absolutely nothing." }, { "code": null, "e": 1274, "s": 1170, "text": "We want our models to be simple and explainable. We lose explainability when we have a lot of features." }, { "code": null, "e": 1425, "s": 1274, "text": "Most of the times, we will have many non-informative features. For Example, Name or ID variables. Poor-quality input will produce Poor-Quality output." }, { "code": null, "e": 1530, "s": 1425, "text": "Also, a large number of features make a model bulky, time-taking, and harder to implement in production." }, { "code": null, "e": 1562, "s": 1530, "text": "We select only useful features." }, { "code": null, "e": 1798, "s": 1562, "text": "Fortunately, Scikit-learn has made it pretty much easy for us to make the feature selection. There are a lot of ways in which we can think of feature selection, but most feature selection methods can be divided into three major buckets" }, { "code": null, "e": 1931, "s": 1798, "text": "Filter based: We specify some metric and based on that filter features. An example of such a metric could be correlation/chi-square." }, { "code": null, "e": 2066, "s": 1931, "text": "Wrapper-based: Wrapper methods consider the selection of a set of features as a search problem. Example: Recursive Feature Elimination" }, { "code": null, "e": 2223, "s": 2066, "text": "Embedded: Embedded methods use algorithms that have built-in feature selection methods. For instance, Lasso and RF have their own feature selection methods." }, { "code": null, "e": 2297, "s": 2223, "text": "So enough of theory let us start with our five feature selection methods." }, { "code": null, "e": 2361, "s": 2297, "text": "We will try to do this using a dataset to understand it better." }, { "code": null, "e": 2454, "s": 2361, "text": "I am going to be using a football player dataset to find out what makes a good player great?" }, { "code": null, "e": 2550, "s": 2454, "text": "Don’t worry if you don’t understand football terminologies. I will try to keep it at a minimum." }, { "code": null, "e": 2611, "s": 2550, "text": "Here is the Kaggle Kernel with the code to try out yourself." }, { "code": null, "e": 2756, "s": 2611, "text": "We have done some basic preprocessing such as removing Nulls and one hot encoding. And converting the problem to a classification problem using:" }, { "code": null, "e": 2783, "s": 2756, "text": "y = traindf['Overall']>=87" }, { "code": null, "e": 2839, "s": 2783, "text": "Here we use High Overall as a proxy for a great player." }, { "code": null, "e": 2892, "s": 2839, "text": "Our dataset(X) looks like below and has 223 columns." }, { "code": null, "e": 2923, "s": 2892, "text": "This is a filter-based method." }, { "code": null, "e": 3090, "s": 2923, "text": "We check the absolute value of the Pearson’s correlation between the target and numerical features in our dataset. We keep the top n features based on this criterion." }, { "code": null, "e": 3127, "s": 3090, "text": "This is another filter-based method." }, { "code": null, "e": 3290, "s": 3127, "text": "In this method, we calculate the chi-square metric between the target and the numerical variable and only select the variable with the maximum chi-squared values." }, { "code": null, "e": 3380, "s": 3290, "text": "Let us create a small example of how we calculate the chi-squared statistic for a sample." }, { "code": null, "e": 3620, "s": 3380, "text": "So let’s say we have 75 Right-Forwards in our dataset and 25 Non-Right-Forwards. We observe that 40 of the Right-Forwards are good, and 35 are not good. Does this signify that the player being right forward affects the overall performance?" }, { "code": null, "e": 3656, "s": 3620, "text": "We calculate the chi-squared value:" }, { "code": null, "e": 3814, "s": 3656, "text": "To do this, we first find out the values we would expect to be falling in each bucket if there was indeed independence between the two categorical variables." }, { "code": null, "e": 3924, "s": 3814, "text": "This is simple. We multiply the row sum and the column sum for each cell and divide it by total observations." }, { "code": null, "e": 4026, "s": 3924, "text": "so Good and NotRightforward Bucket Expected value= 25(Row Sum)*60(Column Sum)/100(Total Observations)" }, { "code": null, "e": 4184, "s": 4026, "text": "Why is this expected? Since there are 25% notRightforwards in the data, we would expect 25% of the 60 good players we observed in that cell. Thus 15 players." }, { "code": null, "e": 4254, "s": 4184, "text": "Then we could just use the below formula to sum over all the 4 cells:" }, { "code": null, "e": 4390, "s": 4254, "text": "I won’t show it here, but the chi-squared statistic also works in a hand-wavy way with non-negative numerical and categorical features." }, { "code": null, "e": 4443, "s": 4390, "text": "We can get chi-squared features from our dataset as:" }, { "code": null, "e": 4574, "s": 4443, "text": "This is a wrapper based method. As I said before, wrapper methods consider the selection of a set of features as a search problem." }, { "code": null, "e": 4602, "s": 4574, "text": "From sklearn Documentation:" }, { "code": null, "e": 5128, "s": 4602, "text": "The goal of recursive feature elimination (RFE) is to select features by recursively considering smaller and smaller sets of features. First, the estimator is trained on the initial set of features and the importance of each feature is obtained either through a coef_ attribute or through a feature_importances_ attribute. Then, the least important features are pruned from current set of features. That procedure is recursively repeated on the pruned set until the desired number of features to select is eventually reached." }, { "code": null, "e": 5315, "s": 5128, "text": "As you would have guessed, we could use any estimator with the method. In this case, we use LogisticRegression , and the RFE observes the coef_ attribute of the LogisticRegression object" }, { "code": null, "e": 5437, "s": 5315, "text": "This is an Embedded method. As said before, Embedded methods use algorithms that have built-in feature selection methods." }, { "code": null, "e": 5567, "s": 5437, "text": "For example, Lasso and RF have their own feature selection methods. Lasso Regularizer forces a lot of feature weights to be zero." }, { "code": null, "e": 5606, "s": 5567, "text": "Here we use Lasso to select variables." }, { "code": null, "e": 5728, "s": 5606, "text": "This is an Embedded method. As said before, Embedded methods use algorithms that have built-in feature selection methods." }, { "code": null, "e": 5805, "s": 5728, "text": "We can also use RandomForest to select features based on feature importance." }, { "code": null, "e": 5985, "s": 5805, "text": "We calculate feature importance using node impurities in each decision tree. In Random forest, the final feature importance is the average of all decision tree feature importance." }, { "code": null, "e": 6091, "s": 5985, "text": "We could also have used a LightGBM. Or an XGBoost object as long it has a feature_importances_ attribute." }, { "code": null, "e": 6126, "s": 6091, "text": "Why use one, when we can have all?" }, { "code": null, "e": 6207, "s": 6126, "text": "The answer is sometimes it won’t be possible with a lot of data and time crunch." }, { "code": null, "e": 6247, "s": 6207, "text": "But whenever possible, why not do this?" }, { "code": null, "e": 6480, "s": 6247, "text": "We check if we get a feature based on all the methods. In this case, as we can see Reactions and LongPassing are excellent attributes to have in a high rated player. And as expected Ballcontrol and Finishing occupy the top spot too." }, { "code": null, "e": 6575, "s": 6480, "text": "Feature engineering and feature selection are critical parts of any machine learning pipeline." }, { "code": null, "e": 6700, "s": 6575, "text": "We strive for accuracy in our models, and one cannot get to a good accuracy without revisiting these pieces again and again." }, { "code": null, "e": 6846, "s": 6700, "text": "In this article, I tried to explain some of the most used feature selection techniques as well as my workflow when it comes to feature selection." }, { "code": null, "e": 7006, "s": 6846, "text": "I also tried to provide some intuition into these methods, but you should probably try to see more into it and try to incorporate these methods into your work." }, { "code": null, "e": 7072, "s": 7006, "text": "Do read my post on feature engineering too if you are interested." }, { "code": null, "e": 7234, "s": 7072, "text": "If you want to learn more about Data Science, I would like to call out this excellent course by Andrew Ng. This was the one that got me started. Do check it out." } ]
Sibling of a list element in JavaScript?
To find the sibling of a list element javascript has provided a method called node.nextSibling. If we know any member of a list we can find its sibling. Let's discuss it in a nutshell. node.nextSibling; In the following example, there are 3 list elements. Using the nextSibling property the sibling of the first element is found out and displayed the result in the output. Live Demo <html> <body> <ul><li id="item1">Tesla</li><li id="item2">Spacex</li><li id="item3">Solarcity</li></ul> <p id="next"></p> <script> var x = document.getElementById("item1").nextSibling.innerHTML; document.getElementById("next").innerHTML = "The sibling element is "+" "+x; </script> </body> </html> Tesla Spacex Solarcity The sibling element is Spacex In the following example, there are 3 list elements. Using the nextSibling property the sibling of the second element is found out and displayed the result in the output. The sibling element is nothing but the next element of the target element. Live Demo <html> <body> <ul><li id="item1">Tesla</li><li id="item2">Spacex</li><li id="item3">Solarcity</li></ul> <p id="next"></p> <script> var x = document.getElementById("item2").nextSibling.innerHTML; document.getElementById("next").innerHTML = "The sibling element is "+" "+x; </script> </body> </html> Tesla Spacex Solarcity The sibling element is Solarcity
[ { "code": null, "e": 1247, "s": 1062, "text": "To find the sibling of a list element javascript has provided a method called node.nextSibling. If we know any member of a list we can find its sibling. Let's discuss it in a nutshell." }, { "code": null, "e": 1265, "s": 1247, "text": "node.nextSibling;" }, { "code": null, "e": 1435, "s": 1265, "text": "In the following example, there are 3 list elements. Using the nextSibling property the sibling of the first element is found out and displayed the result in the output." }, { "code": null, "e": 1445, "s": 1435, "text": "Live Demo" }, { "code": null, "e": 1743, "s": 1445, "text": "<html>\n<body>\n<ul><li id=\"item1\">Tesla</li><li id=\"item2\">Spacex</li><li id=\"item3\">Solarcity</li></ul>\n<p id=\"next\"></p>\n<script>\nvar x = document.getElementById(\"item1\").nextSibling.innerHTML;\ndocument.getElementById(\"next\").innerHTML = \"The sibling element is \"+\" \"+x;\n</script>\n</body>\n</html>" }, { "code": null, "e": 1796, "s": 1743, "text": "Tesla\nSpacex\nSolarcity\nThe sibling element is Spacex" }, { "code": null, "e": 2042, "s": 1796, "text": "In the following example, there are 3 list elements. Using the nextSibling property the sibling of the second element is found out and displayed the result in the output. The sibling element is nothing but the next element of the target element." }, { "code": null, "e": 2052, "s": 2042, "text": "Live Demo" }, { "code": null, "e": 2350, "s": 2052, "text": "<html>\n<body>\n<ul><li id=\"item1\">Tesla</li><li id=\"item2\">Spacex</li><li id=\"item3\">Solarcity</li></ul>\n<p id=\"next\"></p>\n<script>\nvar x = document.getElementById(\"item2\").nextSibling.innerHTML;\ndocument.getElementById(\"next\").innerHTML = \"The sibling element is \"+\" \"+x;\n</script>\n</body>\n</html>" }, { "code": null, "e": 2406, "s": 2350, "text": "Tesla\nSpacex\nSolarcity\nThe sibling element is Solarcity" } ]
K'th Smallest/Largest Element in Unsorted Array | Set 1 - GeeksforGeeks
12 May, 2022 Given an array and a number k where k is smaller than the size of the array, we need to find the k’th smallest element in the given array. It is given that all array elements are distinct. Examples: Input: arr[] = {7, 10, 4, 3, 20, 15} k = 3 Output: 7 Input: arr[] = {7, 10, 4, 3, 20, 15} k = 4 Output: 10 We have discussed a similar problem to print k largest elements. Method 1 (Simple Solution) A simple solution is to sort the given array using an O(N log N) sorting algorithm like Merge Sort, Heap Sort, etc, and return the element at index k-1 in the sorted array. The Time Complexity of this solution is O(N log N) C++ Java Python3 C# PHP Javascript // Simple C++ program to find k'th smallest element#include <algorithm>#include <iostream>using namespace std; // Function to return k'th smallest element in a given arrayint kthSmallest(int arr[], int n, int k){ // Sort the given array sort(arr, arr + n); // Return k'th element in the sorted array return arr[k - 1];} // Driver program to test above methodsint main(){ int arr[] = { 12, 3, 5, 7, 19 }; int n = sizeof(arr) / sizeof(arr[0]), k = 2; cout << "K'th smallest element is " << kthSmallest(arr, n, k); return 0;} // Java code for kth smallest element// in an arrayimport java.util.Arrays;import java.util.Collections; class GFG { // Function to return k'th smallest // element in a given array public static int kthSmallest(Integer[] arr, int k) { // Sort the given array Arrays.sort(arr); // Return k'th element in // the sorted array return arr[k - 1]; } // driver program public static void main(String[] args) { Integer arr[] = new Integer[] { 12, 3, 5, 7, 19 }; int k = 2; System.out.print("K'th smallest element is " + kthSmallest(arr, k)); }} // This code is contributed by Chhavi # Python3 program to find k'th smallest# element # Function to return k'th smallest# element in a given arraydef kthSmallest(arr, n, k): # Sort the given array arr.sort() # Return k'th element in the # sorted array return arr[k-1] # Driver codeif __name__=='__main__': arr = [12, 3, 5, 7, 19] n = len(arr) k = 2 print("K'th smallest element is", kthSmallest(arr, n, k)) # This code is contributed by# Shrikant13 // C# code for kth smallest element// in an arrayusing System; class GFG { // Function to return k'th smallest // element in a given array public static int kthSmallest(int[] arr, int k) { // Sort the given array Array.Sort(arr); // Return k'th element in // the sorted array return arr[k - 1]; } // driver program public static void Main() { int[] arr = new int[] { 12, 3, 5, 7, 19 }; int k = 2; Console.Write("K'th smallest element" + " is " + kthSmallest(arr, k)); }} // This code is contributed by nitin mittal. <?php// Simple PHP program to find// k'th smallest element // Function to return k'th smallest// element in a given arrayfunction kthSmallest($arr, $n, $k){ // Sort the given array sort($arr); // Return k'th element // in the sorted array return $arr[$k - 1];} // Driver Code $arr = array(12, 3, 5, 7, 19); $n =count($arr); $k = 2; echo "K'th smallest element is ", kthSmallest($arr, $n, $k); // This code is contributed by anuj_67.?> <script> // Simple Javascript program to find k'th smallest element // Function to return k'th smallest element in a given arrayfunction kthSmallest(arr, n, k){ // Sort the given array arr.sort((a,b) => a-b); // Return k'th element in the sorted array return arr[k - 1];} // Driver program to test above methods let arr = [ 12, 3, 5, 7, 19 ]; let n = arr.length, k = 2; document.write("K'th smallest element is " + kthSmallest(arr, n, k)); //This code is contributed by Mayank Tyagi</script> K'th smallest element is 5 Method 2 (using set from C++ STL) we can find the kth smallest element in time complexity better than O(N log N). we know the Set in C++ STL is implemented using Binary Search Tree and we also know that the time complexity of all cases(searching, inserting, deleting ) in BST is log (n) in the average case and O(n) in the worst case. We are using set because it is mentioned in the question that all the elements in an array are distinct. The following is the C++ implementation of the above method. C++ /* the following code demonstrates how to find kth smallestelement using set from C++ STL */ #include <bits/stdc++.h>using namespace std; int main(){ int arr[] = { 12, 3, 5, 7, 19 }; int n = sizeof(arr) / sizeof(arr[0]); int k = 4; set<int> s(arr, arr + n); set<int>::iterator itr = s.begin(); // s.begin() returns a pointer to first // element in the set advance(itr, k - 1); // itr points to kth element in set cout << *itr << "\n"; return 0;} 12 Time Complexity: O( log N) in Average Case and O(N) in Worst CaseAuxiliary Space: O(N) Method 3 (Using Min Heap – HeapSelect) We can find k’th smallest element in time complexity better than O(N Log N). A simple optimization is to create a Min Heap of the given n elements and call extractMin() k times. The following is C++ implementation of above method. C++ Java Python3 C# // A C++ program to find k'th smallest element using min heap#include <climits>#include <iostream>using namespace std; // Prototype of a utility function to swap two integersvoid swap(int* x, int* y); // A class for Min Heapclass MinHeap { int* harr; // pointer to array of elements in heap int capacity; // maximum possible size of min heap int heap_size; // Current number of elements in min heappublic: MinHeap(int a[], int size); // Constructor void MinHeapify(int i); // To minheapify subtree rooted with index i int parent(int i) { return (i - 1) / 2; } int left(int i) { return (2 * i + 1); } int right(int i) { return (2 * i + 2); } int extractMin(); // extracts root (minimum) element int getMin() { return harr[0]; } // Returns minimum}; MinHeap::MinHeap(int a[], int size){ heap_size = size; harr = a; // store address of array int i = (heap_size - 1) / 2; while (i >= 0) { MinHeapify(i); i--; }} // Method to remove minimum element (or root) from min heapint MinHeap::extractMin(){ if (heap_size == 0) return INT_MAX; // Store the minimum value. int root = harr[0]; // If there are more than 1 items, move the last item to root // and call heapify. if (heap_size > 1) { harr[0] = harr[heap_size - 1]; MinHeapify(0); } heap_size--; return root;} // A recursive method to heapify a subtree with root at given index// This method assumes that the subtrees are already heapifiedvoid MinHeap::MinHeapify(int i){ int l = left(i); int r = right(i); int smallest = i; if (l < heap_size && harr[l] < harr[i]) smallest = l; if (r < heap_size && harr[r] < harr[smallest]) smallest = r; if (smallest != i) { swap(&harr[i], &harr[smallest]); MinHeapify(smallest); }} // A utility function to swap two elementsvoid swap(int* x, int* y){ int temp = *x; *x = *y; *y = temp;} // Function to return k'th smallest element in a given arrayint kthSmallest(int arr[], int n, int k){ // Build a heap of n elements: O(n) time MinHeap mh(arr, n); // Do extract min (k-1) times for (int i = 0; i < k - 1; i++) mh.extractMin(); // Return root return mh.getMin();} // Driver program to test above methodsint main(){ int arr[] = { 12, 3, 5, 7, 19 }; int n = sizeof(arr) / sizeof(arr[0]), k = 2; cout << "K'th smallest element is " << kthSmallest(arr, n, k); return 0;} // A Java program to find k'th smallest element using min heapimport java.util.*;class GFG{ // A class for Max Heap class MinHeap { int[] harr; // pointer to array of elements in heap int capacity; // maximum possible size of min heap int heap_size; // Current number of elements in min heap int parent(int i) { return (i - 1) / 2; } int left(int i) { return ((2 * i )+ 1); } int right(int i) { return ((2 * i) + 2); } int getMin() { return harr[0]; } // Returns minimum // to replace root with new node x and heapify() new root void replaceMax(int x) { this.harr[0] = x; minHeapify(0); } MinHeap(int a[], int size) { heap_size = size; harr = a; // store address of array int i = (heap_size - 1) / 2; while (i >= 0) { minHeapify(i); i--; } } // Method to remove maximum element (or root) from min heap int extractMin() { if (heap_size == 0) return Integer.MAX_VALUE; // Store the maximum value. int root = harr[0]; // If there are more than 1 items, move the last item to root // and call heapify. if (heap_size > 1) { harr[0] = harr[heap_size - 1]; minHeapify(0); } heap_size--; return root; } // A recursive method to heapify a subtree with root at given index // This method assumes that the subtrees are already heapified void minHeapify(int i) { int l = left(i); int r = right(i); int smallest = i; if (l < heap_size && harr[l] < harr[i]) smallest = l; if (r < heap_size && harr[r] < harr[smallest]) smallest = r; if (smallest != i) { int t = harr[i]; harr[i] = harr[smallest]; harr[smallest] = t; minHeapify(smallest); } } }; // Function to return k'th largest element in a given array int kthSmallest(int arr[], int n, int k) { // Build a heap of first k elements: O(k) time MinHeap mh = new MinHeap(arr, n); // Process remaining n-k elements. If current element is // smaller than root, replace root with current element for (int i = 0; i < k - 1; i++) mh.extractMin(); // Return root return mh.getMin(); } // Driver program to test above methods public static void main(String[] args) { int arr[] = { 12, 3, 5, 7, 19 }; int n = arr.length, k = 2; GFG gfg = new GFG(); System.out.print("K'th smallest element is " + gfg.kthSmallest(arr, n, k)); }} // This code is contributed by avanitrachhadiya2155 # Python3 program to find k'th smallest element# using min heap # Class for Min Heapclass MinHeap: # Constructor def __init__(self, a, size): # list of elements in the heap self.harr = a # maximum possible size of min heap self.capacity = None # current number of elements in min heap self.heap_size = size i = int((self.heap_size - 1) / 2) while i >= 0: self.minHeapify(i) i -= 1 def parent(self, i): return (i - 1) / 2 def left(self, i): return 2 * i + 1 def right(self, i): return 2 * i + 2 # Returns minimum def getMin(self): return self.harr[0] # Method to remove minimum element (or root) # from min heap def extractMin(self): if self.heap_size == 0: return float("inf") # Store the minimum value root = self.harr[0] # If there are more than 1 items, move the last item # to root and call heapify if self.heap_size > 1: self.harr[0] = self.harr[self.heap_size - 1] self.minHeapify(0) self.heap_size -= 1 return root # A recursive method to heapify a subtree with root at # given index. This method assumes that the subtrees # are already heapified def minHeapify(self, i): l = self.left(i) r = self.right(i) smallest = i if ((l < self.heap_size) and (self.harr[l] < self.harr[i])): smallest = l if ((r < self.heap_size) and (self.harr[r] < self.harr[smallest])): smallest = r if smallest != i: self.harr[i], self.harr[smallest] = ( self.harr[smallest], self.harr[i]) self.minHeapify(smallest) # Function to return k'th smallest element in a given arraydef kthSmallest(arr, n, k): # Build a heap of n elements in O(n) time mh = MinHeap(arr, n) # Do extract min (k-1) times for i in range(k - 1): mh.extractMin() # Return root return mh.getMin() # Driver codearr = [12, 3, 5, 7, 19]n = len(arr)k = 2print("K'th smallest element is", kthSmallest(arr, n, k)) # This Code is contributed by Kevin Joshi using System;public class GFG{ public class MinHeap { int[] harr; // pointer to array of elements in heap // int capacity; // maximum possible size of min heap int heap_size; // Current number of elements in min heap int parent(int i) { return (i - 1) / 2; } int left(int i) { return ((2 * i )+ 1); } int right(int i) { return ((2 * i) + 2); } public int getMin() { return harr[0]; } // Returns minimum // to replace root with new node x and heapify() new root public void replaceMax(int x) { this.harr[0] = x; minHeapify(0); } public MinHeap(int[] a, int size) { heap_size = size; harr = a; // store address of array int i = (heap_size - 1) / 2; while (i >= 0) { minHeapify(i); i--; } } // Method to remove maximum element (or root) from min heap public int extractMin() { if (heap_size == 0) return Int32.MaxValue; // Store the maximum value. int root = harr[0]; // If there are more than 1 items, move the last item to root // and call heapify. if (heap_size > 1) { harr[0] = harr[heap_size - 1]; minHeapify(0); } heap_size--; return root; } // A recursive method to heapify a subtree with root at given index // This method assumes that the subtrees are already heapified public void minHeapify(int i) { int l = left(i); int r = right(i); int smallest = i; if (l < heap_size && harr[l] < harr[i]) smallest = l; if (r < heap_size && harr[r] < harr[smallest]) smallest = r; if (smallest != i) { int t = harr[i]; harr[i] = harr[smallest]; harr[smallest] = t; minHeapify(smallest); } } }; // Function to return k'th largest element in a given array int kthSmallest(int[] arr, int n, int k) { // Build a heap of first k elements: O(k) time MinHeap mh = new MinHeap(arr, n); // Process remaining n-k elements. If current element is // smaller than root, replace root with current element for (int i = 0; i < k - 1; i++) mh.extractMin(); // Return root return mh.getMin(); } // Driver program to test above methods static public void Main (){ int[] arr = { 12, 3, 5, 7, 19 }; int n = arr.Length, k = 2; GFG gfg = new GFG(); Console.Write("K'th smallest element is " + gfg.kthSmallest(arr, n, k)); }} // This code is contributed by rag2127 K'th smallest element is 5 Time complexity of this solution is O(n + kLogn). Method 4 (Using Max-Heap) We can also use Max Heap for finding the k’th smallest element. Following is an algorithm. 1) Build a Max-Heap MH of the first k elements (arr[0] to arr[k-1]) of the given array. O(k)2) For each element, after the k’th element (arr[k] to arr[n-1]), compare it with root of MH. ......a) If the element is less than the root then make it root and call heapify for MH ......b) Else ignore it. // The step 2 is O((n-k)*logk)3) Finally, the root of the MH is the kth smallest element.Time complexity of this solution is O(k + (n-k)*Logk) The following is C++ implementation of the above algorithm C++ Java Python3 C# // A C++ program to find k'th smallest element using max heap#include <climits>#include <iostream>using namespace std; // Prototype of a utility function to swap two integersvoid swap(int* x, int* y); // A class for Max Heapclass MaxHeap { int* harr; // pointer to array of elements in heap int capacity; // maximum possible size of max heap int heap_size; // Current number of elements in max heappublic: MaxHeap(int a[], int size); // Constructor void maxHeapify(int i); // To maxHeapify subtree rooted with index i int parent(int i) { return (i - 1) / 2; } int left(int i) { return (2 * i + 1); } int right(int i) { return (2 * i + 2); } int extractMax(); // extracts root (maximum) element int getMax() { return harr[0]; } // Returns maximum // to replace root with new node x and heapify() new root void replaceMax(int x) { harr[0] = x; maxHeapify(0); }}; MaxHeap::MaxHeap(int a[], int size){ heap_size = size; harr = a; // store address of array int i = (heap_size - 1) / 2; while (i >= 0) { maxHeapify(i); i--; }} // Method to remove maximum element (or root) from max heapint MaxHeap::extractMax(){ if (heap_size == 0) return INT_MAX; // Store the maximum value. int root = harr[0]; // If there are more than 1 items, move the last item to root // and call heapify. if (heap_size > 1) { harr[0] = harr[heap_size - 1]; maxHeapify(0); } heap_size--; return root;} // A recursive method to heapify a subtree with root at given index// This method assumes that the subtrees are already heapifiedvoid MaxHeap::maxHeapify(int i){ int l = left(i); int r = right(i); int largest = i; if (l < heap_size && harr[l] > harr[i]) largest = l; if (r < heap_size && harr[r] > harr[largest]) largest = r; if (largest != i) { swap(&harr[i], &harr[largest]); maxHeapify(largest); }} // A utility function to swap two elementsvoid swap(int* x, int* y){ int temp = *x; *x = *y; *y = temp;} // Function to return k'th largest element in a given arrayint kthSmallest(int arr[], int n, int k){ // Build a heap of first k elements: O(k) time MaxHeap mh(arr, k); // Process remaining n-k elements. If current element is // smaller than root, replace root with current element for (int i = k; i < n; i++) if (arr[i] < mh.getMax()) mh.replaceMax(arr[i]); // Return root return mh.getMax();} // Driver program to test above methodsint main(){ int arr[] = { 12, 3, 5, 7, 19 }; int n = sizeof(arr) / sizeof(arr[0]), k = 4; cout << "K'th smallest element is " << kthSmallest(arr, n, k); return 0;} // A Java program to find k'th smallest element using max heapimport java.util.*;class GFG{ // A class for Max Heap class MaxHeap { int[] harr; // pointer to array of elements in heap int capacity; // maximum possible size of max heap int heap_size; // Current number of elements in max heap int parent(int i) { return (i - 1) / 2; } int left(int i) { return (2 * i + 1); } int right(int i) { return (2 * i + 2); } int getMax() { return harr[0]; } // Returns maximum // to replace root with new node x and heapify() new root void replaceMax(int x) { this.harr[0] = x; maxHeapify(0); } MaxHeap(int a[], int size) { heap_size = size; harr = a; // store address of array int i = (heap_size - 1) / 2; while (i >= 0) { maxHeapify(i); i--; } } // Method to remove maximum element (or root) from max heap int extractMax() { if (heap_size == 0) return Integer.MAX_VALUE; // Store the maximum value. int root = harr[0]; // If there are more than 1 items, move the last item to root // and call heapify. if (heap_size > 1) { harr[0] = harr[heap_size - 1]; maxHeapify(0); } heap_size--; return root; } // A recursive method to heapify a subtree with root at given index // This method assumes that the subtrees are already heapified void maxHeapify(int i) { int l = left(i); int r = right(i); int largest = i; if (l < heap_size && harr[l] > harr[i]) largest = l; if (r < heap_size && harr[r] > harr[largest]) largest = r; if (largest != i) { int t = harr[i]; harr[i] = harr[largest]; harr[largest] = t; maxHeapify(largest); } } }; // Function to return k'th largest element in a given array int kthSmallest(int arr[], int n, int k) { // Build a heap of first k elements: O(k) time MaxHeap mh = new MaxHeap(arr, k); // Process remaining n-k elements. If current element is // smaller than root, replace root with current element for (int i = k; i < n; i++) if (arr[i] < mh.getMax()) mh.replaceMax(arr[i]); // Return root return mh.getMax(); } // Driver program to test above methods public static void main(String[] args) { int arr[] = { 12, 3, 5, 7, 19 }; int n = arr.length, k = 4; GFG gfg = new GFG(); System.out.print("K'th smallest element is " + gfg.kthSmallest(arr, n, k)); }} // This code is contributed by Rajput-Ji # Python3 program to find k'th smallest element# using max heap # Class for Max Heapclass MaxHeap: # Constructor def __init__(self, a, size): # list of elements in the heap self.harr = a # maximum possible size of max heap self.capacity = None # current number of elements in max heap self.heap_size = size i = int((self.heap_size - 1) / 2) while i >= 0: self.maxHeapify(i) i -= 1 def parent(self, i): return (i - 1) / 2 def left(self, i): return 2 * i + 1 def right(self, i): return 2 * i + 2 # Returns maximum def getMax(self): return self.harr[0] # to replace root with new node x and heapify() new root def replaceMax(self, x): self.harr[0] = x self.maxHeapify(0) # Method to remove maximum element (or root) # from max heap def extractMin(self): if self.heap_size == 0: return float("inf") # Store the maximum value. root = self.harr[0] # If there are more than 1 items, move the # last item to root and call heapify if self.heap_size > 1: self.harr[0] = self.harr[self.heap_size - 1] self.maxHeapify(0) self.heap_size -= 1 return root # A recursive method to heapify a subtree with root at # given index. This method assumes that the subtrees # are already heapified def maxHeapify(self, i): l = self.left(i) r = self.right(i) largest = i if ((l < self.heap_size) and (self.harr[l] > self.harr[i])): largest = l if ((r < self.heap_size) and (self.harr[r] > self.harr[largest])): largest = r if largest != i: self.harr[i], self.harr[largest] = ( self.harr[largest], self.harr[i]) self.maxHeapify(largest) # Function to return k'th smallest element in a given arraydef kthSmallest(arr, n, k): # Build a heap of first k elements in O(k) time mh = MaxHeap(arr, k) # Process remaining n-k elements. If current element is # smaller than root, replace root with current element for i in range(k, n): if arr[i] < mh.getMax(): mh.replaceMax(arr[i]) # Return root return mh.getMax() # Driver codearr = [12, 3, 5, 7, 19]n = len(arr)k = 4print("K'th smallest element is", kthSmallest(arr, n, k)) # Code contributed by Kevin Joshi // A C# program to find k'th smallest element using max heapusing System; public class GFG { // A class for Max Heap public class MaxHeap { public int[] harr; // pointer to array of elements in // heap public int capacity; // maximum possible size of max // heap public int heap_size; // Current number of elements in // max heap public int parent(int i) { return (i - 1) / 2; } public int left(int i) { return (2 * i + 1); } public int right(int i) { return (2 * i + 2); } public int getMax() { return harr[0]; } // Returns maximum // to replace root with new node x and heapify() new // root public void replaceMax(int x) { this.harr[0] = x; maxHeapify(0); } public MaxHeap(int[] a, int size) { heap_size = size; harr = a; // store address of array int i = (heap_size - 1) / 2; while (i >= 0) { maxHeapify(i); i--; } } // Method to remove maximum element (or root) from // max heap public int extractMax() { if (heap_size == 0) return int.MaxValue; // Store the maximum value. int root = harr[0]; // If there are more than 1 items, move the last // item to root and call heapify. if (heap_size > 1) { harr[0] = harr[heap_size - 1]; maxHeapify(0); } heap_size--; return root; } // A recursive method to heapify a subtree with root // at given index This method assumes that the // subtrees are already heapified public void maxHeapify(int i) { int l = left(i); int r = right(i); int largest = i; if (l < heap_size && harr[l] > harr[i]) largest = l; if (r < heap_size && harr[r] > harr[largest]) largest = r; if (largest != i) { int t = harr[i]; harr[i] = harr[largest]; harr[largest] = t; maxHeapify(largest); } } }; // Function to return k'th largest element in a given // array int kthSmallest(int[] arr, int n, int k) { // Build a heap of first k elements: O(k) time MaxHeap mh = new MaxHeap(arr, k); // Process remaining n-k elements. If current // element is smaller than root, replace root with // current element for (int i = k; i < n; i++) if (arr[i] < mh.getMax()) mh.replaceMax(arr[i]); // Return root return mh.getMax(); } // Driver code public static void Main(String[] args) { int[] arr = { 12, 3, 5, 7, 19 }; int n = arr.Length, k = 4; GFG gfg = new GFG(); Console.Write("K'th smallest element is " + gfg.kthSmallest(arr, n, k)); }} // This code is contributed by gauravrajput1 K'th smallest element is 12 Method 5 (QuickSelect) This is an optimization over method 1 if QuickSort is used as a sorting algorithm in first step. In QuickSort, we pick a pivot element, then move the pivot element to its correct position and partition the surrounding array. The idea is, not to do complete quicksort, but stop at the point where pivot itself is k’th smallest element. Also, not to recur for both left and right sides of pivot, but recur for one of them according to the position of pivot. The worst case time complexity of this method is O(n2), but it works in O(n) on average. C++ Java Python3 C# Javascript #include <climits>#include <iostream>using namespace std; int partition(int arr[], int l, int r); // This function returns k'th smallest element in arr[l..r] using// QuickSort based method. ASSUMPTION: ALL ELEMENTS IN ARR[] ARE DISTINCTint kthSmallest(int arr[], int l, int r, int k){ // If k is smaller than number of elements in array if (k > 0 && k <= r - l + 1) { // Partition the array around last element and get // position of pivot element in sorted array int pos = partition(arr, l, r); // If position is same as k if (pos - l == k - 1) return arr[pos]; if (pos - l > k - 1) // If position is more, recur for left subarray return kthSmallest(arr, l, pos - 1, k); // Else recur for right subarray return kthSmallest(arr, pos + 1, r, k - pos + l - 1); } // If k is more than number of elements in array return INT_MAX;} void swap(int* a, int* b){ int temp = *a; *a = *b; *b = temp;} // Standard partition process of QuickSort(). It considers the last// element as pivot and moves all smaller element to left of it// and greater elements to rightint partition(int arr[], int l, int r){ int x = arr[r], i = l; for (int j = l; j <= r - 1; j++) { if (arr[j] <= x) { swap(&arr[i], &arr[j]); i++; } } swap(&arr[i], &arr[r]); return i;} // Driver program to test above methodsint main(){ int arr[] = { 12, 3, 5, 7, 4, 19, 26 }; int n = sizeof(arr) / sizeof(arr[0]), k = 3; cout << "K'th smallest element is " << kthSmallest(arr, 0, n - 1, k); return 0;} // Java code for kth smallest element in an arrayimport java.util.Arrays;import java.util.Collections; class GFG { // Standard partition process of QuickSort. // It considers the last element as pivot // and moves all smaller element to left of // it and greater elements to right public static int partition(Integer[] arr, int l, int r) { int x = arr[r], i = l; for (int j = l; j <= r - 1; j++) { if (arr[j] <= x) { // Swapping arr[i] and arr[j] int temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; i++; } } // Swapping arr[i] and arr[r] int temp = arr[i]; arr[i] = arr[r]; arr[r] = temp; return i; } // This function returns k'th smallest element // in arr[l..r] using QuickSort based method. // ASSUMPTION: ALL ELEMENTS IN ARR[] ARE DISTINCT public static int kthSmallest(Integer[] arr, int l, int r, int k) { // If k is smaller than number of elements // in array if (k > 0 && k <= r - l + 1) { // Partition the array around last // element and get position of pivot // element in sorted array int pos = partition(arr, l, r); // If position is same as k if (pos - l == k - 1) return arr[pos]; // If position is more, recur for // left subarray if (pos - l > k - 1) return kthSmallest(arr, l, pos - 1, k); // Else recur for right subarray return kthSmallest(arr, pos + 1, r, k - pos + l - 1); } // If k is more than number of elements // in array return Integer.MAX_VALUE; } // Driver program to test above methods public static void main(String[] args) { Integer arr[] = new Integer[] { 12, 3, 5, 7, 4, 19, 26 }; int k = 3; System.out.print("K'th smallest element is " + kthSmallest(arr, 0, arr.length - 1, k)); }} // This code is contributed by Chhavi # This function returns k'th smallest element# in arr[l..r] using QuickSort based method.# ASSUMPTION: ALL ELEMENTS IN ARR[] ARE DISTINCTimport sys def kthSmallest(arr, l, r, k): # If k is smaller than number of # elements in array if (k > 0 and k <= r - l + 1): # Partition the array around last # element and get position of pivot # element in sorted array pos = partition(arr, l, r) # If position is same as k if (pos - l == k - 1): return arr[pos] if (pos - l > k - 1): # If position is more, # recur for left subarray return kthSmallest(arr, l, pos - 1, k) # Else recur for right subarray return kthSmallest(arr, pos + 1, r, k - pos + l - 1) # If k is more than number of # elements in array return sys.maxsize # Standard partition process of QuickSort().# It considers the last element as pivot and# moves all smaller element to left of it# and greater elements to rightdef partition(arr, l, r): x = arr[r] i = l for j in range(l, r): if (arr[j] <= x): arr[i], arr[j] = arr[j], arr[i] i += 1 arr[i], arr[r] = arr[r], arr[i] return i # Driver Codeif __name__ == "__main__": arr = [12, 3, 5, 7, 4, 19, 26] n = len(arr) k = 3; print("K'th smallest element is", kthSmallest(arr, 0, n - 1, k)) # This code is contributed by ita_c // C# code for kth smallest element// in an arrayusing System; class GFG { // Standard partition process of QuickSort. // It considers the last element as pivot // and moves all smaller element to left of // it and greater elements to right public static int partition(int[] arr, int l, int r) { int x = arr[r], i = l; int temp = 0; for (int j = l; j <= r - 1; j++) { if (arr[j] <= x) { // Swapping arr[i] and arr[j] temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; i++; } } // Swapping arr[i] and arr[r] temp = arr[i]; arr[i] = arr[r]; arr[r] = temp; return i; } // This function returns k'th smallest // element in arr[l..r] using QuickSort // based method. ASSUMPTION: ALL ELEMENTS // IN ARR[] ARE DISTINCT public static int kthSmallest(int[] arr, int l, int r, int k) { // If k is smaller than number // of elements in array if (k > 0 && k <= r - l + 1) { // Partition the array around last // element and get position of pivot // element in sorted array int pos = partition(arr, l, r); // If position is same as k if (pos - l == k - 1) return arr[pos]; // If position is more, recur for // left subarray if (pos - l > k - 1) return kthSmallest(arr, l, pos - 1, k); // Else recur for right subarray return kthSmallest(arr, pos + 1, r, k - pos + l - 1); } // If k is more than number // of elements in array return int.MaxValue; } // Driver Code public static void Main() { int[] arr = { 12, 3, 5, 7, 4, 19, 26 }; int k = 3; Console.Write("K'th smallest element is " + kthSmallest(arr, 0, arr.Length - 1, k)); }} // This code is contributed// by 29AjayKumar <script> // JavaScript code for kth smallest// element in an array // Standard partition process of QuickSort. // It considers the last element as pivot // and moves all smaller element to left of // it and greater elements to right function partition( arr , l , r) { var x = arr[r], i = l; for (j = l; j <= r - 1; j++) { if (arr[j] <= x) { // Swapping arr[i] and arr[j] var temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; i++; } } // Swapping arr[i] and arr[r] var temp = arr[i]; arr[i] = arr[r]; arr[r] = temp; return i; } // This function returns k'th smallest element // in arr[l..r] using QuickSort based method. // ASSUMPTION: ALL ELEMENTS IN ARR ARE DISTINCT function kthSmallest( arr , l , r , k) { // If k is smaller than number of elements // in array if (k > 0 && k <= r - l + 1) { // Partition the array around last // element and get position of pivot // element in sorted array var pos = partition(arr, l, r); // If position is same as k if (pos - l == k - 1) return arr[pos]; // If position is more, recur for // left subarray if (pos - l > k - 1) return kthSmallest(arr, l, pos - 1, k); // Else recur for right subarray return kthSmallest(arr, pos + 1, r, k - pos + l - 1); } // If k is more than number of elements // in array return Number.MAX_VALUE; } // Driver program to test above methods var arr = [ 12, 3, 5, 7, 4, 19, 26 ]; var k = 3; document.write("K'th smallest element is " + kthSmallest(arr, 0, arr.length - 1, k)); // This code contributed by Rajput-Ji </script> K'th smallest element is 5 Method 6 (Map STL) A map-based STL approach is although very much similar to the quickselect and counting sort algorithm but much easier to implement. We can use an ordered map and map each element with its frequency. And as we know that an ordered map would store the data in a sorted manner, we keep on adding the frequency of each element till it does not become greater than or equal to k so that we reach the k’th element from the start i.e. the k’th smallest element. Eg – Array={7,0,25,6,16,17,0} k=3 Now in order to get the k’th largest element, we need to add the frequencies till it becomes greater than or equal to 3. It is clear from the above that the frequency of 0 + frequency of 6 will become equal to 3 so the third smallest number in the array will be 6. We can achieve the above using an iterator to traverse the map. C++ Java #include <bits/stdc++.h>using namespace std;int Kth_smallest(map<int, int> m, int k){ int freq = 0; for (auto it = m.begin(); it != m.end(); it++) { freq += (it->second); // adding the frequencies of // each element if (freq >= k) // if at any point frequency becomes // greater than or equal to k then // return that element { return it->first; } } return -1; // returning -1 if k>size of the array which // is an impossible scenario}int main(){ int n = 5; int k = 2; vector<int> arr = { 12, 3, 5, 7, 19 }; map<int, int> m; for (int i = 0; i < n; i++) { m[arr[i]] += 1; // mapping every element with it's // frequency } int ans = Kth_smallest(m, k); if(k==1){ cout << "The " << k << "st smallest element is " << ans << endl; } else if(k==2){ cout << "The " << k << "nd smallest element is " << ans << endl; } else if(k==3){ cout << "The " << k << "rd smallest element is " << ans << endl; } else{ cout << "The " << k << "th smallest element is " << ans << endl; } return 0;} // Java program for the above approachimport java.util.*; class GFG { static int Kth_smallest(TreeMap<Integer, Integer> m, int k) { int freq = 0; for (Map.Entry it : m.entrySet()) { // adding the frequencies of each element freq += (int)it.getValue(); // if at any point frequency becomes // greater than or equal to k then // return that element if (freq >= k) { return (int)it.getKey(); } } return -1; // returning -1 if k>size of the array // which is an impossible scenario } // Driver code public static void main(String[] args) { int n = 5; int k = 2; int[] arr = { 12, 3, 5, 7, 19 }; TreeMap<Integer, Integer> m = new TreeMap<>(); for (int i = 0; i < n; i++) { // mapping every element with // it's // frequency m.put(arr[i], m.getOrDefault(arr[i], 0) + 1); } int ans = Kth_smallest(m, k); if(k==1){ System.out.println( "The " + k + "st smallest element is " + ans); } else if(k==2){ System.out.println( "The " + k + "nd smallest element is " + ans); } else if(k==3){ System.out.println( "The " + k + "rd smallest element is " + ans); } else{ System.out.println( "The " + k + "th smallest element is " + ans); } }} // This code is contributed by harshit17. The 2nd smallest element is 5 There are two more solutions that are better than the above-discussed ones: One solution is to do a randomized version of quickSelect() and the other solution is the worst-case linear time algorithm (see the following posts). Method 7 (Max heap using STL): We can implement max and min heap using a priority queue.To find the kth minimum element in an array we will max heapify the array until the size of the heap becomes k. After that for each entry we will pop the top element from the heap/Priority Queue. Below is the implementation of the above approach: C++ Java // C++ code to implement the approach#include<bits/stdc++.h>using namespace std; // Function to find the kth smallest array elementint kthSmallest(int arr[], int n, int k) { // For finding min element we need (Max heap)priority queue priority_queue<int> pq; for(int i = 0; i < k; i++) { // First push first K elememts into heap pq.push(arr[i]); } // Now check from k to last element for(int i = k; i < n; i++) { // If current element is < top that means // there are other k-1 lesser elements // are present at bottom thus, pop that element // and add kth largest element into the heap till curr // at last all the greater element than kth element will get pop off // and at the top of heap there will be kth smallest element if(arr[i] < pq.top()) { pq.pop(); // Push curr element pq.push(arr[i]); } } // Return top of element return pq.top(); } // Driver's code:int main(){ int n = 10; int arr[n] = {10, 5, 4 , 3 ,48, 6 , 2 , 33, 53, 10}; int k = 4; cout<< "Kth Smallest Element is: "<<kthSmallest(arr, n, k); } // Java code to implement the approachimport java.util.*; //Custom comparator class to form the Max heapclass MinHeapComparator implements Comparator<Integer> { @Override public int compare(Integer number1, Integer number2) { int value = number1.compareTo(number2); // Elements are sorted in reverse order if (value > 0) { return -1; } else if (value < 0) { return 1; } else { return 0; } }}class GFG{ // Function to find kth smallest array elementstatic int kthSmallest(int []v, int N, int K){ //For finding min element we need (Max heap)priority queue PriorityQueue<Integer> heap1 = new PriorityQueue<Integer>(new MinHeapComparator()); for (int i = 0; i < N; ++i) { // Insert elements into // the priority queue heap1.add(v[i]); //If current element is less than top, that means there are //other k-1 lesser elements are present at bottom // thus pop that element and add kth largest element into the heap till curr // at last all the greater element than kth element will get pop off // and at the top of heap there will be kth smallest element if (heap1.size() > K) { heap1.remove(); } } //Return the top of the heap as kth smallest element return heap1.peek();} // Driver codepublic static void main(String[] args){ // Given array int []vec = {10, 5, 4 , 3 ,48, 15, 6 , 2 , 33, 53, 10}; // Size of array int N = vec.length; // Given K int K = 4; // Function Call System.out.println("Kth Smallest Element: " + kthSmallest(vec, N, K)) ;}} Kth Smallest Element is: 5 Time complexity: O(nlogk)Auxiliary Space Complexity: O(logK) This method is contributed by rupeshsk30. K’th Smallest/Largest Element in Unsorted Array | Set 2 (Expected Linear Time) K’th Smallest/Largest Element in Unsorted Array | Set 3 (Worst-Case Linear Time) nitin mittal vt_m shrikanth13 29AjayKumar ukasp velli_chor arpit2205 Rajput-Ji GauravRajput1 avanitrachhadiya2155 rag2127 mayanktyagi1709 adityamutharia moneshsannareddy sumitgumber28 rajsanghavi9 abhishek0719kadiyan kevinjoshi46b harshit17 rupeshsk30 krishjindalrock ABCO Accolite Amazon Cisco Microsoft Order-Statistics Rockstand SAP Labs Snapdeal VMWare Arrays Heap Searching VMWare Accolite Amazon Microsoft Snapdeal ABCO SAP Labs Cisco Rockstand Arrays Searching Heap Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Introduction to Arrays Multidimensional Arrays in Java Linked List vs Array Python | Using 2D arrays/lists the right way Search an element in a sorted and rotated array HeapSort Binary Heap Huffman Coding | Greedy Algo-3 Building Heap from Array Insertion and Deletion in Heaps
[ { "code": null, "e": 26105, "s": 26077, "text": "\n12 May, 2022" }, { "code": null, "e": 26294, "s": 26105, "text": "Given an array and a number k where k is smaller than the size of the array, we need to find the k’th smallest element in the given array. It is given that all array elements are distinct." }, { "code": null, "e": 26306, "s": 26294, "text": "Examples: " }, { "code": null, "e": 26359, "s": 26306, "text": "Input: arr[] = {7, 10, 4, 3, 20, 15} k = 3 Output: 7" }, { "code": null, "e": 26415, "s": 26359, "text": "Input: arr[] = {7, 10, 4, 3, 20, 15} k = 4 Output: 10 " }, { "code": null, "e": 26481, "s": 26415, "text": "We have discussed a similar problem to print k largest elements. " }, { "code": null, "e": 26733, "s": 26481, "text": "Method 1 (Simple Solution) A simple solution is to sort the given array using an O(N log N) sorting algorithm like Merge Sort, Heap Sort, etc, and return the element at index k-1 in the sorted array. The Time Complexity of this solution is O(N log N) " }, { "code": null, "e": 26737, "s": 26733, "text": "C++" }, { "code": null, "e": 26742, "s": 26737, "text": "Java" }, { "code": null, "e": 26750, "s": 26742, "text": "Python3" }, { "code": null, "e": 26753, "s": 26750, "text": "C#" }, { "code": null, "e": 26757, "s": 26753, "text": "PHP" }, { "code": null, "e": 26768, "s": 26757, "text": "Javascript" }, { "code": "// Simple C++ program to find k'th smallest element#include <algorithm>#include <iostream>using namespace std; // Function to return k'th smallest element in a given arrayint kthSmallest(int arr[], int n, int k){ // Sort the given array sort(arr, arr + n); // Return k'th element in the sorted array return arr[k - 1];} // Driver program to test above methodsint main(){ int arr[] = { 12, 3, 5, 7, 19 }; int n = sizeof(arr) / sizeof(arr[0]), k = 2; cout << \"K'th smallest element is \" << kthSmallest(arr, n, k); return 0;}", "e": 27316, "s": 26768, "text": null }, { "code": "// Java code for kth smallest element// in an arrayimport java.util.Arrays;import java.util.Collections; class GFG { // Function to return k'th smallest // element in a given array public static int kthSmallest(Integer[] arr, int k) { // Sort the given array Arrays.sort(arr); // Return k'th element in // the sorted array return arr[k - 1]; } // driver program public static void main(String[] args) { Integer arr[] = new Integer[] { 12, 3, 5, 7, 19 }; int k = 2; System.out.print(\"K'th smallest element is \" + kthSmallest(arr, k)); }} // This code is contributed by Chhavi", "e": 28009, "s": 27316, "text": null }, { "code": "# Python3 program to find k'th smallest# element # Function to return k'th smallest# element in a given arraydef kthSmallest(arr, n, k): # Sort the given array arr.sort() # Return k'th element in the # sorted array return arr[k-1] # Driver codeif __name__=='__main__': arr = [12, 3, 5, 7, 19] n = len(arr) k = 2 print(\"K'th smallest element is\", kthSmallest(arr, n, k)) # This code is contributed by# Shrikant13", "e": 28459, "s": 28009, "text": null }, { "code": "// C# code for kth smallest element// in an arrayusing System; class GFG { // Function to return k'th smallest // element in a given array public static int kthSmallest(int[] arr, int k) { // Sort the given array Array.Sort(arr); // Return k'th element in // the sorted array return arr[k - 1]; } // driver program public static void Main() { int[] arr = new int[] { 12, 3, 5, 7, 19 }; int k = 2; Console.Write(\"K'th smallest element\" + \" is \" + kthSmallest(arr, k)); }} // This code is contributed by nitin mittal.", "e": 29147, "s": 28459, "text": null }, { "code": "<?php// Simple PHP program to find// k'th smallest element // Function to return k'th smallest// element in a given arrayfunction kthSmallest($arr, $n, $k){ // Sort the given array sort($arr); // Return k'th element // in the sorted array return $arr[$k - 1];} // Driver Code $arr = array(12, 3, 5, 7, 19); $n =count($arr); $k = 2; echo \"K'th smallest element is \", kthSmallest($arr, $n, $k); // This code is contributed by anuj_67.?>", "e": 29619, "s": 29147, "text": null }, { "code": "<script> // Simple Javascript program to find k'th smallest element // Function to return k'th smallest element in a given arrayfunction kthSmallest(arr, n, k){ // Sort the given array arr.sort((a,b) => a-b); // Return k'th element in the sorted array return arr[k - 1];} // Driver program to test above methods let arr = [ 12, 3, 5, 7, 19 ]; let n = arr.length, k = 2; document.write(\"K'th smallest element is \" + kthSmallest(arr, n, k)); //This code is contributed by Mayank Tyagi</script>", "e": 30133, "s": 29619, "text": null }, { "code": null, "e": 30160, "s": 30133, "text": "K'th smallest element is 5" }, { "code": null, "e": 30194, "s": 30160, "text": "Method 2 (using set from C++ STL)" }, { "code": null, "e": 30600, "s": 30194, "text": "we can find the kth smallest element in time complexity better than O(N log N). we know the Set in C++ STL is implemented using Binary Search Tree and we also know that the time complexity of all cases(searching, inserting, deleting ) in BST is log (n) in the average case and O(n) in the worst case. We are using set because it is mentioned in the question that all the elements in an array are distinct." }, { "code": null, "e": 30661, "s": 30600, "text": "The following is the C++ implementation of the above method." }, { "code": null, "e": 30665, "s": 30661, "text": "C++" }, { "code": "/* the following code demonstrates how to find kth smallestelement using set from C++ STL */ #include <bits/stdc++.h>using namespace std; int main(){ int arr[] = { 12, 3, 5, 7, 19 }; int n = sizeof(arr) / sizeof(arr[0]); int k = 4; set<int> s(arr, arr + n); set<int>::iterator itr = s.begin(); // s.begin() returns a pointer to first // element in the set advance(itr, k - 1); // itr points to kth element in set cout << *itr << \"\\n\"; return 0;}", "e": 31166, "s": 30665, "text": null }, { "code": null, "e": 31169, "s": 31166, "text": "12" }, { "code": null, "e": 31257, "s": 31169, "text": "Time Complexity: O( log N) in Average Case and O(N) in Worst CaseAuxiliary Space: O(N)" }, { "code": null, "e": 31475, "s": 31257, "text": "Method 3 (Using Min Heap – HeapSelect) We can find k’th smallest element in time complexity better than O(N Log N). A simple optimization is to create a Min Heap of the given n elements and call extractMin() k times. " }, { "code": null, "e": 31530, "s": 31475, "text": "The following is C++ implementation of above method. " }, { "code": null, "e": 31534, "s": 31530, "text": "C++" }, { "code": null, "e": 31539, "s": 31534, "text": "Java" }, { "code": null, "e": 31547, "s": 31539, "text": "Python3" }, { "code": null, "e": 31550, "s": 31547, "text": "C#" }, { "code": "// A C++ program to find k'th smallest element using min heap#include <climits>#include <iostream>using namespace std; // Prototype of a utility function to swap two integersvoid swap(int* x, int* y); // A class for Min Heapclass MinHeap { int* harr; // pointer to array of elements in heap int capacity; // maximum possible size of min heap int heap_size; // Current number of elements in min heappublic: MinHeap(int a[], int size); // Constructor void MinHeapify(int i); // To minheapify subtree rooted with index i int parent(int i) { return (i - 1) / 2; } int left(int i) { return (2 * i + 1); } int right(int i) { return (2 * i + 2); } int extractMin(); // extracts root (minimum) element int getMin() { return harr[0]; } // Returns minimum}; MinHeap::MinHeap(int a[], int size){ heap_size = size; harr = a; // store address of array int i = (heap_size - 1) / 2; while (i >= 0) { MinHeapify(i); i--; }} // Method to remove minimum element (or root) from min heapint MinHeap::extractMin(){ if (heap_size == 0) return INT_MAX; // Store the minimum value. int root = harr[0]; // If there are more than 1 items, move the last item to root // and call heapify. if (heap_size > 1) { harr[0] = harr[heap_size - 1]; MinHeapify(0); } heap_size--; return root;} // A recursive method to heapify a subtree with root at given index// This method assumes that the subtrees are already heapifiedvoid MinHeap::MinHeapify(int i){ int l = left(i); int r = right(i); int smallest = i; if (l < heap_size && harr[l] < harr[i]) smallest = l; if (r < heap_size && harr[r] < harr[smallest]) smallest = r; if (smallest != i) { swap(&harr[i], &harr[smallest]); MinHeapify(smallest); }} // A utility function to swap two elementsvoid swap(int* x, int* y){ int temp = *x; *x = *y; *y = temp;} // Function to return k'th smallest element in a given arrayint kthSmallest(int arr[], int n, int k){ // Build a heap of n elements: O(n) time MinHeap mh(arr, n); // Do extract min (k-1) times for (int i = 0; i < k - 1; i++) mh.extractMin(); // Return root return mh.getMin();} // Driver program to test above methodsint main(){ int arr[] = { 12, 3, 5, 7, 19 }; int n = sizeof(arr) / sizeof(arr[0]), k = 2; cout << \"K'th smallest element is \" << kthSmallest(arr, n, k); return 0;}", "e": 34010, "s": 31550, "text": null }, { "code": "// A Java program to find k'th smallest element using min heapimport java.util.*;class GFG{ // A class for Max Heap class MinHeap { int[] harr; // pointer to array of elements in heap int capacity; // maximum possible size of min heap int heap_size; // Current number of elements in min heap int parent(int i) { return (i - 1) / 2; } int left(int i) { return ((2 * i )+ 1); } int right(int i) { return ((2 * i) + 2); } int getMin() { return harr[0]; } // Returns minimum // to replace root with new node x and heapify() new root void replaceMax(int x) { this.harr[0] = x; minHeapify(0); } MinHeap(int a[], int size) { heap_size = size; harr = a; // store address of array int i = (heap_size - 1) / 2; while (i >= 0) { minHeapify(i); i--; } } // Method to remove maximum element (or root) from min heap int extractMin() { if (heap_size == 0) return Integer.MAX_VALUE; // Store the maximum value. int root = harr[0]; // If there are more than 1 items, move the last item to root // and call heapify. if (heap_size > 1) { harr[0] = harr[heap_size - 1]; minHeapify(0); } heap_size--; return root; } // A recursive method to heapify a subtree with root at given index // This method assumes that the subtrees are already heapified void minHeapify(int i) { int l = left(i); int r = right(i); int smallest = i; if (l < heap_size && harr[l] < harr[i]) smallest = l; if (r < heap_size && harr[r] < harr[smallest]) smallest = r; if (smallest != i) { int t = harr[i]; harr[i] = harr[smallest]; harr[smallest] = t; minHeapify(smallest); } } }; // Function to return k'th largest element in a given array int kthSmallest(int arr[], int n, int k) { // Build a heap of first k elements: O(k) time MinHeap mh = new MinHeap(arr, n); // Process remaining n-k elements. If current element is // smaller than root, replace root with current element for (int i = 0; i < k - 1; i++) mh.extractMin(); // Return root return mh.getMin(); } // Driver program to test above methods public static void main(String[] args) { int arr[] = { 12, 3, 5, 7, 19 }; int n = arr.length, k = 2; GFG gfg = new GFG(); System.out.print(\"K'th smallest element is \" + gfg.kthSmallest(arr, n, k)); }} // This code is contributed by avanitrachhadiya2155", "e": 36576, "s": 34010, "text": null }, { "code": "# Python3 program to find k'th smallest element# using min heap # Class for Min Heapclass MinHeap: # Constructor def __init__(self, a, size): # list of elements in the heap self.harr = a # maximum possible size of min heap self.capacity = None # current number of elements in min heap self.heap_size = size i = int((self.heap_size - 1) / 2) while i >= 0: self.minHeapify(i) i -= 1 def parent(self, i): return (i - 1) / 2 def left(self, i): return 2 * i + 1 def right(self, i): return 2 * i + 2 # Returns minimum def getMin(self): return self.harr[0] # Method to remove minimum element (or root) # from min heap def extractMin(self): if self.heap_size == 0: return float(\"inf\") # Store the minimum value root = self.harr[0] # If there are more than 1 items, move the last item # to root and call heapify if self.heap_size > 1: self.harr[0] = self.harr[self.heap_size - 1] self.minHeapify(0) self.heap_size -= 1 return root # A recursive method to heapify a subtree with root at # given index. This method assumes that the subtrees # are already heapified def minHeapify(self, i): l = self.left(i) r = self.right(i) smallest = i if ((l < self.heap_size) and (self.harr[l] < self.harr[i])): smallest = l if ((r < self.heap_size) and (self.harr[r] < self.harr[smallest])): smallest = r if smallest != i: self.harr[i], self.harr[smallest] = ( self.harr[smallest], self.harr[i]) self.minHeapify(smallest) # Function to return k'th smallest element in a given arraydef kthSmallest(arr, n, k): # Build a heap of n elements in O(n) time mh = MinHeap(arr, n) # Do extract min (k-1) times for i in range(k - 1): mh.extractMin() # Return root return mh.getMin() # Driver codearr = [12, 3, 5, 7, 19]n = len(arr)k = 2print(\"K'th smallest element is\", kthSmallest(arr, n, k)) # This Code is contributed by Kevin Joshi", "e": 38806, "s": 36576, "text": null }, { "code": "using System;public class GFG{ public class MinHeap { int[] harr; // pointer to array of elements in heap // int capacity; // maximum possible size of min heap int heap_size; // Current number of elements in min heap int parent(int i) { return (i - 1) / 2; } int left(int i) { return ((2 * i )+ 1); } int right(int i) { return ((2 * i) + 2); } public int getMin() { return harr[0]; } // Returns minimum // to replace root with new node x and heapify() new root public void replaceMax(int x) { this.harr[0] = x; minHeapify(0); } public MinHeap(int[] a, int size) { heap_size = size; harr = a; // store address of array int i = (heap_size - 1) / 2; while (i >= 0) { minHeapify(i); i--; } } // Method to remove maximum element (or root) from min heap public int extractMin() { if (heap_size == 0) return Int32.MaxValue; // Store the maximum value. int root = harr[0]; // If there are more than 1 items, move the last item to root // and call heapify. if (heap_size > 1) { harr[0] = harr[heap_size - 1]; minHeapify(0); } heap_size--; return root; } // A recursive method to heapify a subtree with root at given index // This method assumes that the subtrees are already heapified public void minHeapify(int i) { int l = left(i); int r = right(i); int smallest = i; if (l < heap_size && harr[l] < harr[i]) smallest = l; if (r < heap_size && harr[r] < harr[smallest]) smallest = r; if (smallest != i) { int t = harr[i]; harr[i] = harr[smallest]; harr[smallest] = t; minHeapify(smallest); } } }; // Function to return k'th largest element in a given array int kthSmallest(int[] arr, int n, int k) { // Build a heap of first k elements: O(k) time MinHeap mh = new MinHeap(arr, n); // Process remaining n-k elements. If current element is // smaller than root, replace root with current element for (int i = 0; i < k - 1; i++) mh.extractMin(); // Return root return mh.getMin(); } // Driver program to test above methods static public void Main (){ int[] arr = { 12, 3, 5, 7, 19 }; int n = arr.Length, k = 2; GFG gfg = new GFG(); Console.Write(\"K'th smallest element is \" + gfg.kthSmallest(arr, n, k)); }} // This code is contributed by rag2127", "e": 41299, "s": 38806, "text": null }, { "code": null, "e": 41326, "s": 41299, "text": "K'th smallest element is 5" }, { "code": null, "e": 41376, "s": 41326, "text": "Time complexity of this solution is O(n + kLogn)." }, { "code": null, "e": 41935, "s": 41376, "text": "Method 4 (Using Max-Heap) We can also use Max Heap for finding the k’th smallest element. Following is an algorithm. 1) Build a Max-Heap MH of the first k elements (arr[0] to arr[k-1]) of the given array. O(k)2) For each element, after the k’th element (arr[k] to arr[n-1]), compare it with root of MH. ......a) If the element is less than the root then make it root and call heapify for MH ......b) Else ignore it. // The step 2 is O((n-k)*logk)3) Finally, the root of the MH is the kth smallest element.Time complexity of this solution is O(k + (n-k)*Logk)" }, { "code": null, "e": 41995, "s": 41935, "text": "The following is C++ implementation of the above algorithm " }, { "code": null, "e": 41999, "s": 41995, "text": "C++" }, { "code": null, "e": 42004, "s": 41999, "text": "Java" }, { "code": null, "e": 42012, "s": 42004, "text": "Python3" }, { "code": null, "e": 42015, "s": 42012, "text": "C#" }, { "code": "// A C++ program to find k'th smallest element using max heap#include <climits>#include <iostream>using namespace std; // Prototype of a utility function to swap two integersvoid swap(int* x, int* y); // A class for Max Heapclass MaxHeap { int* harr; // pointer to array of elements in heap int capacity; // maximum possible size of max heap int heap_size; // Current number of elements in max heappublic: MaxHeap(int a[], int size); // Constructor void maxHeapify(int i); // To maxHeapify subtree rooted with index i int parent(int i) { return (i - 1) / 2; } int left(int i) { return (2 * i + 1); } int right(int i) { return (2 * i + 2); } int extractMax(); // extracts root (maximum) element int getMax() { return harr[0]; } // Returns maximum // to replace root with new node x and heapify() new root void replaceMax(int x) { harr[0] = x; maxHeapify(0); }}; MaxHeap::MaxHeap(int a[], int size){ heap_size = size; harr = a; // store address of array int i = (heap_size - 1) / 2; while (i >= 0) { maxHeapify(i); i--; }} // Method to remove maximum element (or root) from max heapint MaxHeap::extractMax(){ if (heap_size == 0) return INT_MAX; // Store the maximum value. int root = harr[0]; // If there are more than 1 items, move the last item to root // and call heapify. if (heap_size > 1) { harr[0] = harr[heap_size - 1]; maxHeapify(0); } heap_size--; return root;} // A recursive method to heapify a subtree with root at given index// This method assumes that the subtrees are already heapifiedvoid MaxHeap::maxHeapify(int i){ int l = left(i); int r = right(i); int largest = i; if (l < heap_size && harr[l] > harr[i]) largest = l; if (r < heap_size && harr[r] > harr[largest]) largest = r; if (largest != i) { swap(&harr[i], &harr[largest]); maxHeapify(largest); }} // A utility function to swap two elementsvoid swap(int* x, int* y){ int temp = *x; *x = *y; *y = temp;} // Function to return k'th largest element in a given arrayint kthSmallest(int arr[], int n, int k){ // Build a heap of first k elements: O(k) time MaxHeap mh(arr, k); // Process remaining n-k elements. If current element is // smaller than root, replace root with current element for (int i = k; i < n; i++) if (arr[i] < mh.getMax()) mh.replaceMax(arr[i]); // Return root return mh.getMax();} // Driver program to test above methodsint main(){ int arr[] = { 12, 3, 5, 7, 19 }; int n = sizeof(arr) / sizeof(arr[0]), k = 4; cout << \"K'th smallest element is \" << kthSmallest(arr, n, k); return 0;}", "e": 44739, "s": 42015, "text": null }, { "code": "// A Java program to find k'th smallest element using max heapimport java.util.*;class GFG{ // A class for Max Heap class MaxHeap { int[] harr; // pointer to array of elements in heap int capacity; // maximum possible size of max heap int heap_size; // Current number of elements in max heap int parent(int i) { return (i - 1) / 2; } int left(int i) { return (2 * i + 1); } int right(int i) { return (2 * i + 2); } int getMax() { return harr[0]; } // Returns maximum // to replace root with new node x and heapify() new root void replaceMax(int x) { this.harr[0] = x; maxHeapify(0); } MaxHeap(int a[], int size) { heap_size = size; harr = a; // store address of array int i = (heap_size - 1) / 2; while (i >= 0) { maxHeapify(i); i--; } } // Method to remove maximum element (or root) from max heap int extractMax() { if (heap_size == 0) return Integer.MAX_VALUE; // Store the maximum value. int root = harr[0]; // If there are more than 1 items, move the last item to root // and call heapify. if (heap_size > 1) { harr[0] = harr[heap_size - 1]; maxHeapify(0); } heap_size--; return root; } // A recursive method to heapify a subtree with root at given index // This method assumes that the subtrees are already heapified void maxHeapify(int i) { int l = left(i); int r = right(i); int largest = i; if (l < heap_size && harr[l] > harr[i]) largest = l; if (r < heap_size && harr[r] > harr[largest]) largest = r; if (largest != i) { int t = harr[i]; harr[i] = harr[largest]; harr[largest] = t; maxHeapify(largest); } } }; // Function to return k'th largest element in a given array int kthSmallest(int arr[], int n, int k) { // Build a heap of first k elements: O(k) time MaxHeap mh = new MaxHeap(arr, k); // Process remaining n-k elements. If current element is // smaller than root, replace root with current element for (int i = k; i < n; i++) if (arr[i] < mh.getMax()) mh.replaceMax(arr[i]); // Return root return mh.getMax(); } // Driver program to test above methods public static void main(String[] args) { int arr[] = { 12, 3, 5, 7, 19 }; int n = arr.length, k = 4; GFG gfg = new GFG(); System.out.print(\"K'th smallest element is \" + gfg.kthSmallest(arr, n, k)); }} // This code is contributed by Rajput-Ji", "e": 47319, "s": 44739, "text": null }, { "code": "# Python3 program to find k'th smallest element# using max heap # Class for Max Heapclass MaxHeap: # Constructor def __init__(self, a, size): # list of elements in the heap self.harr = a # maximum possible size of max heap self.capacity = None # current number of elements in max heap self.heap_size = size i = int((self.heap_size - 1) / 2) while i >= 0: self.maxHeapify(i) i -= 1 def parent(self, i): return (i - 1) / 2 def left(self, i): return 2 * i + 1 def right(self, i): return 2 * i + 2 # Returns maximum def getMax(self): return self.harr[0] # to replace root with new node x and heapify() new root def replaceMax(self, x): self.harr[0] = x self.maxHeapify(0) # Method to remove maximum element (or root) # from max heap def extractMin(self): if self.heap_size == 0: return float(\"inf\") # Store the maximum value. root = self.harr[0] # If there are more than 1 items, move the # last item to root and call heapify if self.heap_size > 1: self.harr[0] = self.harr[self.heap_size - 1] self.maxHeapify(0) self.heap_size -= 1 return root # A recursive method to heapify a subtree with root at # given index. This method assumes that the subtrees # are already heapified def maxHeapify(self, i): l = self.left(i) r = self.right(i) largest = i if ((l < self.heap_size) and (self.harr[l] > self.harr[i])): largest = l if ((r < self.heap_size) and (self.harr[r] > self.harr[largest])): largest = r if largest != i: self.harr[i], self.harr[largest] = ( self.harr[largest], self.harr[i]) self.maxHeapify(largest) # Function to return k'th smallest element in a given arraydef kthSmallest(arr, n, k): # Build a heap of first k elements in O(k) time mh = MaxHeap(arr, k) # Process remaining n-k elements. If current element is # smaller than root, replace root with current element for i in range(k, n): if arr[i] < mh.getMax(): mh.replaceMax(arr[i]) # Return root return mh.getMax() # Driver codearr = [12, 3, 5, 7, 19]n = len(arr)k = 4print(\"K'th smallest element is\", kthSmallest(arr, n, k)) # Code contributed by Kevin Joshi", "e": 49776, "s": 47319, "text": null }, { "code": "// A C# program to find k'th smallest element using max heapusing System; public class GFG { // A class for Max Heap public class MaxHeap { public int[] harr; // pointer to array of elements in // heap public int capacity; // maximum possible size of max // heap public int heap_size; // Current number of elements in // max heap public int parent(int i) { return (i - 1) / 2; } public int left(int i) { return (2 * i + 1); } public int right(int i) { return (2 * i + 2); } public int getMax() { return harr[0]; } // Returns maximum // to replace root with new node x and heapify() new // root public void replaceMax(int x) { this.harr[0] = x; maxHeapify(0); } public MaxHeap(int[] a, int size) { heap_size = size; harr = a; // store address of array int i = (heap_size - 1) / 2; while (i >= 0) { maxHeapify(i); i--; } } // Method to remove maximum element (or root) from // max heap public int extractMax() { if (heap_size == 0) return int.MaxValue; // Store the maximum value. int root = harr[0]; // If there are more than 1 items, move the last // item to root and call heapify. if (heap_size > 1) { harr[0] = harr[heap_size - 1]; maxHeapify(0); } heap_size--; return root; } // A recursive method to heapify a subtree with root // at given index This method assumes that the // subtrees are already heapified public void maxHeapify(int i) { int l = left(i); int r = right(i); int largest = i; if (l < heap_size && harr[l] > harr[i]) largest = l; if (r < heap_size && harr[r] > harr[largest]) largest = r; if (largest != i) { int t = harr[i]; harr[i] = harr[largest]; harr[largest] = t; maxHeapify(largest); } } }; // Function to return k'th largest element in a given // array int kthSmallest(int[] arr, int n, int k) { // Build a heap of first k elements: O(k) time MaxHeap mh = new MaxHeap(arr, k); // Process remaining n-k elements. If current // element is smaller than root, replace root with // current element for (int i = k; i < n; i++) if (arr[i] < mh.getMax()) mh.replaceMax(arr[i]); // Return root return mh.getMax(); } // Driver code public static void Main(String[] args) { int[] arr = { 12, 3, 5, 7, 19 }; int n = arr.Length, k = 4; GFG gfg = new GFG(); Console.Write(\"K'th smallest element is \" + gfg.kthSmallest(arr, n, k)); }} // This code is contributed by gauravrajput1", "e": 53240, "s": 49776, "text": null }, { "code": null, "e": 53268, "s": 53240, "text": "K'th smallest element is 12" }, { "code": null, "e": 53837, "s": 53268, "text": "Method 5 (QuickSelect) This is an optimization over method 1 if QuickSort is used as a sorting algorithm in first step. In QuickSort, we pick a pivot element, then move the pivot element to its correct position and partition the surrounding array. The idea is, not to do complete quicksort, but stop at the point where pivot itself is k’th smallest element. Also, not to recur for both left and right sides of pivot, but recur for one of them according to the position of pivot. The worst case time complexity of this method is O(n2), but it works in O(n) on average. " }, { "code": null, "e": 53841, "s": 53837, "text": "C++" }, { "code": null, "e": 53846, "s": 53841, "text": "Java" }, { "code": null, "e": 53854, "s": 53846, "text": "Python3" }, { "code": null, "e": 53857, "s": 53854, "text": "C#" }, { "code": null, "e": 53868, "s": 53857, "text": "Javascript" }, { "code": "#include <climits>#include <iostream>using namespace std; int partition(int arr[], int l, int r); // This function returns k'th smallest element in arr[l..r] using// QuickSort based method. ASSUMPTION: ALL ELEMENTS IN ARR[] ARE DISTINCTint kthSmallest(int arr[], int l, int r, int k){ // If k is smaller than number of elements in array if (k > 0 && k <= r - l + 1) { // Partition the array around last element and get // position of pivot element in sorted array int pos = partition(arr, l, r); // If position is same as k if (pos - l == k - 1) return arr[pos]; if (pos - l > k - 1) // If position is more, recur for left subarray return kthSmallest(arr, l, pos - 1, k); // Else recur for right subarray return kthSmallest(arr, pos + 1, r, k - pos + l - 1); } // If k is more than number of elements in array return INT_MAX;} void swap(int* a, int* b){ int temp = *a; *a = *b; *b = temp;} // Standard partition process of QuickSort(). It considers the last// element as pivot and moves all smaller element to left of it// and greater elements to rightint partition(int arr[], int l, int r){ int x = arr[r], i = l; for (int j = l; j <= r - 1; j++) { if (arr[j] <= x) { swap(&arr[i], &arr[j]); i++; } } swap(&arr[i], &arr[r]); return i;} // Driver program to test above methodsint main(){ int arr[] = { 12, 3, 5, 7, 4, 19, 26 }; int n = sizeof(arr) / sizeof(arr[0]), k = 3; cout << \"K'th smallest element is \" << kthSmallest(arr, 0, n - 1, k); return 0;}", "e": 55492, "s": 53868, "text": null }, { "code": "// Java code for kth smallest element in an arrayimport java.util.Arrays;import java.util.Collections; class GFG { // Standard partition process of QuickSort. // It considers the last element as pivot // and moves all smaller element to left of // it and greater elements to right public static int partition(Integer[] arr, int l, int r) { int x = arr[r], i = l; for (int j = l; j <= r - 1; j++) { if (arr[j] <= x) { // Swapping arr[i] and arr[j] int temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; i++; } } // Swapping arr[i] and arr[r] int temp = arr[i]; arr[i] = arr[r]; arr[r] = temp; return i; } // This function returns k'th smallest element // in arr[l..r] using QuickSort based method. // ASSUMPTION: ALL ELEMENTS IN ARR[] ARE DISTINCT public static int kthSmallest(Integer[] arr, int l, int r, int k) { // If k is smaller than number of elements // in array if (k > 0 && k <= r - l + 1) { // Partition the array around last // element and get position of pivot // element in sorted array int pos = partition(arr, l, r); // If position is same as k if (pos - l == k - 1) return arr[pos]; // If position is more, recur for // left subarray if (pos - l > k - 1) return kthSmallest(arr, l, pos - 1, k); // Else recur for right subarray return kthSmallest(arr, pos + 1, r, k - pos + l - 1); } // If k is more than number of elements // in array return Integer.MAX_VALUE; } // Driver program to test above methods public static void main(String[] args) { Integer arr[] = new Integer[] { 12, 3, 5, 7, 4, 19, 26 }; int k = 3; System.out.print(\"K'th smallest element is \" + kthSmallest(arr, 0, arr.length - 1, k)); }} // This code is contributed by Chhavi", "e": 57645, "s": 55492, "text": null }, { "code": "# This function returns k'th smallest element# in arr[l..r] using QuickSort based method.# ASSUMPTION: ALL ELEMENTS IN ARR[] ARE DISTINCTimport sys def kthSmallest(arr, l, r, k): # If k is smaller than number of # elements in array if (k > 0 and k <= r - l + 1): # Partition the array around last # element and get position of pivot # element in sorted array pos = partition(arr, l, r) # If position is same as k if (pos - l == k - 1): return arr[pos] if (pos - l > k - 1): # If position is more, # recur for left subarray return kthSmallest(arr, l, pos - 1, k) # Else recur for right subarray return kthSmallest(arr, pos + 1, r, k - pos + l - 1) # If k is more than number of # elements in array return sys.maxsize # Standard partition process of QuickSort().# It considers the last element as pivot and# moves all smaller element to left of it# and greater elements to rightdef partition(arr, l, r): x = arr[r] i = l for j in range(l, r): if (arr[j] <= x): arr[i], arr[j] = arr[j], arr[i] i += 1 arr[i], arr[r] = arr[r], arr[i] return i # Driver Codeif __name__ == \"__main__\": arr = [12, 3, 5, 7, 4, 19, 26] n = len(arr) k = 3; print(\"K'th smallest element is\", kthSmallest(arr, 0, n - 1, k)) # This code is contributed by ita_c", "e": 59116, "s": 57645, "text": null }, { "code": "// C# code for kth smallest element// in an arrayusing System; class GFG { // Standard partition process of QuickSort. // It considers the last element as pivot // and moves all smaller element to left of // it and greater elements to right public static int partition(int[] arr, int l, int r) { int x = arr[r], i = l; int temp = 0; for (int j = l; j <= r - 1; j++) { if (arr[j] <= x) { // Swapping arr[i] and arr[j] temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; i++; } } // Swapping arr[i] and arr[r] temp = arr[i]; arr[i] = arr[r]; arr[r] = temp; return i; } // This function returns k'th smallest // element in arr[l..r] using QuickSort // based method. ASSUMPTION: ALL ELEMENTS // IN ARR[] ARE DISTINCT public static int kthSmallest(int[] arr, int l, int r, int k) { // If k is smaller than number // of elements in array if (k > 0 && k <= r - l + 1) { // Partition the array around last // element and get position of pivot // element in sorted array int pos = partition(arr, l, r); // If position is same as k if (pos - l == k - 1) return arr[pos]; // If position is more, recur for // left subarray if (pos - l > k - 1) return kthSmallest(arr, l, pos - 1, k); // Else recur for right subarray return kthSmallest(arr, pos + 1, r, k - pos + l - 1); } // If k is more than number // of elements in array return int.MaxValue; } // Driver Code public static void Main() { int[] arr = { 12, 3, 5, 7, 4, 19, 26 }; int k = 3; Console.Write(\"K'th smallest element is \" + kthSmallest(arr, 0, arr.Length - 1, k)); }} // This code is contributed// by 29AjayKumar", "e": 61215, "s": 59116, "text": null }, { "code": "<script> // JavaScript code for kth smallest// element in an array // Standard partition process of QuickSort. // It considers the last element as pivot // and moves all smaller element to left of // it and greater elements to right function partition( arr , l , r) { var x = arr[r], i = l; for (j = l; j <= r - 1; j++) { if (arr[j] <= x) { // Swapping arr[i] and arr[j] var temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; i++; } } // Swapping arr[i] and arr[r] var temp = arr[i]; arr[i] = arr[r]; arr[r] = temp; return i; } // This function returns k'th smallest element // in arr[l..r] using QuickSort based method. // ASSUMPTION: ALL ELEMENTS IN ARR ARE DISTINCT function kthSmallest( arr , l , r , k) { // If k is smaller than number of elements // in array if (k > 0 && k <= r - l + 1) { // Partition the array around last // element and get position of pivot // element in sorted array var pos = partition(arr, l, r); // If position is same as k if (pos - l == k - 1) return arr[pos]; // If position is more, recur for // left subarray if (pos - l > k - 1) return kthSmallest(arr, l, pos - 1, k); // Else recur for right subarray return kthSmallest(arr, pos + 1, r, k - pos + l - 1); } // If k is more than number of elements // in array return Number.MAX_VALUE; } // Driver program to test above methods var arr = [ 12, 3, 5, 7, 4, 19, 26 ]; var k = 3; document.write(\"K'th smallest element is \" + kthSmallest(arr, 0, arr.length - 1, k)); // This code contributed by Rajput-Ji </script>", "e": 63154, "s": 61215, "text": null }, { "code": null, "e": 63181, "s": 63154, "text": "K'th smallest element is 5" }, { "code": null, "e": 63201, "s": 63181, "text": "Method 6 (Map STL) " }, { "code": null, "e": 63656, "s": 63201, "text": "A map-based STL approach is although very much similar to the quickselect and counting sort algorithm but much easier to implement. We can use an ordered map and map each element with its frequency. And as we know that an ordered map would store the data in a sorted manner, we keep on adding the frequency of each element till it does not become greater than or equal to k so that we reach the k’th element from the start i.e. the k’th smallest element." }, { "code": null, "e": 63661, "s": 63656, "text": "Eg –" }, { "code": null, "e": 63686, "s": 63661, "text": "Array={7,0,25,6,16,17,0}" }, { "code": null, "e": 63690, "s": 63686, "text": "k=3" }, { "code": null, "e": 63955, "s": 63690, "text": "Now in order to get the k’th largest element, we need to add the frequencies till it becomes greater than or equal to 3. It is clear from the above that the frequency of 0 + frequency of 6 will become equal to 3 so the third smallest number in the array will be 6." }, { "code": null, "e": 64019, "s": 63955, "text": "We can achieve the above using an iterator to traverse the map." }, { "code": null, "e": 64023, "s": 64019, "text": "C++" }, { "code": null, "e": 64028, "s": 64023, "text": "Java" }, { "code": "#include <bits/stdc++.h>using namespace std;int Kth_smallest(map<int, int> m, int k){ int freq = 0; for (auto it = m.begin(); it != m.end(); it++) { freq += (it->second); // adding the frequencies of // each element if (freq >= k) // if at any point frequency becomes // greater than or equal to k then // return that element { return it->first; } } return -1; // returning -1 if k>size of the array which // is an impossible scenario}int main(){ int n = 5; int k = 2; vector<int> arr = { 12, 3, 5, 7, 19 }; map<int, int> m; for (int i = 0; i < n; i++) { m[arr[i]] += 1; // mapping every element with it's // frequency } int ans = Kth_smallest(m, k); if(k==1){ cout << \"The \" << k << \"st smallest element is \" << ans << endl; } else if(k==2){ cout << \"The \" << k << \"nd smallest element is \" << ans << endl; } else if(k==3){ cout << \"The \" << k << \"rd smallest element is \" << ans << endl; } else{ cout << \"The \" << k << \"th smallest element is \" << ans << endl; } return 0;}", "e": 65248, "s": 64028, "text": null }, { "code": "// Java program for the above approachimport java.util.*; class GFG { static int Kth_smallest(TreeMap<Integer, Integer> m, int k) { int freq = 0; for (Map.Entry it : m.entrySet()) { // adding the frequencies of each element freq += (int)it.getValue(); // if at any point frequency becomes // greater than or equal to k then // return that element if (freq >= k) { return (int)it.getKey(); } } return -1; // returning -1 if k>size of the array // which is an impossible scenario } // Driver code public static void main(String[] args) { int n = 5; int k = 2; int[] arr = { 12, 3, 5, 7, 19 }; TreeMap<Integer, Integer> m = new TreeMap<>(); for (int i = 0; i < n; i++) { // mapping every element with // it's // frequency m.put(arr[i], m.getOrDefault(arr[i], 0) + 1); } int ans = Kth_smallest(m, k); if(k==1){ System.out.println( \"The \" + k + \"st smallest element is \" + ans); } else if(k==2){ System.out.println( \"The \" + k + \"nd smallest element is \" + ans); } else if(k==3){ System.out.println( \"The \" + k + \"rd smallest element is \" + ans); } else{ System.out.println( \"The \" + k + \"th smallest element is \" + ans); } }} // This code is contributed by harshit17.", "e": 66791, "s": 65248, "text": null }, { "code": null, "e": 66821, "s": 66791, "text": "The 2nd smallest element is 5" }, { "code": null, "e": 67047, "s": 66821, "text": "There are two more solutions that are better than the above-discussed ones: One solution is to do a randomized version of quickSelect() and the other solution is the worst-case linear time algorithm (see the following posts)." }, { "code": null, "e": 67078, "s": 67047, "text": "Method 7 (Max heap using STL):" }, { "code": null, "e": 67332, "s": 67078, "text": "We can implement max and min heap using a priority queue.To find the kth minimum element in an array we will max heapify the array until the size of the heap becomes k. After that for each entry we will pop the top element from the heap/Priority Queue. " }, { "code": null, "e": 67383, "s": 67332, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 67387, "s": 67383, "text": "C++" }, { "code": null, "e": 67392, "s": 67387, "text": "Java" }, { "code": "// C++ code to implement the approach#include<bits/stdc++.h>using namespace std; // Function to find the kth smallest array elementint kthSmallest(int arr[], int n, int k) { // For finding min element we need (Max heap)priority queue priority_queue<int> pq; for(int i = 0; i < k; i++) { // First push first K elememts into heap pq.push(arr[i]); } // Now check from k to last element for(int i = k; i < n; i++) { // If current element is < top that means // there are other k-1 lesser elements // are present at bottom thus, pop that element // and add kth largest element into the heap till curr // at last all the greater element than kth element will get pop off // and at the top of heap there will be kth smallest element if(arr[i] < pq.top()) { pq.pop(); // Push curr element pq.push(arr[i]); } } // Return top of element return pq.top(); } // Driver's code:int main(){ int n = 10; int arr[n] = {10, 5, 4 , 3 ,48, 6 , 2 , 33, 53, 10}; int k = 4; cout<< \"Kth Smallest Element is: \"<<kthSmallest(arr, n, k); }", "e": 68599, "s": 67392, "text": null }, { "code": "// Java code to implement the approachimport java.util.*; //Custom comparator class to form the Max heapclass MinHeapComparator implements Comparator<Integer> { @Override public int compare(Integer number1, Integer number2) { int value = number1.compareTo(number2); // Elements are sorted in reverse order if (value > 0) { return -1; } else if (value < 0) { return 1; } else { return 0; } }}class GFG{ // Function to find kth smallest array elementstatic int kthSmallest(int []v, int N, int K){ //For finding min element we need (Max heap)priority queue PriorityQueue<Integer> heap1 = new PriorityQueue<Integer>(new MinHeapComparator()); for (int i = 0; i < N; ++i) { // Insert elements into // the priority queue heap1.add(v[i]); //If current element is less than top, that means there are //other k-1 lesser elements are present at bottom // thus pop that element and add kth largest element into the heap till curr // at last all the greater element than kth element will get pop off // and at the top of heap there will be kth smallest element if (heap1.size() > K) { heap1.remove(); } } //Return the top of the heap as kth smallest element return heap1.peek();} // Driver codepublic static void main(String[] args){ // Given array int []vec = {10, 5, 4 , 3 ,48, 15, 6 , 2 , 33, 53, 10}; // Size of array int N = vec.length; // Given K int K = 4; // Function Call System.out.println(\"Kth Smallest Element: \" + kthSmallest(vec, N, K)) ;}}", "e": 70279, "s": 68599, "text": null }, { "code": null, "e": 70306, "s": 70279, "text": "Kth Smallest Element is: 5" }, { "code": null, "e": 70367, "s": 70306, "text": "Time complexity: O(nlogk)Auxiliary Space Complexity: O(logK)" }, { "code": null, "e": 70409, "s": 70367, "text": "This method is contributed by rupeshsk30." }, { "code": null, "e": 70569, "s": 70409, "text": "K’th Smallest/Largest Element in Unsorted Array | Set 2 (Expected Linear Time) K’th Smallest/Largest Element in Unsorted Array | Set 3 (Worst-Case Linear Time)" }, { "code": null, "e": 70588, "s": 70575, "text": "nitin mittal" }, { "code": null, "e": 70593, "s": 70588, "text": "vt_m" }, { "code": null, "e": 70605, "s": 70593, "text": "shrikanth13" }, { "code": null, "e": 70617, "s": 70605, "text": "29AjayKumar" }, { "code": null, "e": 70623, "s": 70617, "text": "ukasp" }, { "code": null, "e": 70634, "s": 70623, "text": "velli_chor" }, { "code": null, "e": 70644, "s": 70634, "text": "arpit2205" }, { "code": null, "e": 70654, "s": 70644, "text": "Rajput-Ji" }, { "code": null, "e": 70668, "s": 70654, "text": "GauravRajput1" }, { "code": null, "e": 70689, "s": 70668, "text": "avanitrachhadiya2155" }, { "code": null, "e": 70697, "s": 70689, "text": "rag2127" }, { "code": null, "e": 70713, "s": 70697, "text": "mayanktyagi1709" }, { "code": null, "e": 70728, "s": 70713, "text": "adityamutharia" }, { "code": null, "e": 70745, "s": 70728, "text": "moneshsannareddy" }, { "code": null, "e": 70759, "s": 70745, "text": "sumitgumber28" }, { "code": null, "e": 70772, "s": 70759, "text": "rajsanghavi9" }, { "code": null, "e": 70792, "s": 70772, "text": "abhishek0719kadiyan" }, { "code": null, "e": 70806, "s": 70792, "text": "kevinjoshi46b" }, { "code": null, "e": 70816, "s": 70806, "text": "harshit17" }, { "code": null, "e": 70827, "s": 70816, "text": "rupeshsk30" }, { "code": null, "e": 70843, "s": 70827, "text": "krishjindalrock" }, { "code": null, "e": 70848, "s": 70843, "text": "ABCO" }, { "code": null, "e": 70857, "s": 70848, "text": "Accolite" }, { "code": null, "e": 70864, "s": 70857, "text": "Amazon" }, { "code": null, "e": 70870, "s": 70864, "text": "Cisco" }, { "code": null, "e": 70880, "s": 70870, "text": "Microsoft" }, { "code": null, "e": 70897, "s": 70880, "text": "Order-Statistics" }, { "code": null, "e": 70907, "s": 70897, "text": "Rockstand" }, { "code": null, "e": 70916, "s": 70907, "text": "SAP Labs" }, { "code": null, "e": 70925, "s": 70916, "text": "Snapdeal" }, { "code": null, "e": 70932, "s": 70925, "text": "VMWare" }, { "code": null, "e": 70939, "s": 70932, "text": "Arrays" }, { "code": null, "e": 70944, "s": 70939, "text": "Heap" }, { "code": null, "e": 70954, "s": 70944, "text": "Searching" }, { "code": null, "e": 70961, "s": 70954, "text": "VMWare" }, { "code": null, "e": 70970, "s": 70961, "text": "Accolite" }, { "code": null, "e": 70977, "s": 70970, "text": "Amazon" }, { "code": null, "e": 70987, "s": 70977, "text": "Microsoft" }, { "code": null, "e": 70996, "s": 70987, "text": "Snapdeal" }, { "code": null, "e": 71001, "s": 70996, "text": "ABCO" }, { "code": null, "e": 71010, "s": 71001, "text": "SAP Labs" }, { "code": null, "e": 71016, "s": 71010, "text": "Cisco" }, { "code": null, "e": 71026, "s": 71016, "text": "Rockstand" }, { "code": null, "e": 71033, "s": 71026, "text": "Arrays" }, { "code": null, "e": 71043, "s": 71033, "text": "Searching" }, { "code": null, "e": 71048, "s": 71043, "text": "Heap" }, { "code": null, "e": 71146, "s": 71048, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 71169, "s": 71146, "text": "Introduction to Arrays" }, { "code": null, "e": 71201, "s": 71169, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 71222, "s": 71201, "text": "Linked List vs Array" }, { "code": null, "e": 71267, "s": 71222, "text": "Python | Using 2D arrays/lists the right way" }, { "code": null, "e": 71315, "s": 71267, "text": "Search an element in a sorted and rotated array" }, { "code": null, "e": 71324, "s": 71315, "text": "HeapSort" }, { "code": null, "e": 71336, "s": 71324, "text": "Binary Heap" }, { "code": null, "e": 71367, "s": 71336, "text": "Huffman Coding | Greedy Algo-3" }, { "code": null, "e": 71392, "s": 71367, "text": "Building Heap from Array" } ]
Angular PrimeNG Fieldset Component - GeeksforGeeks
07 Oct, 2021 Angular PrimeNG is an open-source framework with a rich set of native Angular UI components that are used for great styling and this framework is used to make responsive websites with very much ease. In this article, we will know how to use the Fieldset component in Angular PrimeNG. We will also learn about the properties, events & styling along with their syntaxes that will be used in the code. Fieldset Component: It is a grouping component that takes a header along with some content associated with that header having a toggle feature. Properties: legend: It is the header text of the fieldset. It is of string data type, the default value is null. toggleable: It specifies whether the content can be toggled by clicking the legend. It is of boolean data type, the default value is false. collapsed: It defines the default visibility state of the content. It is of boolean data type, the default value is false. style: It is an inline style of the fieldset. It is of string data type, the default value is null. styleClass: It is the style class of the fieldset. It is of string data type, the default value is null. transitionOptions: It is the transition option of the animation. It is of string data type, the default value is 400ms cubic-bezier(0.86, 0, 0.07, 1). Event: onBeforeToggle: It is a callback that is fired before content toggle. onAfterToggle: It is a callback that is fired after content toggle. Styling: p-fieldset: It is the fieldset element. p-fieldset-toggleable: It is the toggleable fieldset element. p-fieldset-legend: It is the legend element. p-fieldset-content: It is the content element. Creating Angular application & module installation: Step 1: Create an Angular application using the following command. ng new appname Step 2: After creating your project folder i.e. appname, move to it using the following command. cd appname Step 3: Install PrimeNG in your given directory. npm install primeng --save npm install primeicons --save Project Structure: It will look like the following: Example 1: This is the basic example that illustrates how to use the Fieldset component. app.component.html <h2>GeeksforGeeks</h2><h5>PrimeNG Fieldset Component</h5><p-fieldset legend="Angular PrimeNG"> <p> Angular PrimeNG is a framework used with angular to create components with great styling and this framework is very easy to use and is used to make responsive websites. </p> </p-fieldset> app.component.ts import { Component } from '@angular/core'; @Component({ selector: 'my-app', templateUrl: './app.component.html', styleUrls: ['./app.component.scss']})export class AppComponent {} app.module.ts import { NgModule } from "@angular/core";import { BrowserModule } from "@angular/platform-browser";import { BrowserAnimationsModule } from "@angular/platform-browser/animations"; import { AppComponent } from "./app.component";import { FieldsetModule } from "primeng/fieldset"; @NgModule({ imports: [BrowserModule, BrowserAnimationsModule, FieldsetModule], declarations: [AppComponent], bootstrap: [AppComponent],})export class AppModule {} Output: Example 2: In this example, we will know how to use the toggleable property in the Fieldset component. app.component.html <h2>GeeksforGeeks</h2><h5>PrimeNG Fieldset Component</h5><p-fieldset legend="Angular PrimeNG" toggleable="true"> <p> Angular PrimeNG is a framework used with angular to create components with great styling and this framework is very easy to use and is used to make responsive websites. </p></p-fieldset> app.component.ts import { Component } from '@angular/core'; @Component({ selector: 'my-app', templateUrl: './app.component.html', styleUrls: ['./app.component.scss']})export class AppComponent {} app.module.ts import { NgModule } from "@angular/core";import { BrowserModule } from "@angular/platform-browser";import { BrowserAnimationsModule } from "@angular/platform-browser/animations"; import { AppComponent } from "./app.component";import { FieldsetModule } from "primeng/fieldset"; @NgModule({ imports: [BrowserModule, BrowserAnimationsModule, FieldsetModule], declarations: [AppComponent], bootstrap: [AppComponent],})export class AppModule {} Output: Reference: https://primefaces.org/primeng/showcase/#/fieldset Angular-PrimeNG AngularJS Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Angular PrimeNG Dropdown Component Angular PrimeNG Calendar Component Angular PrimeNG Messages Component Angular 10 (blur) Event How to make a Bootstrap Modal Popup in Angular 9/8 ? Remove elements from a JavaScript Array Installation of Node.js on Linux Convert a string to an integer in JavaScript How to fetch data from an API in ReactJS ? How to insert spaces/tabs in text using HTML/CSS?
[ { "code": null, "e": 26464, "s": 26436, "text": "\n07 Oct, 2021" }, { "code": null, "e": 26863, "s": 26464, "text": "Angular PrimeNG is an open-source framework with a rich set of native Angular UI components that are used for great styling and this framework is used to make responsive websites with very much ease. In this article, we will know how to use the Fieldset component in Angular PrimeNG. We will also learn about the properties, events & styling along with their syntaxes that will be used in the code." }, { "code": null, "e": 27007, "s": 26863, "text": "Fieldset Component: It is a grouping component that takes a header along with some content associated with that header having a toggle feature." }, { "code": null, "e": 27019, "s": 27007, "text": "Properties:" }, { "code": null, "e": 27120, "s": 27019, "text": "legend: It is the header text of the fieldset. It is of string data type, the default value is null." }, { "code": null, "e": 27260, "s": 27120, "text": "toggleable: It specifies whether the content can be toggled by clicking the legend. It is of boolean data type, the default value is false." }, { "code": null, "e": 27383, "s": 27260, "text": "collapsed: It defines the default visibility state of the content. It is of boolean data type, the default value is false." }, { "code": null, "e": 27483, "s": 27383, "text": "style: It is an inline style of the fieldset. It is of string data type, the default value is null." }, { "code": null, "e": 27588, "s": 27483, "text": "styleClass: It is the style class of the fieldset. It is of string data type, the default value is null." }, { "code": null, "e": 27739, "s": 27588, "text": "transitionOptions: It is the transition option of the animation. It is of string data type, the default value is 400ms cubic-bezier(0.86, 0, 0.07, 1)." }, { "code": null, "e": 27746, "s": 27739, "text": "Event:" }, { "code": null, "e": 27816, "s": 27746, "text": "onBeforeToggle: It is a callback that is fired before content toggle." }, { "code": null, "e": 27884, "s": 27816, "text": "onAfterToggle: It is a callback that is fired after content toggle." }, { "code": null, "e": 27895, "s": 27886, "text": "Styling:" }, { "code": null, "e": 27935, "s": 27895, "text": "p-fieldset: It is the fieldset element." }, { "code": null, "e": 27997, "s": 27935, "text": "p-fieldset-toggleable: It is the toggleable fieldset element." }, { "code": null, "e": 28042, "s": 27997, "text": "p-fieldset-legend: It is the legend element." }, { "code": null, "e": 28089, "s": 28042, "text": "p-fieldset-content: It is the content element." }, { "code": null, "e": 28141, "s": 28089, "text": "Creating Angular application & module installation:" }, { "code": null, "e": 28208, "s": 28141, "text": "Step 1: Create an Angular application using the following command." }, { "code": null, "e": 28223, "s": 28208, "text": "ng new appname" }, { "code": null, "e": 28320, "s": 28223, "text": "Step 2: After creating your project folder i.e. appname, move to it using the following command." }, { "code": null, "e": 28331, "s": 28320, "text": "cd appname" }, { "code": null, "e": 28380, "s": 28331, "text": "Step 3: Install PrimeNG in your given directory." }, { "code": null, "e": 28437, "s": 28380, "text": "npm install primeng --save\nnpm install primeicons --save" }, { "code": null, "e": 28489, "s": 28437, "text": "Project Structure: It will look like the following:" }, { "code": null, "e": 28578, "s": 28489, "text": "Example 1: This is the basic example that illustrates how to use the Fieldset component." }, { "code": null, "e": 28597, "s": 28578, "text": "app.component.html" }, { "code": "<h2>GeeksforGeeks</h2><h5>PrimeNG Fieldset Component</h5><p-fieldset legend=\"Angular PrimeNG\"> <p> Angular PrimeNG is a framework used with angular to create components with great styling and this framework is very easy to use and is used to make responsive websites. </p> </p-fieldset>", "e": 28906, "s": 28597, "text": null }, { "code": null, "e": 28923, "s": 28906, "text": "app.component.ts" }, { "code": "import { Component } from '@angular/core'; @Component({ selector: 'my-app', templateUrl: './app.component.html', styleUrls: ['./app.component.scss']})export class AppComponent {}", "e": 29106, "s": 28923, "text": null }, { "code": null, "e": 29122, "s": 29108, "text": "app.module.ts" }, { "code": "import { NgModule } from \"@angular/core\";import { BrowserModule } from \"@angular/platform-browser\";import { BrowserAnimationsModule } from \"@angular/platform-browser/animations\"; import { AppComponent } from \"./app.component\";import { FieldsetModule } from \"primeng/fieldset\"; @NgModule({ imports: [BrowserModule, BrowserAnimationsModule, FieldsetModule], declarations: [AppComponent], bootstrap: [AppComponent],})export class AppModule {}", "e": 29597, "s": 29122, "text": null }, { "code": null, "e": 29605, "s": 29597, "text": "Output:" }, { "code": null, "e": 29708, "s": 29605, "text": "Example 2: In this example, we will know how to use the toggleable property in the Fieldset component." }, { "code": null, "e": 29727, "s": 29708, "text": "app.component.html" }, { "code": "<h2>GeeksforGeeks</h2><h5>PrimeNG Fieldset Component</h5><p-fieldset legend=\"Angular PrimeNG\" toggleable=\"true\"> <p> Angular PrimeNG is a framework used with angular to create components with great styling and this framework is very easy to use and is used to make responsive websites. </p></p-fieldset>", "e": 30050, "s": 29727, "text": null }, { "code": null, "e": 30067, "s": 30050, "text": "app.component.ts" }, { "code": "import { Component } from '@angular/core'; @Component({ selector: 'my-app', templateUrl: './app.component.html', styleUrls: ['./app.component.scss']})export class AppComponent {}", "e": 30250, "s": 30067, "text": null }, { "code": null, "e": 30264, "s": 30250, "text": "app.module.ts" }, { "code": "import { NgModule } from \"@angular/core\";import { BrowserModule } from \"@angular/platform-browser\";import { BrowserAnimationsModule } from \"@angular/platform-browser/animations\"; import { AppComponent } from \"./app.component\";import { FieldsetModule } from \"primeng/fieldset\"; @NgModule({ imports: [BrowserModule, BrowserAnimationsModule, FieldsetModule], declarations: [AppComponent], bootstrap: [AppComponent],})export class AppModule {}", "e": 30739, "s": 30264, "text": null }, { "code": null, "e": 30747, "s": 30739, "text": "Output:" }, { "code": null, "e": 30809, "s": 30747, "text": "Reference: https://primefaces.org/primeng/showcase/#/fieldset" }, { "code": null, "e": 30825, "s": 30809, "text": "Angular-PrimeNG" }, { "code": null, "e": 30835, "s": 30825, "text": "AngularJS" }, { "code": null, "e": 30852, "s": 30835, "text": "Web Technologies" }, { "code": null, "e": 30950, "s": 30852, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30985, "s": 30950, "text": "Angular PrimeNG Dropdown Component" }, { "code": null, "e": 31020, "s": 30985, "text": "Angular PrimeNG Calendar Component" }, { "code": null, "e": 31055, "s": 31020, "text": "Angular PrimeNG Messages Component" }, { "code": null, "e": 31079, "s": 31055, "text": "Angular 10 (blur) Event" }, { "code": null, "e": 31132, "s": 31079, "text": "How to make a Bootstrap Modal Popup in Angular 9/8 ?" }, { "code": null, "e": 31172, "s": 31132, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 31205, "s": 31172, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 31250, "s": 31205, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 31293, "s": 31250, "text": "How to fetch data from an API in ReactJS ?" } ]
Extract First and last N rows from PySpark DataFrame - GeeksforGeeks
06 Jun, 2021 In this article, we are going to get the extract first N rows and Last N rows from the dataframe using PySpark in Python. To do our task first we will create a sample dataframe. We have to create a spark object with the help of the spark session and give the app name by using getorcreate() method. spark = SparkSession.builder.appName('sparkdf').getOrCreate() Finally, after creating the data with the list and column list to the method: dataframe = spark.createDataFrame(data, columns) Python3 # importing moduleimport pyspark # importing sparksession from pyspark.sql modulefrom pyspark.sql import SparkSession # creating sparksession and giving an app namespark = SparkSession.builder.appName('sparkdf').getOrCreate() # list of employee data with 5 row valuesdata = [["1", "sravan", "company 1"], ["2", "ojaswi", "company 2"], ["3", "bobby", "company 3"], ["4", "rohith", "company 2"], ["5", "gnanesh", "company 1"]] # specify column namescolumns = ['Employee ID', 'Employee NAME', 'Company Name'] # creating a dataframe from the lists of datadataframe = spark.createDataFrame(data, columns) print('Actual data in dataframe')dataframe.show() Output: We can extract the first N rows by using several methods which are discussed below with the help of some examples: Method 1: Using head() This function is used to extract top N rows in the given dataframe Syntax: dataframe.head(n) where, n specifies the number of rows to be extracted from first dataframe is the dataframe name created from the nested lists using pyspark. Python3 print("Top 2 rows ") # extract top 2 rowsa = dataframe.head(2)print(a) print("Top 1 row ") # extract top 1 rowa = dataframe.head(1)print(a) Output: Top 2 rows [Row(Employee ID=’1′, Employee NAME=’sravan’, Company Name=’company 1′), Row(Employee ID=’2′, Employee NAME=’ojaswi’, Company Name=’company 2′)] Top 1 row [Row(Employee ID=’1′, Employee NAME=’sravan’, Company Name=’company 1′)] Method 2: Using first() This function is used to extract only one row in the dataframe. Syntax: dataframe.first() It doesn’t take any parameter dataframe is the dataframe name created from the nested lists using pyspark Python3 print("Top row ") # extract top rowa = dataframe.first()print(a) Output: Top row Row(Employee ID=’1′, Employee NAME=’sravan’, Company Name=’company 1′) Method 3: Using show() Used to display the dataframe from top to bottom by default. Syntax: dataframe.show(n) where, dataframe is the input dataframe n is the number of rows to be displayed from the top ,if n is not specified it will print entire rows in the dataframe Python3 # show() function to get # 2 rowsdataframe.show(2) Output: Extracting the last rows means getting the last N rows from the given dataframe. For this, we are using tail() function and can get the last N rows Syntax: dataframe.tail(n) where, n is the number to get last n rows data frame is the input dataframe Example: Python3 print("Last 2 rows ") # extract last 2 rowsa = dataframe.tail(2)print(a) print("Last 1 row ") # extract last 1 rowa = dataframe.tail(1)print(a) Output: Last 2 rows [Row(Employee ID=’4′, Employee NAME=’rohith’, Company Name=’company 2′), Row(Employee ID=’5′, Employee NAME=’gnanesh’, Company Name=’company 1′)] Last 1 row [Row(Employee ID=’5′, Employee NAME=’gnanesh’, Company Name=’company 1′)] Picked Python-Pyspark Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? How To Convert Python Dictionary To JSON? Check if element exists in list in Python How to drop one or multiple columns in Pandas Dataframe Python Classes and Objects Python | os.path.join() method Create a directory in Python Defaultdict in Python Python | Get unique values from a list Python | Pandas dataframe.groupby()
[ { "code": null, "e": 25665, "s": 25637, "text": "\n06 Jun, 2021" }, { "code": null, "e": 25843, "s": 25665, "text": "In this article, we are going to get the extract first N rows and Last N rows from the dataframe using PySpark in Python. To do our task first we will create a sample dataframe." }, { "code": null, "e": 25964, "s": 25843, "text": "We have to create a spark object with the help of the spark session and give the app name by using getorcreate() method." }, { "code": null, "e": 26026, "s": 25964, "text": "spark = SparkSession.builder.appName('sparkdf').getOrCreate()" }, { "code": null, "e": 26104, "s": 26026, "text": "Finally, after creating the data with the list and column list to the method:" }, { "code": null, "e": 26153, "s": 26104, "text": "dataframe = spark.createDataFrame(data, columns)" }, { "code": null, "e": 26161, "s": 26153, "text": "Python3" }, { "code": "# importing moduleimport pyspark # importing sparksession from pyspark.sql modulefrom pyspark.sql import SparkSession # creating sparksession and giving an app namespark = SparkSession.builder.appName('sparkdf').getOrCreate() # list of employee data with 5 row valuesdata = [[\"1\", \"sravan\", \"company 1\"], [\"2\", \"ojaswi\", \"company 2\"], [\"3\", \"bobby\", \"company 3\"], [\"4\", \"rohith\", \"company 2\"], [\"5\", \"gnanesh\", \"company 1\"]] # specify column namescolumns = ['Employee ID', 'Employee NAME', 'Company Name'] # creating a dataframe from the lists of datadataframe = spark.createDataFrame(data, columns) print('Actual data in dataframe')dataframe.show()", "e": 26846, "s": 26161, "text": null }, { "code": null, "e": 26854, "s": 26846, "text": "Output:" }, { "code": null, "e": 26969, "s": 26854, "text": "We can extract the first N rows by using several methods which are discussed below with the help of some examples:" }, { "code": null, "e": 26992, "s": 26969, "text": "Method 1: Using head()" }, { "code": null, "e": 27059, "s": 26992, "text": "This function is used to extract top N rows in the given dataframe" }, { "code": null, "e": 27085, "s": 27059, "text": "Syntax: dataframe.head(n)" }, { "code": null, "e": 27093, "s": 27085, "text": "where, " }, { "code": null, "e": 27151, "s": 27093, "text": "n specifies the number of rows to be extracted from first" }, { "code": null, "e": 27228, "s": 27151, "text": "dataframe is the dataframe name created from the nested lists using pyspark." }, { "code": null, "e": 27236, "s": 27228, "text": "Python3" }, { "code": "print(\"Top 2 rows \") # extract top 2 rowsa = dataframe.head(2)print(a) print(\"Top 1 row \") # extract top 1 rowa = dataframe.head(1)print(a)", "e": 27379, "s": 27236, "text": null }, { "code": null, "e": 27387, "s": 27379, "text": "Output:" }, { "code": null, "e": 27400, "s": 27387, "text": "Top 2 rows " }, { "code": null, "e": 27474, "s": 27400, "text": "[Row(Employee ID=’1′, Employee NAME=’sravan’, Company Name=’company 1′), " }, { "code": null, "e": 27546, "s": 27474, "text": "Row(Employee ID=’2′, Employee NAME=’ojaswi’, Company Name=’company 2′)]" }, { "code": null, "e": 27558, "s": 27546, "text": "Top 1 row " }, { "code": null, "e": 27631, "s": 27558, "text": "[Row(Employee ID=’1′, Employee NAME=’sravan’, Company Name=’company 1′)]" }, { "code": null, "e": 27655, "s": 27631, "text": "Method 2: Using first()" }, { "code": null, "e": 27719, "s": 27655, "text": "This function is used to extract only one row in the dataframe." }, { "code": null, "e": 27745, "s": 27719, "text": "Syntax: dataframe.first()" }, { "code": null, "e": 27775, "s": 27745, "text": "It doesn’t take any parameter" }, { "code": null, "e": 27851, "s": 27775, "text": "dataframe is the dataframe name created from the nested lists using pyspark" }, { "code": null, "e": 27859, "s": 27851, "text": "Python3" }, { "code": "print(\"Top row \") # extract top rowa = dataframe.first()print(a)", "e": 27926, "s": 27859, "text": null }, { "code": null, "e": 27934, "s": 27926, "text": "Output:" }, { "code": null, "e": 27944, "s": 27934, "text": "Top row " }, { "code": null, "e": 28015, "s": 27944, "text": "Row(Employee ID=’1′, Employee NAME=’sravan’, Company Name=’company 1′)" }, { "code": null, "e": 28039, "s": 28015, "text": "Method 3: Using show() " }, { "code": null, "e": 28100, "s": 28039, "text": "Used to display the dataframe from top to bottom by default." }, { "code": null, "e": 28126, "s": 28100, "text": "Syntax: dataframe.show(n)" }, { "code": null, "e": 28133, "s": 28126, "text": "where," }, { "code": null, "e": 28166, "s": 28133, "text": "dataframe is the input dataframe" }, { "code": null, "e": 28285, "s": 28166, "text": "n is the number of rows to be displayed from the top ,if n is not specified it will print entire rows in the dataframe" }, { "code": null, "e": 28293, "s": 28285, "text": "Python3" }, { "code": "# show() function to get # 2 rowsdataframe.show(2)", "e": 28344, "s": 28293, "text": null }, { "code": null, "e": 28352, "s": 28344, "text": "Output:" }, { "code": null, "e": 28500, "s": 28352, "text": "Extracting the last rows means getting the last N rows from the given dataframe. For this, we are using tail() function and can get the last N rows" }, { "code": null, "e": 28526, "s": 28500, "text": "Syntax: dataframe.tail(n)" }, { "code": null, "e": 28533, "s": 28526, "text": "where," }, { "code": null, "e": 28568, "s": 28533, "text": "n is the number to get last n rows" }, { "code": null, "e": 28602, "s": 28568, "text": "data frame is the input dataframe" }, { "code": null, "e": 28611, "s": 28602, "text": "Example:" }, { "code": null, "e": 28619, "s": 28611, "text": "Python3" }, { "code": "print(\"Last 2 rows \") # extract last 2 rowsa = dataframe.tail(2)print(a) print(\"Last 1 row \") # extract last 1 rowa = dataframe.tail(1)print(a)", "e": 28766, "s": 28619, "text": null }, { "code": null, "e": 28774, "s": 28766, "text": "Output:" }, { "code": null, "e": 28788, "s": 28774, "text": "Last 2 rows " }, { "code": null, "e": 28862, "s": 28788, "text": "[Row(Employee ID=’4′, Employee NAME=’rohith’, Company Name=’company 2′), " }, { "code": null, "e": 28935, "s": 28862, "text": "Row(Employee ID=’5′, Employee NAME=’gnanesh’, Company Name=’company 1′)]" }, { "code": null, "e": 28948, "s": 28935, "text": "Last 1 row " }, { "code": null, "e": 29022, "s": 28948, "text": "[Row(Employee ID=’5′, Employee NAME=’gnanesh’, Company Name=’company 1′)]" }, { "code": null, "e": 29029, "s": 29022, "text": "Picked" }, { "code": null, "e": 29044, "s": 29029, "text": "Python-Pyspark" }, { "code": null, "e": 29051, "s": 29044, "text": "Python" }, { "code": null, "e": 29149, "s": 29051, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29181, "s": 29149, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 29223, "s": 29181, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 29265, "s": 29223, "text": "Check if element exists in list in Python" }, { "code": null, "e": 29321, "s": 29265, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 29348, "s": 29321, "text": "Python Classes and Objects" }, { "code": null, "e": 29379, "s": 29348, "text": "Python | os.path.join() method" }, { "code": null, "e": 29408, "s": 29379, "text": "Create a directory in Python" }, { "code": null, "e": 29430, "s": 29408, "text": "Defaultdict in Python" }, { "code": null, "e": 29469, "s": 29430, "text": "Python | Get unique values from a list" } ]
Android Online Quiz
Following quiz provides Multiple Choice Questions (MCQs) related to Android. You will have to read all the given answers and click over the correct answer. If you are not sure about the answer then you can check the answer using Show Answer button. You can use Next Quiz button to check new set of questions in the quiz. Q 1 - How to pass the data between activities in Android? A - Intent B - Content Provider C - Broadcast receiver D - None of the Above An Intent is used to connect one activity to another activity and having a message passing mechanism between activities. Q 2 - What is Manifest.xml in android? A - It has information about layout in an application B - It has the information about activities in an application C - It has all the information about an application D - None of the above Manifest.xml is having information about application as number components in your application,Activity information,service information, and icon about an application Each application has at least one Manifest file. Without manifest file we can't generate the APK file. Q 3 -What are the return values of onStartCommand() in android services? A - START_STICKY B - START_NOT_STICKY C - START_REDELIVER_INTENT D - All of the above E - None of the above START_STICKY − If android stops services forcefully, using with START_STICKY, it can be restarted automatically without the user interaction. START_NOT_STICKY − If android stops services forcefully, it will not restart services till user start services. START_REDELIVER_INTENT − If android stops services forcefully, it will restart services by re-sending an intent. Q 4 - What is the life cycle of broadcast receivers in android? A - send intent() B - onRecieve() C - implicitBroadcast() D - sendBroadcast(), sendOrderBroadcast(), and sendStickyBroadcast(). Broadcast receiver has only onReceive() method. Broadcast starts from onRecieve() and control comes out from onRecieve(). Q 5 - What are the wake locks available in android? A - PARTIAL_WAKE_LOCK B - SCREEN_DIM_WAKE_LOCK C - SCREEN_BRIGHT_WAKE_LOCK D - FULL_WAKE_LOCK E - FULL_WAKE_LOCK When CPU is on mode, PARTIAL_WAKE_LOCK will be active. When CPU + bright Screen low is on mode, SCREEN_DIM_WAKE_LOCK will be active. When CPU + bright Screen High is on mode,SCREEN_BRIGHT_WAKE_LOCK will be active. When CPU, Screen, bright Screen High is on mode, FULL_WAKE_LOCK will be active. Q 6 - What is DDMS in android? A - Dalvik memory server B - Device memory server C - Dalvik monitoring services D - Dalvik debug monitor services DDMS provides port forwarding, screen capturing, memory mapping, logcat, calls, SMS etc. Q 7 - What is an HTTP client class in android? A - httprequest(get/post) and returns response from the server B - Cookies management C - Authentication management D - None of the above Http request has get and post methods and it returns the response from the servers. Q 8 - What is fragment life cycle in android? A - onReceive() B - onCreate() C - onAttach()->onCreate() −> onCreateView() −> onActivityCreated() −> onStart() −> onResume() D - None of the above Fragment life cycle is as shown below − onAttach() OnCreate() onCreateView() onActivityCreated() onStart() onResume() onPause() onStop() onDestroyView() onDestroy() onDetach() Q 9 - Is it mandatory to call onCreate() and onStart() in android? A - No, we can write the program without writing onCreate() and onStart() B - Yes, we should call onCreate() and onStart() to write the program C - At least we need to call onCreate() once D - None of the above It is not mandatory, the program will work perfectly without fail, but the programmer has to implement the life cycle of activity. Q 10 - Can a class be immutable in android? A - No, it can't B - Yes, Class can be immutable C - Can't make the class as final class D - None of the above Class can be immutable. 46 Lectures 7.5 hours Aditya Dua 32 Lectures 3.5 hours Sharad Kumar 9 Lectures 1 hours Abhilash Nelson 14 Lectures 1.5 hours Abhilash Nelson 15 Lectures 1.5 hours Abhilash Nelson 10 Lectures 1 hours Abhilash Nelson Print Add Notes Bookmark this page
[ { "code": null, "e": 3928, "s": 3607, "text": "Following quiz provides Multiple Choice Questions (MCQs) related to Android. You will have to read all the given answers and click over the correct answer. If you are not sure about the answer then you can check the answer using Show Answer button. You can use Next Quiz button to check new set of questions in the quiz." }, { "code": null, "e": 3986, "s": 3928, "text": "Q 1 - How to pass the data between activities in Android?" }, { "code": null, "e": 3997, "s": 3986, "text": "A - Intent" }, { "code": null, "e": 4018, "s": 3997, "text": "B - Content Provider" }, { "code": null, "e": 4041, "s": 4018, "text": "C - Broadcast receiver" }, { "code": null, "e": 4064, "s": 4041, "text": "D - None of the Above " }, { "code": null, "e": 4185, "s": 4064, "text": "An Intent is used to connect one activity to another activity and having a message passing mechanism between activities." }, { "code": null, "e": 4224, "s": 4185, "text": "Q 2 - What is Manifest.xml in android?" }, { "code": null, "e": 4278, "s": 4224, "text": "A - It has information about layout in an application" }, { "code": null, "e": 4340, "s": 4278, "text": "B - It has the information about activities in an application" }, { "code": null, "e": 4392, "s": 4340, "text": "C - It has all the information about an application" }, { "code": null, "e": 4414, "s": 4392, "text": "D - None of the above" }, { "code": null, "e": 4580, "s": 4414, "text": "Manifest.xml is having information about application as number components in your application,Activity information,service information, and icon about an application" }, { "code": null, "e": 4683, "s": 4580, "text": "Each application has at least one Manifest file. Without manifest file we can't generate the APK file." }, { "code": null, "e": 4756, "s": 4683, "text": "Q 3 -What are the return values of onStartCommand() in android services?" }, { "code": null, "e": 4773, "s": 4756, "text": "A - START_STICKY" }, { "code": null, "e": 4794, "s": 4773, "text": "B - START_NOT_STICKY" }, { "code": null, "e": 4821, "s": 4794, "text": "C - START_REDELIVER_INTENT" }, { "code": null, "e": 4842, "s": 4821, "text": "D - All of the above" }, { "code": null, "e": 4865, "s": 4842, "text": "E - None of the above " }, { "code": null, "e": 5007, "s": 4865, "text": "START_STICKY − If android stops services forcefully, using with START_STICKY, it can be restarted automatically without the user interaction." }, { "code": null, "e": 5119, "s": 5007, "text": "START_NOT_STICKY − If android stops services forcefully, it will not restart services till user start services." }, { "code": null, "e": 5232, "s": 5119, "text": "START_REDELIVER_INTENT − If android stops services forcefully, it will restart services by re-sending an intent." }, { "code": null, "e": 5296, "s": 5232, "text": "Q 4 - What is the life cycle of broadcast receivers in android?" }, { "code": null, "e": 5314, "s": 5296, "text": "A - send intent()" }, { "code": null, "e": 5330, "s": 5314, "text": "B - onRecieve()" }, { "code": null, "e": 5354, "s": 5330, "text": "C - implicitBroadcast()" }, { "code": null, "e": 5424, "s": 5354, "text": "D - sendBroadcast(), sendOrderBroadcast(), and sendStickyBroadcast()." }, { "code": null, "e": 5546, "s": 5424, "text": "Broadcast receiver has only onReceive() method. Broadcast starts from onRecieve() and control comes out from onRecieve()." }, { "code": null, "e": 5598, "s": 5546, "text": "Q 5 - What are the wake locks available in android?" }, { "code": null, "e": 5620, "s": 5598, "text": "A - PARTIAL_WAKE_LOCK" }, { "code": null, "e": 5645, "s": 5620, "text": "B - SCREEN_DIM_WAKE_LOCK" }, { "code": null, "e": 5673, "s": 5645, "text": "C - SCREEN_BRIGHT_WAKE_LOCK" }, { "code": null, "e": 5693, "s": 5673, "text": "D - FULL_WAKE_LOCK " }, { "code": null, "e": 5713, "s": 5693, "text": "E - FULL_WAKE_LOCK " }, { "code": null, "e": 5768, "s": 5713, "text": "When CPU is on mode, PARTIAL_WAKE_LOCK will be active." }, { "code": null, "e": 5847, "s": 5768, "text": "When CPU + bright Screen low is on mode, SCREEN_DIM_WAKE_LOCK will be active." }, { "code": null, "e": 5928, "s": 5847, "text": "When CPU + bright Screen High is on mode,SCREEN_BRIGHT_WAKE_LOCK will be active." }, { "code": null, "e": 6008, "s": 5928, "text": "When CPU, Screen, bright Screen High is on mode, FULL_WAKE_LOCK will be active." }, { "code": null, "e": 6039, "s": 6008, "text": "Q 6 - What is DDMS in android?" }, { "code": null, "e": 6064, "s": 6039, "text": "A - Dalvik memory server" }, { "code": null, "e": 6090, "s": 6064, "text": "B - Device memory server " }, { "code": null, "e": 6121, "s": 6090, "text": "C - Dalvik monitoring services" }, { "code": null, "e": 6155, "s": 6121, "text": "D - Dalvik debug monitor services" }, { "code": null, "e": 6244, "s": 6155, "text": "DDMS provides port forwarding, screen capturing, memory mapping, logcat, calls, SMS etc." }, { "code": null, "e": 6291, "s": 6244, "text": "Q 7 - What is an HTTP client class in android?" }, { "code": null, "e": 6354, "s": 6291, "text": "A - httprequest(get/post) and returns response from the server" }, { "code": null, "e": 6378, "s": 6354, "text": "B - Cookies management" }, { "code": null, "e": 6408, "s": 6378, "text": "C - Authentication management" }, { "code": null, "e": 6430, "s": 6408, "text": "D - None of the above" }, { "code": null, "e": 6514, "s": 6430, "text": "Http request has get and post methods and it returns the response from the servers." }, { "code": null, "e": 6560, "s": 6514, "text": "Q 8 - What is fragment life cycle in android?" }, { "code": null, "e": 6576, "s": 6560, "text": "A - onReceive()" }, { "code": null, "e": 6592, "s": 6576, "text": "B - onCreate() " }, { "code": null, "e": 6687, "s": 6592, "text": "C - onAttach()->onCreate() −> onCreateView() −> onActivityCreated() −> onStart() −> onResume()" }, { "code": null, "e": 6709, "s": 6687, "text": "D - None of the above" }, { "code": null, "e": 6749, "s": 6709, "text": "Fragment life cycle is as shown below −" }, { "code": null, "e": 6885, "s": 6749, "text": "onAttach()\nOnCreate()\nonCreateView()\nonActivityCreated()\nonStart()\nonResume()\nonPause()\nonStop()\nonDestroyView()\nonDestroy()\nonDetach()" }, { "code": null, "e": 6952, "s": 6885, "text": "Q 9 - Is it mandatory to call onCreate() and onStart() in android?" }, { "code": null, "e": 7027, "s": 6952, "text": "A - No, we can write the program without writing onCreate() and onStart() " }, { "code": null, "e": 7097, "s": 7027, "text": "B - Yes, we should call onCreate() and onStart() to write the program" }, { "code": null, "e": 7142, "s": 7097, "text": "C - At least we need to call onCreate() once" }, { "code": null, "e": 7164, "s": 7142, "text": "D - None of the above" }, { "code": null, "e": 7295, "s": 7164, "text": "It is not mandatory, the program will work perfectly without fail, but the programmer has to implement the life cycle of activity." }, { "code": null, "e": 7339, "s": 7295, "text": "Q 10 - Can a class be immutable in android?" }, { "code": null, "e": 7358, "s": 7339, "text": "A - No, it can't " }, { "code": null, "e": 7390, "s": 7358, "text": "B - Yes, Class can be immutable" }, { "code": null, "e": 7430, "s": 7390, "text": "C - Can't make the class as final class" }, { "code": null, "e": 7452, "s": 7430, "text": "D - None of the above" }, { "code": null, "e": 7476, "s": 7452, "text": "Class can be immutable." }, { "code": null, "e": 7511, "s": 7476, "text": "\n 46 Lectures \n 7.5 hours \n" }, { "code": null, "e": 7523, "s": 7511, "text": " Aditya Dua" }, { "code": null, "e": 7558, "s": 7523, "text": "\n 32 Lectures \n 3.5 hours \n" }, { "code": null, "e": 7572, "s": 7558, "text": " Sharad Kumar" }, { "code": null, "e": 7604, "s": 7572, "text": "\n 9 Lectures \n 1 hours \n" }, { "code": null, "e": 7621, "s": 7604, "text": " Abhilash Nelson" }, { "code": null, "e": 7656, "s": 7621, "text": "\n 14 Lectures \n 1.5 hours \n" }, { "code": null, "e": 7673, "s": 7656, "text": " Abhilash Nelson" }, { "code": null, "e": 7708, "s": 7673, "text": "\n 15 Lectures \n 1.5 hours \n" }, { "code": null, "e": 7725, "s": 7708, "text": " Abhilash Nelson" }, { "code": null, "e": 7758, "s": 7725, "text": "\n 10 Lectures \n 1 hours \n" }, { "code": null, "e": 7775, "s": 7758, "text": " Abhilash Nelson" }, { "code": null, "e": 7782, "s": 7775, "text": " Print" }, { "code": null, "e": 7793, "s": 7782, "text": " Add Notes" } ]
Fix: ERROR 1396 (HY000): Operation CREATE USER failed in MySQL?
To fix the error, let us see how to create a user correctly. Let us create a user − mysql> create user 'Emma'@'localhost' IDENTIFIED BY 'emma_654'; Query OK, 0 rows affected (0.00 sec) Let us display all users along with host − mysql> select user,host from MySQL.user; This will produce the following output. The new user created above is visible in the below list of all users along with host − +------------------+-----------+ | user | host | +------------------+-----------+ | Bob | % | | Charlie | % | | Robert | % | | User2 | % | | mysql.infoschema | % | | mysql.session | % | | mysql.sys | % | | root | % | | @UserName@ | localhost | | Adam | localhost | | Adam Smith | localhost | | Chris | localhost | | David | localhost | | Emma | localhost | | Jace | localhost | | James | localhost | | John | localhost | | John Doe | localhost | | Michael | localhost | | Mike | localhost | | Robert | localhost | | User1 | localhost | | am | localhost | | hbstudent | localhost | | mysql.infoschema | localhost | | mysql.session | localhost | +------------------+-----------+ 26 rows in set (0.00 sec)
[ { "code": null, "e": 1146, "s": 1062, "text": "To fix the error, let us see how to create a user correctly. Let us create a user −" }, { "code": null, "e": 1247, "s": 1146, "text": "mysql> create user 'Emma'@'localhost' IDENTIFIED BY 'emma_654';\nQuery OK, 0 rows affected (0.00 sec)" }, { "code": null, "e": 1290, "s": 1247, "text": "Let us display all users along with host −" }, { "code": null, "e": 1331, "s": 1290, "text": "mysql> select user,host from MySQL.user;" }, { "code": null, "e": 1458, "s": 1331, "text": "This will produce the following output. The new user created above is visible in the below list of all users along with host −" }, { "code": null, "e": 2474, "s": 1458, "text": "+------------------+-----------+\n| user | host |\n+------------------+-----------+\n| Bob | % |\n| Charlie | % |\n| Robert | % |\n| User2 | % |\n| mysql.infoschema | % |\n| mysql.session | % |\n| mysql.sys | % |\n| root | % |\n| @UserName@ | localhost |\n| Adam | localhost |\n| Adam Smith | localhost |\n| Chris | localhost |\n| David | localhost |\n| Emma | localhost |\n| Jace | localhost |\n| James | localhost |\n| John | localhost |\n| John Doe | localhost |\n| Michael | localhost |\n| Mike | localhost |\n| Robert | localhost |\n| User1 | localhost |\n| am | localhost |\n| hbstudent | localhost |\n| mysql.infoschema | localhost |\n| mysql.session | localhost |\n+------------------+-----------+\n26 rows in set (0.00 sec)" } ]
Multi Label Text Classification with Scikit-Learn | by Susan Li | Towards Data Science
Multi-class classification means a classification task with more than two classes; each label are mutually exclusive. The classification makes the assumption that each sample is assigned to one and only one label. On the other hand, Multi-label classification assigns to each sample a set of target labels. This can be thought as predicting properties of a data-point that are not mutually exclusive, such as Tim Horton are often categorized as both bakery and coffee shop. Multi-label text classification has many real world applications such as categorizing businesses on Yelp or classifying movies into one or more genre(s). Anyone who has been the target of abuse or harassment online will know that it doesn’t go away when you log off or switch off your phone. Researchers at Google are working on tools to study toxic comments online. In this post, we will build a multi-label model that’s capable of detecting different types of toxicity like severe toxic, threats, obscenity, insults, and so on. We will be using supervised classifiers and text representations. A toxic comment might be about any of toxic, severe toxic, obscene, threat, insult or identity hate at the same time or none of the above. The data set can be found at Kaggle. (Disclaimer from the data source: the dataset contains text that may be considered profane, vulgar, or offensive.) %matplotlib inlineimport reimport matplotlibimport numpy as npimport matplotlib.pyplot as pltimport pandas as pdfrom sklearn.model_selection import train_test_splitfrom sklearn.feature_extraction.text import TfidfVectorizerfrom sklearn.naive_bayes import MultinomialNBfrom sklearn.metrics import accuracy_scorefrom sklearn.multiclass import OneVsRestClassifierfrom nltk.corpus import stopwordsstop_words = set(stopwords.words('english'))from sklearn.svm import LinearSVCfrom sklearn.linear_model import LogisticRegressionfrom sklearn.pipeline import Pipelineimport seaborn as snsdf = pd.read_csv("train 2.csv", encoding = "ISO-8859-1")df.head() Number of comments in each category df_toxic = df.drop(['id', 'comment_text'], axis=1)counts = []categories = list(df_toxic.columns.values)for i in categories: counts.append((i, df_toxic[i].sum()))df_stats = pd.DataFrame(counts, columns=['category', 'number_of_comments'])df_stats df_stats.plot(x='category', y='number_of_comments', kind='bar', legend=False, grid=True, figsize=(8, 5))plt.title("Number of comments per category")plt.ylabel('# of Occurrences', fontsize=12)plt.xlabel('category', fontsize=12) How many comments have multi labels? rowsums = df.iloc[:,2:].sum(axis=1)x=rowsums.value_counts()#plotplt.figure(figsize=(8,5))ax = sns.barplot(x.index, x.values)plt.title("Multiple categories per comment")plt.ylabel('# of Occurrences', fontsize=12)plt.xlabel('# of categories', fontsize=12) Vast majority of the comment text are not labeled. print('Percentage of comments that are not labelled:')print(len(df[(df['toxic']==0) & (df['severe_toxic']==0) & (df['obscene']==0) & (df['threat']== 0) & (df['insult']==0) & (df['identity_hate']==0)]) / len(df)) Percentage of comments that are not labelled:0.8983211235124177 The distribution of the number of words in comment texts. lens = df.comment_text.str.len()lens.hist(bins = np.arange(0,5000,50)) Most of the comment text length are within 500 characters, with some outliers up to 5,000 characters long. There is no missing comment in comment text column. print('Number of missing comments in comment text:')df['comment_text'].isnull().sum() Number of missing comments in comment text: 0 Have a peek the first comment, the text needs to be cleaned. df['comment_text'][0] “Explanation\rWhy the edits made under my username Hardcore Metallica Fan were reverted? They weren’t vandalisms, just closure on some GAs after I voted at New York Dolls FAC. And please don’t remove the template from the talk page since I’m retired now.89.205.38.27” Create a function to clean the text def clean_text(text): text = text.lower() text = re.sub(r"what's", "what is ", text) text = re.sub(r"\'s", " ", text) text = re.sub(r"\'ve", " have ", text) text = re.sub(r"can't", "can not ", text) text = re.sub(r"n't", " not ", text) text = re.sub(r"i'm", "i am ", text) text = re.sub(r"\'re", " are ", text) text = re.sub(r"\'d", " would ", text) text = re.sub(r"\'ll", " will ", text) text = re.sub(r"\'scuse", " excuse ", text) text = re.sub('\W', ' ', text) text = re.sub('\s+', ' ', text) text = text.strip(' ') return text Clean up comment_text column: df['comment_text'] = df['comment_text'].map(lambda com : clean_text(com))df['comment_text'][0] ‘explanation why the edits made under my username hardcore metallica fan were reverted they were not vandalisms just closure on some gas after i voted at new york dolls fac and please do not remove the template from the talk page since i am retired now 89 205 38 27’ Much better! Split the data to train and test sets: categories = ['toxic', 'severe_toxic', 'obscene', 'threat', 'insult', 'identity_hate']train, test = train_test_split(df, random_state=42, test_size=0.33, shuffle=True)X_train = train.comment_textX_test = test.comment_textprint(X_train.shape)print(X_test.shape) (106912,)(52659,) Scikit-learn provides a pipeline utility to help automate machine learning workflows. Pipelines are very common in Machine Learning systems, since there is a lot of data to manipulate and many data transformations to apply. So we will utilize pipeline to train every classifier. The Multi-label algorithm accepts a binary mask over multiple labels. The result for each prediction will be an array of 0s and 1s marking which class labels apply to each row input sample. OneVsRest strategy can be used for multi-label learning, where a classifier is used to predict multiple labels for instance. Naive Bayes supports multi-class, but we are in a multi-label scenario, therefore, we wrap Naive Bayes in the OneVsRestClassifier. # Define a pipeline combining a text feature extractor with multi lable classifierNB_pipeline = Pipeline([ ('tfidf', TfidfVectorizer(stop_words=stop_words)), ('clf', OneVsRestClassifier(MultinomialNB( fit_prior=True, class_prior=None))), ])for category in categories: print('... Processing {}'.format(category)) # train the model using X_dtm & y NB_pipeline.fit(X_train, train[category]) # compute the testing accuracy prediction = NB_pipeline.predict(X_test) print('Test accuracy is {}'.format(accuracy_score(test[category], prediction))) ... Processing toxicTest accuracy is 0.9191401279933155... Processing severe_toxicTest accuracy is 0.9900112041626312... Processing obsceneTest accuracy is 0.9514802787747584... Processing threatTest accuracy is 0.9971135038644866... Processing insultTest accuracy is 0.9517271501547694... Processing identity_hateTest accuracy is 0.9910556600011394 SVC_pipeline = Pipeline([ ('tfidf', TfidfVectorizer(stop_words=stop_words)), ('clf', OneVsRestClassifier(LinearSVC(), n_jobs=1)), ])for category in categories: print('... Processing {}'.format(category)) # train the model using X_dtm & y SVC_pipeline.fit(X_train, train[category]) # compute the testing accuracy prediction = SVC_pipeline.predict(X_test) print('Test accuracy is {}'.format(accuracy_score(test[category], prediction))) ... Processing toxicTest accuracy is 0.9599498661197516... Processing severe_toxicTest accuracy is 0.9906948479842003... Processing obsceneTest accuracy is 0.9789019920621356... Processing threatTest accuracy is 0.9974173455629617... Processing insultTest accuracy is 0.9712299891756395... Processing identity_hateTest accuracy is 0.9919861752027194 LogReg_pipeline = Pipeline([ ('tfidf', TfidfVectorizer(stop_words=stop_words)), ('clf', OneVsRestClassifier(LogisticRegression(solver='sag'), n_jobs=1)), ])for category in categories: print('... Processing {}'.format(category)) # train the model using X_dtm & y LogReg_pipeline.fit(X_train, train[category]) # compute the testing accuracy prediction = LogReg_pipeline.predict(X_test) print('Test accuracy is {}'.format(accuracy_score(test[category], prediction))) ... Processing toxicTest accuracy is 0.9548415275641391... Processing severe_toxicTest accuracy is 0.9910556600011394... Processing obsceneTest accuracy is 0.9761104464573956... Processing threatTest accuracy is 0.9973793653506523... Processing insultTest accuracy is 0.9687612753755294... Processing identity_hateTest accuracy is 0.991758293928863 The three classifiers produced similar results. We have created a strong baseline for the toxic comment multi-label text classification problem. The full code for this post can be found on Github. I look forward to hearing any feedback or comment.
[ { "code": null, "e": 386, "s": 172, "text": "Multi-class classification means a classification task with more than two classes; each label are mutually exclusive. The classification makes the assumption that each sample is assigned to one and only one label." }, { "code": null, "e": 800, "s": 386, "text": "On the other hand, Multi-label classification assigns to each sample a set of target labels. This can be thought as predicting properties of a data-point that are not mutually exclusive, such as Tim Horton are often categorized as both bakery and coffee shop. Multi-label text classification has many real world applications such as categorizing businesses on Yelp or classifying movies into one or more genre(s)." }, { "code": null, "e": 1418, "s": 800, "text": "Anyone who has been the target of abuse or harassment online will know that it doesn’t go away when you log off or switch off your phone. Researchers at Google are working on tools to study toxic comments online. In this post, we will build a multi-label model that’s capable of detecting different types of toxicity like severe toxic, threats, obscenity, insults, and so on. We will be using supervised classifiers and text representations. A toxic comment might be about any of toxic, severe toxic, obscene, threat, insult or identity hate at the same time or none of the above. The data set can be found at Kaggle." }, { "code": null, "e": 1533, "s": 1418, "text": "(Disclaimer from the data source: the dataset contains text that may be considered profane, vulgar, or offensive.)" }, { "code": null, "e": 2178, "s": 1533, "text": "%matplotlib inlineimport reimport matplotlibimport numpy as npimport matplotlib.pyplot as pltimport pandas as pdfrom sklearn.model_selection import train_test_splitfrom sklearn.feature_extraction.text import TfidfVectorizerfrom sklearn.naive_bayes import MultinomialNBfrom sklearn.metrics import accuracy_scorefrom sklearn.multiclass import OneVsRestClassifierfrom nltk.corpus import stopwordsstop_words = set(stopwords.words('english'))from sklearn.svm import LinearSVCfrom sklearn.linear_model import LogisticRegressionfrom sklearn.pipeline import Pipelineimport seaborn as snsdf = pd.read_csv(\"train 2.csv\", encoding = \"ISO-8859-1\")df.head()" }, { "code": null, "e": 2214, "s": 2178, "text": "Number of comments in each category" }, { "code": null, "e": 2462, "s": 2214, "text": "df_toxic = df.drop(['id', 'comment_text'], axis=1)counts = []categories = list(df_toxic.columns.values)for i in categories: counts.append((i, df_toxic[i].sum()))df_stats = pd.DataFrame(counts, columns=['category', 'number_of_comments'])df_stats" }, { "code": null, "e": 2689, "s": 2462, "text": "df_stats.plot(x='category', y='number_of_comments', kind='bar', legend=False, grid=True, figsize=(8, 5))plt.title(\"Number of comments per category\")plt.ylabel('# of Occurrences', fontsize=12)plt.xlabel('category', fontsize=12)" }, { "code": null, "e": 2726, "s": 2689, "text": "How many comments have multi labels?" }, { "code": null, "e": 2980, "s": 2726, "text": "rowsums = df.iloc[:,2:].sum(axis=1)x=rowsums.value_counts()#plotplt.figure(figsize=(8,5))ax = sns.barplot(x.index, x.values)plt.title(\"Multiple categories per comment\")plt.ylabel('# of Occurrences', fontsize=12)plt.xlabel('# of categories', fontsize=12)" }, { "code": null, "e": 3031, "s": 2980, "text": "Vast majority of the comment text are not labeled." }, { "code": null, "e": 3243, "s": 3031, "text": "print('Percentage of comments that are not labelled:')print(len(df[(df['toxic']==0) & (df['severe_toxic']==0) & (df['obscene']==0) & (df['threat']== 0) & (df['insult']==0) & (df['identity_hate']==0)]) / len(df))" }, { "code": null, "e": 3307, "s": 3243, "text": "Percentage of comments that are not labelled:0.8983211235124177" }, { "code": null, "e": 3365, "s": 3307, "text": "The distribution of the number of words in comment texts." }, { "code": null, "e": 3436, "s": 3365, "text": "lens = df.comment_text.str.len()lens.hist(bins = np.arange(0,5000,50))" }, { "code": null, "e": 3543, "s": 3436, "text": "Most of the comment text length are within 500 characters, with some outliers up to 5,000 characters long." }, { "code": null, "e": 3595, "s": 3543, "text": "There is no missing comment in comment text column." }, { "code": null, "e": 3681, "s": 3595, "text": "print('Number of missing comments in comment text:')df['comment_text'].isnull().sum()" }, { "code": null, "e": 3725, "s": 3681, "text": "Number of missing comments in comment text:" }, { "code": null, "e": 3727, "s": 3725, "text": "0" }, { "code": null, "e": 3788, "s": 3727, "text": "Have a peek the first comment, the text needs to be cleaned." }, { "code": null, "e": 3810, "s": 3788, "text": "df['comment_text'][0]" }, { "code": null, "e": 4078, "s": 3810, "text": "“Explanation\\rWhy the edits made under my username Hardcore Metallica Fan were reverted? They weren’t vandalisms, just closure on some GAs after I voted at New York Dolls FAC. And please don’t remove the template from the talk page since I’m retired now.89.205.38.27”" }, { "code": null, "e": 4114, "s": 4078, "text": "Create a function to clean the text" }, { "code": null, "e": 4690, "s": 4114, "text": "def clean_text(text): text = text.lower() text = re.sub(r\"what's\", \"what is \", text) text = re.sub(r\"\\'s\", \" \", text) text = re.sub(r\"\\'ve\", \" have \", text) text = re.sub(r\"can't\", \"can not \", text) text = re.sub(r\"n't\", \" not \", text) text = re.sub(r\"i'm\", \"i am \", text) text = re.sub(r\"\\'re\", \" are \", text) text = re.sub(r\"\\'d\", \" would \", text) text = re.sub(r\"\\'ll\", \" will \", text) text = re.sub(r\"\\'scuse\", \" excuse \", text) text = re.sub('\\W', ' ', text) text = re.sub('\\s+', ' ', text) text = text.strip(' ') return text" }, { "code": null, "e": 4720, "s": 4690, "text": "Clean up comment_text column:" }, { "code": null, "e": 4815, "s": 4720, "text": "df['comment_text'] = df['comment_text'].map(lambda com : clean_text(com))df['comment_text'][0]" }, { "code": null, "e": 5082, "s": 4815, "text": "‘explanation why the edits made under my username hardcore metallica fan were reverted they were not vandalisms just closure on some gas after i voted at new york dolls fac and please do not remove the template from the talk page since i am retired now 89 205 38 27’" }, { "code": null, "e": 5095, "s": 5082, "text": "Much better!" }, { "code": null, "e": 5134, "s": 5095, "text": "Split the data to train and test sets:" }, { "code": null, "e": 5395, "s": 5134, "text": "categories = ['toxic', 'severe_toxic', 'obscene', 'threat', 'insult', 'identity_hate']train, test = train_test_split(df, random_state=42, test_size=0.33, shuffle=True)X_train = train.comment_textX_test = test.comment_textprint(X_train.shape)print(X_test.shape)" }, { "code": null, "e": 5413, "s": 5395, "text": "(106912,)(52659,)" }, { "code": null, "e": 5692, "s": 5413, "text": "Scikit-learn provides a pipeline utility to help automate machine learning workflows. Pipelines are very common in Machine Learning systems, since there is a lot of data to manipulate and many data transformations to apply. So we will utilize pipeline to train every classifier." }, { "code": null, "e": 5882, "s": 5692, "text": "The Multi-label algorithm accepts a binary mask over multiple labels. The result for each prediction will be an array of 0s and 1s marking which class labels apply to each row input sample." }, { "code": null, "e": 6138, "s": 5882, "text": "OneVsRest strategy can be used for multi-label learning, where a classifier is used to predict multiple labels for instance. Naive Bayes supports multi-class, but we are in a multi-label scenario, therefore, we wrap Naive Bayes in the OneVsRestClassifier." }, { "code": null, "e": 6756, "s": 6138, "text": "# Define a pipeline combining a text feature extractor with multi lable classifierNB_pipeline = Pipeline([ ('tfidf', TfidfVectorizer(stop_words=stop_words)), ('clf', OneVsRestClassifier(MultinomialNB( fit_prior=True, class_prior=None))), ])for category in categories: print('... Processing {}'.format(category)) # train the model using X_dtm & y NB_pipeline.fit(X_train, train[category]) # compute the testing accuracy prediction = NB_pipeline.predict(X_test) print('Test accuracy is {}'.format(accuracy_score(test[category], prediction)))" }, { "code": null, "e": 7106, "s": 6756, "text": "... Processing toxicTest accuracy is 0.9191401279933155... Processing severe_toxicTest accuracy is 0.9900112041626312... Processing obsceneTest accuracy is 0.9514802787747584... Processing threatTest accuracy is 0.9971135038644866... Processing insultTest accuracy is 0.9517271501547694... Processing identity_hateTest accuracy is 0.9910556600011394" }, { "code": null, "e": 7599, "s": 7106, "text": "SVC_pipeline = Pipeline([ ('tfidf', TfidfVectorizer(stop_words=stop_words)), ('clf', OneVsRestClassifier(LinearSVC(), n_jobs=1)), ])for category in categories: print('... Processing {}'.format(category)) # train the model using X_dtm & y SVC_pipeline.fit(X_train, train[category]) # compute the testing accuracy prediction = SVC_pipeline.predict(X_test) print('Test accuracy is {}'.format(accuracy_score(test[category], prediction)))" }, { "code": null, "e": 7949, "s": 7599, "text": "... Processing toxicTest accuracy is 0.9599498661197516... Processing severe_toxicTest accuracy is 0.9906948479842003... Processing obsceneTest accuracy is 0.9789019920621356... Processing threatTest accuracy is 0.9974173455629617... Processing insultTest accuracy is 0.9712299891756395... Processing identity_hateTest accuracy is 0.9919861752027194" }, { "code": null, "e": 8472, "s": 7949, "text": "LogReg_pipeline = Pipeline([ ('tfidf', TfidfVectorizer(stop_words=stop_words)), ('clf', OneVsRestClassifier(LogisticRegression(solver='sag'), n_jobs=1)), ])for category in categories: print('... Processing {}'.format(category)) # train the model using X_dtm & y LogReg_pipeline.fit(X_train, train[category]) # compute the testing accuracy prediction = LogReg_pipeline.predict(X_test) print('Test accuracy is {}'.format(accuracy_score(test[category], prediction)))" }, { "code": null, "e": 8821, "s": 8472, "text": "... Processing toxicTest accuracy is 0.9548415275641391... Processing severe_toxicTest accuracy is 0.9910556600011394... Processing obsceneTest accuracy is 0.9761104464573956... Processing threatTest accuracy is 0.9973793653506523... Processing insultTest accuracy is 0.9687612753755294... Processing identity_hateTest accuracy is 0.991758293928863" }, { "code": null, "e": 8966, "s": 8821, "text": "The three classifiers produced similar results. We have created a strong baseline for the toxic comment multi-label text classification problem." } ]
CSS | border-bottom-style Property - GeeksforGeeks
06 Jul, 2020 The border-bottom-style property in CSS is used to set the style of the bottom border of an element. Syntax: border-bottom-style:none|hidden|dotted|dashed|solid|double|groove| ridge|inset|outset|initial|inherit; Property Values: none: It is the default value and it makes the width of bottom border to zero. Hence, it is not visible. Syntax:border-bottom-style: none; border-bottom-style: none; Example:<!DOCTYPE html> <html> <head> <title> CSS border-bottom-style property </title> <!-- Internal CSS Style Sheet --> <style> h1 { color: green; text-align: center; border: 5px solid black; /* CSS Property for border-bottom-style */ border-bottom-style: none; } </style> </head> <body> <!-- border-bottom-style:none; --> <h1>GeeksForGeeks</h1> </body> </html> <!DOCTYPE html> <html> <head> <title> CSS border-bottom-style property </title> <!-- Internal CSS Style Sheet --> <style> h1 { color: green; text-align: center; border: 5px solid black; /* CSS Property for border-bottom-style */ border-bottom-style: none; } </style> </head> <body> <!-- border-bottom-style:none; --> <h1>GeeksForGeeks</h1> </body> </html> Output: hidden: It is used to make bottom border invisible. It is similar to none value except in case of border conflict resolution of table elements. Syntax:border-bottom-style: hidden; border-bottom-style: hidden; Example:<!DOCTYPE html> <html> <head> <title> CSS border-bottom-style property </title> <!-- Internal CSS Style Sheet --> <style> h1 { color: green; text-align: center; border: 5px solid black; /* CSS Property for border-bottom-style */ border-bottom-style: hidden; } </style> </head> <body> <!-- border-bottom-style:hidden; --> <h1>GeeksForGeeks</h1> </body> </html> <!DOCTYPE html> <html> <head> <title> CSS border-bottom-style property </title> <!-- Internal CSS Style Sheet --> <style> h1 { color: green; text-align: center; border: 5px solid black; /* CSS Property for border-bottom-style */ border-bottom-style: hidden; } </style> </head> <body> <!-- border-bottom-style:hidden; --> <h1>GeeksForGeeks</h1> </body> </html> Output: dotted: It makes the bottom border with a series of dots. Syntax:border-bottom-style: dotted; border-bottom-style: dotted; Example:<!DOCTYPE html> <html> <head> <title> CSS border-bottom-style property </title> <!-- Internal CSS Style Sheet --> <style> h1 { color: green; text-align: center; border: 5px solid black; /* CSS Property for border-bottom-style */ border-bottom-style: dotted; } </style> </head> <body> <!-- border-bottom-style:dotted; --> <h1>GeeksForGeeks</h1> </body> </html> <!DOCTYPE html> <html> <head> <title> CSS border-bottom-style property </title> <!-- Internal CSS Style Sheet --> <style> h1 { color: green; text-align: center; border: 5px solid black; /* CSS Property for border-bottom-style */ border-bottom-style: dotted; } </style> </head> <body> <!-- border-bottom-style:dotted; --> <h1>GeeksForGeeks</h1> </body> </html> Output: dashed: It makes the bottom border with a series of short line segments. Syntax:border-bottom-style: dashed; border-bottom-style: dashed; Example:<!DOCTYPE html> <html> <head> <title> CSS border-bottom-style property </title> <!-- Internal CSS Style Sheet --> <style> h1 { color: green; text-align: center; border: 5px solid black; /* CSS Property for border-bottom-style */ border-bottom-style: dashed; } </style> </head> <body> <!-- border-bottom-style:dashed; --> <h1>GeeksForGeeks</h1> </body> </html> <!DOCTYPE html> <html> <head> <title> CSS border-bottom-style property </title> <!-- Internal CSS Style Sheet --> <style> h1 { color: green; text-align: center; border: 5px solid black; /* CSS Property for border-bottom-style */ border-bottom-style: dashed; } </style> </head> <body> <!-- border-bottom-style:dashed; --> <h1>GeeksForGeeks</h1> </body> </html> Output: solid: It is used to make the bottom border with a single solid line segment. Syntax:border-bottom-style: solid; border-bottom-style: solid; Example:<!DOCTYPE html> <html> <head> <title> CSS border-bottom-style property </title> <!-- Internal CSS Style Sheet --> <style> h1 { color: green; text-align: center; border: 5px solid black; /* CSS Property for border-bottom-style */ border-bottom-style: solid; } </style> </head> <body> <!-- border-bottom-style:solid; --> <h1>GeeksForGeeks</h1> </body> </html> <!DOCTYPE html> <html> <head> <title> CSS border-bottom-style property </title> <!-- Internal CSS Style Sheet --> <style> h1 { color: green; text-align: center; border: 5px solid black; /* CSS Property for border-bottom-style */ border-bottom-style: solid; } </style> </head> <body> <!-- border-bottom-style:solid; --> <h1>GeeksForGeeks</h1> </body> </html> Output: double: It makes the bottom border to double solid line. In this case, the border width is equal to the sum of widths of the two-line segments and the space between them. Syntax:border-bottom-style: double; border-bottom-style: double; Example:<!DOCTYPE html> <html> <head> <title> CSS border-bottom-style property </title> <!-- Internal CSS Style Sheet --> <style> h1 { color: green; text-align: center; border: 5px solid black; /* CSS Property for border-bottom-style */ border-bottom-style: double; } </style> </head> <body> <!-- border-bottom-style:double; --> <h1>GeeksForGeeks</h1> </body> </html> <!DOCTYPE html> <html> <head> <title> CSS border-bottom-style property </title> <!-- Internal CSS Style Sheet --> <style> h1 { color: green; text-align: center; border: 5px solid black; /* CSS Property for border-bottom-style */ border-bottom-style: double; } </style> </head> <body> <!-- border-bottom-style:double; --> <h1>GeeksForGeeks</h1> </body> </html> Output: groove: It makes the bottom border with a grooved line segment, which makes feel that it is going inside. Syntax:border-bottom-style: groove; border-bottom-style: groove; Example:<!DOCTYPE html> <html> <head> <title> CSS border-bottom-style property </title> <!-- Internal CSS Style Sheet --> <style> h1 { border: 10px; border-style: solid; /* CSS Property for border-bottom-style */ border-bottom-style: groove; } </style> </head> <body> <!-- border-bottom-style:groove; --> <h1>GeeksForGeeks</h1> </body> </html> <!DOCTYPE html> <html> <head> <title> CSS border-bottom-style property </title> <!-- Internal CSS Style Sheet --> <style> h1 { border: 10px; border-style: solid; /* CSS Property for border-bottom-style */ border-bottom-style: groove; } </style> </head> <body> <!-- border-bottom-style:groove; --> <h1>GeeksForGeeks</h1> </body> </html> Output: inset: It makes the bottom border with an embedded line segment, which makes feel that it is fixed deeply on the screen. Syntax:border-bottom-style: inset; border-bottom-style: inset; Example:<!DOCTYPE html> <html> <head> <title> CSS border-bottom-style property </title> <!-- Internal CSS Style Sheet --> <style> h1 { border: 10px; border-style: solid; /* CSS Property for border-bottom-style */ border-bottom-style: inset; } </style> </head> <body> <!-- border-bottom-style:inset; --> <h1>GeeksForGeeks</h1> </body> </html> <!DOCTYPE html> <html> <head> <title> CSS border-bottom-style property </title> <!-- Internal CSS Style Sheet --> <style> h1 { border: 10px; border-style: solid; /* CSS Property for border-bottom-style */ border-bottom-style: inset; } </style> </head> <body> <!-- border-bottom-style:inset; --> <h1>GeeksForGeeks</h1> </body> </html> Output: outset: It is opposite of inset. It makes the bottom border with a line segment, which appears to be coming out. Syntax:border-bottom-style: outset; border-bottom-style: outset; Example:<!DOCTYPE html> <html> <head> <title> CSS border-bottom-style property </title> <!-- Internal CSS Style Sheet --> <style> h1 { border: 10px; border-style: solid; /* CSS Property for border-bottom-style */ border-bottom-style: outset; } </style> </head> <body> <!-- border-bottom-style:outset; --> <h1>GeeksForGeeks</h1> </body> </html> <!DOCTYPE html> <html> <head> <title> CSS border-bottom-style property </title> <!-- Internal CSS Style Sheet --> <style> h1 { border: 10px; border-style: solid; /* CSS Property for border-bottom-style */ border-bottom-style: outset; } </style> </head> <body> <!-- border-bottom-style:outset; --> <h1>GeeksForGeeks</h1> </body> </html> Output: initial: It sets the border-bottom-style property to its default value. Syntax:border-bottom-style: initial; border-bottom-style: initial; Example:<!DOCTYPE html> <html> <head> <title> CSS border-bottom-style property </title> <!-- Internal CSS Style Sheet --> <style> h1 { color: green; text-align: center; border: 5px solid black; /* CSS Property for border-bottom-style */ border-bottom-style: initial; } </style> </head> <body> <!-- border-bottom-style:initial; --> <h1>GeeksForGeeks</h1> </body> </html> <!DOCTYPE html> <html> <head> <title> CSS border-bottom-style property </title> <!-- Internal CSS Style Sheet --> <style> h1 { color: green; text-align: center; border: 5px solid black; /* CSS Property for border-bottom-style */ border-bottom-style: initial; } </style> </head> <body> <!-- border-bottom-style:initial; --> <h1>GeeksForGeeks</h1> </body> </html> Output: inherit: The border-bottom-style property to be inherited from its parent element. Syntax:border-bottom-style: inherit; border-bottom-style: inherit; Example:<!DOCTYPE html> <html> <head> <title> CSS border-bottom-style Property </title> <!-- Internal CSS Style Sheet --> <style> div { border-bottom-style: double; } h1 { color: green; text-align: center; border: 5px solid black; /* CSS Property | border-bottom-style */ border-bottom-style: inherit; } </style> </head> <body> <div> <!-- border-bottom-style: inherit; --> <h1>GeeksForGeeks</h1> </div> </body> </html> <!DOCTYPE html> <html> <head> <title> CSS border-bottom-style Property </title> <!-- Internal CSS Style Sheet --> <style> div { border-bottom-style: double; } h1 { color: green; text-align: center; border: 5px solid black; /* CSS Property | border-bottom-style */ border-bottom-style: inherit; } </style> </head> <body> <div> <!-- border-bottom-style: inherit; --> <h1>GeeksForGeeks</h1> </div> </body> </html> Output: Supported Browsers: The browser supported by border-bottom-style property are listed below: Google Chrome 1.0 Internet Explorer 5.5 Firefox 1.0 Opera 9.2 Safari 1.0 nidhi_biet CSS-Properties Picked Technical Scripter 2018 CSS Technical Scripter Web Technologies 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 create footer to stay at the bottom of a Web page? How to update Node.js and NPM to next version ? Types of CSS (Cascading Style Sheet) Roadmap to Become a Web Developer in 2022 Installation of Node.js on Linux Top 10 Projects For Beginners To Practice HTML and CSS Skills How to fetch data from an API in ReactJS ? How to insert spaces/tabs in text using HTML/CSS?
[ { "code": null, "e": 23538, "s": 23510, "text": "\n06 Jul, 2020" }, { "code": null, "e": 23639, "s": 23538, "text": "The border-bottom-style property in CSS is used to set the style of the bottom border of an element." }, { "code": null, "e": 23647, "s": 23639, "text": "Syntax:" }, { "code": null, "e": 23750, "s": 23647, "text": "border-bottom-style:none|hidden|dotted|dashed|solid|double|groove|\nridge|inset|outset|initial|inherit;" }, { "code": null, "e": 23767, "s": 23750, "text": "Property Values:" }, { "code": null, "e": 23872, "s": 23767, "text": "none: It is the default value and it makes the width of bottom border to zero. Hence, it is not visible." }, { "code": null, "e": 23906, "s": 23872, "text": "Syntax:border-bottom-style: none;" }, { "code": null, "e": 23933, "s": 23906, "text": "border-bottom-style: none;" }, { "code": null, "e": 24532, "s": 23933, "text": "Example:<!DOCTYPE html> <html> <head> <title> CSS border-bottom-style property </title> <!-- Internal CSS Style Sheet --> <style> h1 { color: green; text-align: center; border: 5px solid black; /* CSS Property for border-bottom-style */ border-bottom-style: none; } </style> </head> <body> <!-- border-bottom-style:none; --> <h1>GeeksForGeeks</h1> </body> </html> " }, { "code": "<!DOCTYPE html> <html> <head> <title> CSS border-bottom-style property </title> <!-- Internal CSS Style Sheet --> <style> h1 { color: green; text-align: center; border: 5px solid black; /* CSS Property for border-bottom-style */ border-bottom-style: none; } </style> </head> <body> <!-- border-bottom-style:none; --> <h1>GeeksForGeeks</h1> </body> </html> ", "e": 25123, "s": 24532, "text": null }, { "code": null, "e": 25131, "s": 25123, "text": "Output:" }, { "code": null, "e": 25275, "s": 25131, "text": "hidden: It is used to make bottom border invisible. It is similar to none value except in case of border conflict resolution of table elements." }, { "code": null, "e": 25311, "s": 25275, "text": "Syntax:border-bottom-style: hidden;" }, { "code": null, "e": 25340, "s": 25311, "text": "border-bottom-style: hidden;" }, { "code": null, "e": 25944, "s": 25340, "text": "Example:<!DOCTYPE html> <html> <head> <title> CSS border-bottom-style property </title> <!-- Internal CSS Style Sheet --> <style> h1 { color: green; text-align: center; border: 5px solid black; /* CSS Property for border-bottom-style */ border-bottom-style: hidden; } </style> </head> <body> <!-- border-bottom-style:hidden; --> <h1>GeeksForGeeks</h1> </body> </html> " }, { "code": "<!DOCTYPE html> <html> <head> <title> CSS border-bottom-style property </title> <!-- Internal CSS Style Sheet --> <style> h1 { color: green; text-align: center; border: 5px solid black; /* CSS Property for border-bottom-style */ border-bottom-style: hidden; } </style> </head> <body> <!-- border-bottom-style:hidden; --> <h1>GeeksForGeeks</h1> </body> </html> ", "e": 26540, "s": 25944, "text": null }, { "code": null, "e": 26548, "s": 26540, "text": "Output:" }, { "code": null, "e": 26606, "s": 26548, "text": "dotted: It makes the bottom border with a series of dots." }, { "code": null, "e": 26642, "s": 26606, "text": "Syntax:border-bottom-style: dotted;" }, { "code": null, "e": 26671, "s": 26642, "text": "border-bottom-style: dotted;" }, { "code": null, "e": 27274, "s": 26671, "text": "Example:<!DOCTYPE html> <html> <head> <title> CSS border-bottom-style property </title> <!-- Internal CSS Style Sheet --> <style> h1 { color: green; text-align: center; border: 5px solid black; /* CSS Property for border-bottom-style */ border-bottom-style: dotted; } </style> </head> <body> <!-- border-bottom-style:dotted; --> <h1>GeeksForGeeks</h1> </body> </html> " }, { "code": "<!DOCTYPE html> <html> <head> <title> CSS border-bottom-style property </title> <!-- Internal CSS Style Sheet --> <style> h1 { color: green; text-align: center; border: 5px solid black; /* CSS Property for border-bottom-style */ border-bottom-style: dotted; } </style> </head> <body> <!-- border-bottom-style:dotted; --> <h1>GeeksForGeeks</h1> </body> </html> ", "e": 27869, "s": 27274, "text": null }, { "code": null, "e": 27877, "s": 27869, "text": "Output:" }, { "code": null, "e": 27950, "s": 27877, "text": "dashed: It makes the bottom border with a series of short line segments." }, { "code": null, "e": 27986, "s": 27950, "text": "Syntax:border-bottom-style: dashed;" }, { "code": null, "e": 28015, "s": 27986, "text": "border-bottom-style: dashed;" }, { "code": null, "e": 28618, "s": 28015, "text": "Example:<!DOCTYPE html> <html> <head> <title> CSS border-bottom-style property </title> <!-- Internal CSS Style Sheet --> <style> h1 { color: green; text-align: center; border: 5px solid black; /* CSS Property for border-bottom-style */ border-bottom-style: dashed; } </style> </head> <body> <!-- border-bottom-style:dashed; --> <h1>GeeksForGeeks</h1> </body> </html> " }, { "code": "<!DOCTYPE html> <html> <head> <title> CSS border-bottom-style property </title> <!-- Internal CSS Style Sheet --> <style> h1 { color: green; text-align: center; border: 5px solid black; /* CSS Property for border-bottom-style */ border-bottom-style: dashed; } </style> </head> <body> <!-- border-bottom-style:dashed; --> <h1>GeeksForGeeks</h1> </body> </html> ", "e": 29213, "s": 28618, "text": null }, { "code": null, "e": 29221, "s": 29213, "text": "Output:" }, { "code": null, "e": 29299, "s": 29221, "text": "solid: It is used to make the bottom border with a single solid line segment." }, { "code": null, "e": 29334, "s": 29299, "text": "Syntax:border-bottom-style: solid;" }, { "code": null, "e": 29362, "s": 29334, "text": "border-bottom-style: solid;" }, { "code": null, "e": 29963, "s": 29362, "text": "Example:<!DOCTYPE html> <html> <head> <title> CSS border-bottom-style property </title> <!-- Internal CSS Style Sheet --> <style> h1 { color: green; text-align: center; border: 5px solid black; /* CSS Property for border-bottom-style */ border-bottom-style: solid; } </style> </head> <body> <!-- border-bottom-style:solid; --> <h1>GeeksForGeeks</h1> </body> </html> " }, { "code": "<!DOCTYPE html> <html> <head> <title> CSS border-bottom-style property </title> <!-- Internal CSS Style Sheet --> <style> h1 { color: green; text-align: center; border: 5px solid black; /* CSS Property for border-bottom-style */ border-bottom-style: solid; } </style> </head> <body> <!-- border-bottom-style:solid; --> <h1>GeeksForGeeks</h1> </body> </html> ", "e": 30556, "s": 29963, "text": null }, { "code": null, "e": 30564, "s": 30556, "text": "Output:" }, { "code": null, "e": 30735, "s": 30564, "text": "double: It makes the bottom border to double solid line. In this case, the border width is equal to the sum of widths of the two-line segments and the space between them." }, { "code": null, "e": 30771, "s": 30735, "text": "Syntax:border-bottom-style: double;" }, { "code": null, "e": 30800, "s": 30771, "text": "border-bottom-style: double;" }, { "code": null, "e": 31403, "s": 30800, "text": "Example:<!DOCTYPE html> <html> <head> <title> CSS border-bottom-style property </title> <!-- Internal CSS Style Sheet --> <style> h1 { color: green; text-align: center; border: 5px solid black; /* CSS Property for border-bottom-style */ border-bottom-style: double; } </style> </head> <body> <!-- border-bottom-style:double; --> <h1>GeeksForGeeks</h1> </body> </html> " }, { "code": "<!DOCTYPE html> <html> <head> <title> CSS border-bottom-style property </title> <!-- Internal CSS Style Sheet --> <style> h1 { color: green; text-align: center; border: 5px solid black; /* CSS Property for border-bottom-style */ border-bottom-style: double; } </style> </head> <body> <!-- border-bottom-style:double; --> <h1>GeeksForGeeks</h1> </body> </html> ", "e": 31998, "s": 31403, "text": null }, { "code": null, "e": 32006, "s": 31998, "text": "Output:" }, { "code": null, "e": 32112, "s": 32006, "text": "groove: It makes the bottom border with a grooved line segment, which makes feel that it is going inside." }, { "code": null, "e": 32148, "s": 32112, "text": "Syntax:border-bottom-style: groove;" }, { "code": null, "e": 32177, "s": 32148, "text": "border-bottom-style: groove;" }, { "code": null, "e": 32760, "s": 32177, "text": "Example:<!DOCTYPE html> <html> <head> <title> CSS border-bottom-style property </title> <!-- Internal CSS Style Sheet --> <style> h1 { border: 10px; border-style: solid; /* CSS Property for border-bottom-style */ border-bottom-style: groove; } </style> </head> <body> <!-- border-bottom-style:groove; --> <h1>GeeksForGeeks</h1> </body> </html> " }, { "code": "<!DOCTYPE html> <html> <head> <title> CSS border-bottom-style property </title> <!-- Internal CSS Style Sheet --> <style> h1 { border: 10px; border-style: solid; /* CSS Property for border-bottom-style */ border-bottom-style: groove; } </style> </head> <body> <!-- border-bottom-style:groove; --> <h1>GeeksForGeeks</h1> </body> </html> ", "e": 33335, "s": 32760, "text": null }, { "code": null, "e": 33343, "s": 33335, "text": "Output:" }, { "code": null, "e": 33464, "s": 33343, "text": "inset: It makes the bottom border with an embedded line segment, which makes feel that it is fixed deeply on the screen." }, { "code": null, "e": 33499, "s": 33464, "text": "Syntax:border-bottom-style: inset;" }, { "code": null, "e": 33527, "s": 33499, "text": "border-bottom-style: inset;" }, { "code": null, "e": 34108, "s": 33527, "text": "Example:<!DOCTYPE html> <html> <head> <title> CSS border-bottom-style property </title> <!-- Internal CSS Style Sheet --> <style> h1 { border: 10px; border-style: solid; /* CSS Property for border-bottom-style */ border-bottom-style: inset; } </style> </head> <body> <!-- border-bottom-style:inset; --> <h1>GeeksForGeeks</h1> </body> </html> " }, { "code": "<!DOCTYPE html> <html> <head> <title> CSS border-bottom-style property </title> <!-- Internal CSS Style Sheet --> <style> h1 { border: 10px; border-style: solid; /* CSS Property for border-bottom-style */ border-bottom-style: inset; } </style> </head> <body> <!-- border-bottom-style:inset; --> <h1>GeeksForGeeks</h1> </body> </html> ", "e": 34681, "s": 34108, "text": null }, { "code": null, "e": 34689, "s": 34681, "text": "Output:" }, { "code": null, "e": 34802, "s": 34689, "text": "outset: It is opposite of inset. It makes the bottom border with a line segment, which appears to be coming out." }, { "code": null, "e": 34838, "s": 34802, "text": "Syntax:border-bottom-style: outset;" }, { "code": null, "e": 34867, "s": 34838, "text": "border-bottom-style: outset;" }, { "code": null, "e": 35450, "s": 34867, "text": "Example:<!DOCTYPE html> <html> <head> <title> CSS border-bottom-style property </title> <!-- Internal CSS Style Sheet --> <style> h1 { border: 10px; border-style: solid; /* CSS Property for border-bottom-style */ border-bottom-style: outset; } </style> </head> <body> <!-- border-bottom-style:outset; --> <h1>GeeksForGeeks</h1> </body> </html> " }, { "code": "<!DOCTYPE html> <html> <head> <title> CSS border-bottom-style property </title> <!-- Internal CSS Style Sheet --> <style> h1 { border: 10px; border-style: solid; /* CSS Property for border-bottom-style */ border-bottom-style: outset; } </style> </head> <body> <!-- border-bottom-style:outset; --> <h1>GeeksForGeeks</h1> </body> </html> ", "e": 36025, "s": 35450, "text": null }, { "code": null, "e": 36033, "s": 36025, "text": "Output:" }, { "code": null, "e": 36105, "s": 36033, "text": "initial: It sets the border-bottom-style property to its default value." }, { "code": null, "e": 36142, "s": 36105, "text": "Syntax:border-bottom-style: initial;" }, { "code": null, "e": 36172, "s": 36142, "text": "border-bottom-style: initial;" }, { "code": null, "e": 36777, "s": 36172, "text": "Example:<!DOCTYPE html> <html> <head> <title> CSS border-bottom-style property </title> <!-- Internal CSS Style Sheet --> <style> h1 { color: green; text-align: center; border: 5px solid black; /* CSS Property for border-bottom-style */ border-bottom-style: initial; } </style> </head> <body> <!-- border-bottom-style:initial; --> <h1>GeeksForGeeks</h1> </body> </html> " }, { "code": "<!DOCTYPE html> <html> <head> <title> CSS border-bottom-style property </title> <!-- Internal CSS Style Sheet --> <style> h1 { color: green; text-align: center; border: 5px solid black; /* CSS Property for border-bottom-style */ border-bottom-style: initial; } </style> </head> <body> <!-- border-bottom-style:initial; --> <h1>GeeksForGeeks</h1> </body> </html> ", "e": 37374, "s": 36777, "text": null }, { "code": null, "e": 37382, "s": 37374, "text": "Output:" }, { "code": null, "e": 37465, "s": 37382, "text": "inherit: The border-bottom-style property to be inherited from its parent element." }, { "code": null, "e": 37502, "s": 37465, "text": "Syntax:border-bottom-style: inherit;" }, { "code": null, "e": 37532, "s": 37502, "text": "border-bottom-style: inherit;" }, { "code": null, "e": 38256, "s": 37532, "text": "Example:<!DOCTYPE html> <html> <head> <title> CSS border-bottom-style Property </title> <!-- Internal CSS Style Sheet --> <style> div { border-bottom-style: double; } h1 { color: green; text-align: center; border: 5px solid black; /* CSS Property | border-bottom-style */ border-bottom-style: inherit; } </style> </head> <body> <div> <!-- border-bottom-style: inherit; --> <h1>GeeksForGeeks</h1> </div> </body> </html> " }, { "code": "<!DOCTYPE html> <html> <head> <title> CSS border-bottom-style Property </title> <!-- Internal CSS Style Sheet --> <style> div { border-bottom-style: double; } h1 { color: green; text-align: center; border: 5px solid black; /* CSS Property | border-bottom-style */ border-bottom-style: inherit; } </style> </head> <body> <div> <!-- border-bottom-style: inherit; --> <h1>GeeksForGeeks</h1> </div> </body> </html> ", "e": 38972, "s": 38256, "text": null }, { "code": null, "e": 38980, "s": 38972, "text": "Output:" }, { "code": null, "e": 39072, "s": 38980, "text": "Supported Browsers: The browser supported by border-bottom-style property are listed below:" }, { "code": null, "e": 39090, "s": 39072, "text": "Google Chrome 1.0" }, { "code": null, "e": 39112, "s": 39090, "text": "Internet Explorer 5.5" }, { "code": null, "e": 39124, "s": 39112, "text": "Firefox 1.0" }, { "code": null, "e": 39134, "s": 39124, "text": "Opera 9.2" }, { "code": null, "e": 39145, "s": 39134, "text": "Safari 1.0" }, { "code": null, "e": 39156, "s": 39145, "text": "nidhi_biet" }, { "code": null, "e": 39171, "s": 39156, "text": "CSS-Properties" }, { "code": null, "e": 39178, "s": 39171, "text": "Picked" }, { "code": null, "e": 39202, "s": 39178, "text": "Technical Scripter 2018" }, { "code": null, "e": 39206, "s": 39202, "text": "CSS" }, { "code": null, "e": 39225, "s": 39206, "text": "Technical Scripter" }, { "code": null, "e": 39242, "s": 39225, "text": "Web Technologies" }, { "code": null, "e": 39340, "s": 39242, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 39349, "s": 39340, "text": "Comments" }, { "code": null, "e": 39362, "s": 39349, "text": "Old Comments" }, { "code": null, "e": 39424, "s": 39362, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 39474, "s": 39424, "text": "How to insert spaces/tabs in text using HTML/CSS?" }, { "code": null, "e": 39532, "s": 39474, "text": "How to create footer to stay at the bottom of a Web page?" }, { "code": null, "e": 39580, "s": 39532, "text": "How to update Node.js and NPM to next version ?" }, { "code": null, "e": 39617, "s": 39580, "text": "Types of CSS (Cascading Style Sheet)" }, { "code": null, "e": 39659, "s": 39617, "text": "Roadmap to Become a Web Developer in 2022" }, { "code": null, "e": 39692, "s": 39659, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 39754, "s": 39692, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 39797, "s": 39754, "text": "How to fetch data from an API in ReactJS ?" } ]
How to Convert LinkedHashMap to List in Java? - GeeksforGeeks
17 Dec, 2020 LinkedHashMap is predefined class in Java which is similar to HashMap, contains key and its respective value unlike HashMap, in LinkedHashMap insertion order is preserved. We to convert LinkedHashMap to ArrayList. A Map store data in pair of Key and Value while converting a LinkedHashMAp to ArrayList we will store keys of Map in a separate List, similarly store value in another List, look example and algorithm for better understanding. Example : Input : { 1 = 3, 4 = 2, 6 = 5, 2 = 1 } output : Key -> [ 1, 4, 6, 2 ] value -> [ 3, 2, 5, 1] Input : { 2 = 10, 4 = 4, 6 = 23, 8 = 12 } output : Key -> [ 2, 4, 6, 6 ] value -> [ 10, 4, 23, 12] Algorithm : Use For/while loop for iteration in LinkedHashMap Take two different ArrayList for Keys and their Respected Values. Now iterate through for-Each Loop in LinkedhashMap and add keys and values with their defined ArrayList Pseudo code : for (Map.Entry<Object, Object> it : l.entrySet()) { l1.add(it.getKey()); l2.add(it.getValue()); } Here, l is LinkedHashMap l1 is Arraylist for keys l2 is Arraylist for Values Example: Java // Java program to convert LinkedHashMap // to List import java.util.*; import java.io.*; class GFG { public static void main(String[] args) { LinkedHashMap<Object, Object> l = new LinkedHashMap<>(); l.put(2, 5); l.put(4, 6); l.put(5, 16); l.put(6, 63); l.put(3, 18); // Taking two ArrayList ArrayList<Object> l1 = new ArrayList<>(); ArrayList<Object> l2 = new ArrayList<>(); for (Map.Entry<Object, Object> it : l.entrySet()) { l1.add(it.getKey()); l2.add(it.getValue()); } System.out.print("Key -> "); System.out.println(l1); System.out.print("Value -> "); System.out.println(l2); } } Key -> [2, 4, 5, 6, 3] Value -> [5, 6, 16, 63, 18] Time Complexity : O(n) Java-LinkedHashMap Picked Technical Scripter 2020 Java Java Programs Technical Scripter Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Stream In Java Interfaces in Java ArrayList in Java Initialize an ArrayList in Java Stack Class in Java Initializing a List in Java Convert a String to Character Array in Java Java Programming Examples Convert Double to Integer in Java Implementing a Linked List in Java using Class
[ { "code": null, "e": 25715, "s": 25684, "text": " \n17 Dec, 2020\n" }, { "code": null, "e": 25887, "s": 25715, "text": "LinkedHashMap is predefined class in Java which is similar to HashMap, contains key and its respective value unlike HashMap, in LinkedHashMap insertion order is preserved." }, { "code": null, "e": 26156, "s": 25887, "text": "We to convert LinkedHashMap to ArrayList. A Map store data in pair of Key and Value while converting a LinkedHashMAp to ArrayList we will store keys of Map in a separate List, similarly store value in another List, look example and algorithm for better understanding." }, { "code": null, "e": 26166, "s": 26156, "text": "Example :" }, { "code": null, "e": 26392, "s": 26166, "text": "Input : { 1 = 3, 4 = 2, 6 = 5, 2 = 1 }\n\noutput : Key -> [ 1, 4, 6, 2 ]\n value -> [ 3, 2, 5, 1]\n \nInput : { 2 = 10, 4 = 4, 6 = 23, 8 = 12 }\n\noutput : Key -> [ 2, 4, 6, 6 ]\n value -> [ 10, 4, 23, 12]" }, { "code": null, "e": 26404, "s": 26392, "text": "Algorithm :" }, { "code": null, "e": 26455, "s": 26404, "text": "Use For/while loop for iteration in LinkedHashMap " }, { "code": null, "e": 26522, "s": 26455, "text": "Take two different ArrayList for Keys and their Respected Values. " }, { "code": null, "e": 26626, "s": 26522, "text": "Now iterate through for-Each Loop in LinkedhashMap and add keys and values with their defined ArrayList" }, { "code": null, "e": 26641, "s": 26626, "text": "Pseudo code : " }, { "code": null, "e": 26853, "s": 26641, "text": "for (Map.Entry<Object, Object> it : l.entrySet()) {\n l1.add(it.getKey());\n l2.add(it.getValue());\n}\n\nHere, l is LinkedHashMap\n l1 is Arraylist for keys\n l2 is Arraylist for Values" }, { "code": null, "e": 26862, "s": 26853, "text": "Example:" }, { "code": null, "e": 26867, "s": 26862, "text": "Java" }, { "code": "\n\n\n\n\n\n\n// Java program to convert LinkedHashMap \n// to List \n \nimport java.util.*; \nimport java.io.*; \n \nclass GFG { \n \n public static void main(String[] args) \n { \n LinkedHashMap<Object, Object> l = new LinkedHashMap<>(); \n \n l.put(2, 5); \n l.put(4, 6); \n l.put(5, 16); \n l.put(6, 63); \n l.put(3, 18); \n \n // Taking two ArrayList \n ArrayList<Object> l1 = new ArrayList<>(); \n \n ArrayList<Object> l2 = new ArrayList<>(); \n \n for (Map.Entry<Object, Object> it : l.entrySet()) { \n l1.add(it.getKey()); \n l2.add(it.getValue()); \n } \n \n System.out.print(\"Key -> \"); \n System.out.println(l1); \n System.out.print(\"Value -> \"); \n System.out.println(l2); \n } \n}\n\n\n\n\n\n", "e": 27697, "s": 26877, "text": null }, { "code": null, "e": 27748, "s": 27697, "text": "Key -> [2, 4, 5, 6, 3]\nValue -> [5, 6, 16, 63, 18]" }, { "code": null, "e": 27771, "s": 27748, "text": "Time Complexity : O(n)" }, { "code": null, "e": 27792, "s": 27771, "text": "\nJava-LinkedHashMap\n" }, { "code": null, "e": 27801, "s": 27792, "text": "\nPicked\n" }, { "code": null, "e": 27827, "s": 27801, "text": "\nTechnical Scripter 2020\n" }, { "code": null, "e": 27834, "s": 27827, "text": "\nJava\n" }, { "code": null, "e": 27850, "s": 27834, "text": "\nJava Programs\n" }, { "code": null, "e": 27871, "s": 27850, "text": "\nTechnical Scripter\n" }, { "code": null, "e": 28076, "s": 27871, "text": "Writing code in comment? \n Please use ide.geeksforgeeks.org, \n generate link and share the link here.\n " }, { "code": null, "e": 28091, "s": 28076, "text": "Stream In Java" }, { "code": null, "e": 28110, "s": 28091, "text": "Interfaces in Java" }, { "code": null, "e": 28128, "s": 28110, "text": "ArrayList in Java" }, { "code": null, "e": 28160, "s": 28128, "text": "Initialize an ArrayList in Java" }, { "code": null, "e": 28180, "s": 28160, "text": "Stack Class in Java" }, { "code": null, "e": 28208, "s": 28180, "text": "Initializing a List in Java" }, { "code": null, "e": 28252, "s": 28208, "text": "Convert a String to Character Array in Java" }, { "code": null, "e": 28278, "s": 28252, "text": "Java Programming Examples" }, { "code": null, "e": 28312, "s": 28278, "text": "Convert Double to Integer in Java" } ]
Python VLC MediaPlayer - Getting Play Rate - GeeksforGeeks
11 Apr, 2022 In this article we will see how we can get media play rate of the MediaPlayer object in the python vlc module. VLC media player is a free and open-source portable cross-platform media player software and streaming media server developed by the VideoLAN project. MediaPlayer object is the basic object in vlc module for playing the video. We can create a MediaPlayer object with the help of MediaPlayer method. Media play rate is basically is the speed of the video, more the rate faster the video get played, default value is 1.0, in order to slow down the video set rate value less than 1. This rate can be set with the help of set_rate method. In order to do this we will use set_rate method with the MediaPlayer objectSyntax : media_player.set_rate()Argument : It takes no argumentReturn : It returns float value Below is the implementation Python3 # importing vlc moduleimport vlc # importing time moduleimport time # creating vlc media player objectmedia_player = vlc.MediaPlayer() # media objectmedia = vlc.Media("death_note.mkv") # setting media to the media playermedia_player.set_media(media) # setting play rate# doubles the speed of the videomedia_player.set_rate(2) # start playing videomedia_player.play() # wait so the video can be played for 5 seconds# irrespective for length of videotime.sleep(5) # getting play ratevalue = media_player.get_rate() # printing valueprint("Play Rate : ")print(value) Output : Play Rate : 2.0 Another example Below is the implementation Python3 # importing vlc moduleimport vlc # importing time moduleimport time # creating vlc media player objectmedia_player = vlc.MediaPlayer() # media objectmedia = vlc.Media("1mp4.mkv") # setting media to the media playermedia_player.set_media(media) # setting play rate# halves the speed of the videomedia_player.set_rate(0.5) # start playing videomedia_player.play() # wait so the video can be played for 5 seconds# irrespective for length of videotime.sleep(5) # getting play ratevalue = media_player.get_rate() # printing valueprint("Play Rate : ")print(value) Output : Play Rate : 0.5 surinderdawra388 simranarora5sos Python vlc-library Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Read a file line by line in Python How to Install PIP on Windows ? Enumerate() in Python Different ways to create Pandas Dataframe Iterate over a list in Python Python String | replace() *args and **kwargs in Python Reading and Writing to text files in Python Create a Pandas DataFrame from Lists
[ { "code": null, "e": 26213, "s": 26185, "text": "\n11 Apr, 2022" }, { "code": null, "e": 26860, "s": 26213, "text": "In this article we will see how we can get media play rate of the MediaPlayer object in the python vlc module. VLC media player is a free and open-source portable cross-platform media player software and streaming media server developed by the VideoLAN project. MediaPlayer object is the basic object in vlc module for playing the video. We can create a MediaPlayer object with the help of MediaPlayer method. Media play rate is basically is the speed of the video, more the rate faster the video get played, default value is 1.0, in order to slow down the video set rate value less than 1. This rate can be set with the help of set_rate method. " }, { "code": null, "e": 27032, "s": 26860, "text": "In order to do this we will use set_rate method with the MediaPlayer objectSyntax : media_player.set_rate()Argument : It takes no argumentReturn : It returns float value " }, { "code": null, "e": 27062, "s": 27032, "text": "Below is the implementation " }, { "code": null, "e": 27070, "s": 27062, "text": "Python3" }, { "code": "# importing vlc moduleimport vlc # importing time moduleimport time # creating vlc media player objectmedia_player = vlc.MediaPlayer() # media objectmedia = vlc.Media(\"death_note.mkv\") # setting media to the media playermedia_player.set_media(media) # setting play rate# doubles the speed of the videomedia_player.set_rate(2) # start playing videomedia_player.play() # wait so the video can be played for 5 seconds# irrespective for length of videotime.sleep(5) # getting play ratevalue = media_player.get_rate() # printing valueprint(\"Play Rate : \")print(value)", "e": 27635, "s": 27070, "text": null }, { "code": null, "e": 27646, "s": 27635, "text": "Output : " }, { "code": null, "e": 27665, "s": 27648, "text": "Play Rate : \n2.0" }, { "code": null, "e": 27711, "s": 27665, "text": "Another example Below is the implementation " }, { "code": null, "e": 27719, "s": 27711, "text": "Python3" }, { "code": "# importing vlc moduleimport vlc # importing time moduleimport time # creating vlc media player objectmedia_player = vlc.MediaPlayer() # media objectmedia = vlc.Media(\"1mp4.mkv\") # setting media to the media playermedia_player.set_media(media) # setting play rate# halves the speed of the videomedia_player.set_rate(0.5) # start playing videomedia_player.play() # wait so the video can be played for 5 seconds# irrespective for length of videotime.sleep(5) # getting play ratevalue = media_player.get_rate() # printing valueprint(\"Play Rate : \")print(value)", "e": 28278, "s": 27719, "text": null }, { "code": null, "e": 28289, "s": 28278, "text": "Output : " }, { "code": null, "e": 28308, "s": 28291, "text": "Play Rate : \n0.5" }, { "code": null, "e": 28327, "s": 28310, "text": "surinderdawra388" }, { "code": null, "e": 28343, "s": 28327, "text": "simranarora5sos" }, { "code": null, "e": 28362, "s": 28343, "text": "Python vlc-library" }, { "code": null, "e": 28369, "s": 28362, "text": "Python" }, { "code": null, "e": 28467, "s": 28369, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28485, "s": 28467, "text": "Python Dictionary" }, { "code": null, "e": 28520, "s": 28485, "text": "Read a file line by line in Python" }, { "code": null, "e": 28552, "s": 28520, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 28574, "s": 28552, "text": "Enumerate() in Python" }, { "code": null, "e": 28616, "s": 28574, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 28646, "s": 28616, "text": "Iterate over a list in Python" }, { "code": null, "e": 28672, "s": 28646, "text": "Python String | replace()" }, { "code": null, "e": 28701, "s": 28672, "text": "*args and **kwargs in Python" }, { "code": null, "e": 28745, "s": 28701, "text": "Reading and Writing to text files in Python" } ]
SQL Tutorial
SQL is a standard language for storing, manipulating and retrieving data in databases. Our SQL tutorial will teach you how to use SQL in: MySQL, SQL Server, MS Access, Oracle, Sybase, Informix, Postgres, and other database systems. With our online SQL editor, you can edit the SQL statements, and click on a button to view the result. Click on the "Try it Yourself" button to see how it works. Insert the missing statement to get all the columns from the Customers table. * FROM Customers; Start the Exercise Learn by examples! This tutorial supplements all explanations with clarifying examples. See All SQL Examples Test your SQL skills at W3Schools! Start SQL Quiz! At W3Schools you will find a complete reference for keywords and function: SQL Keyword Reference MYSQL Functions SQLServer Functions MS Access Functions SQL Quick Reference Data types and ranges for Microsoft Access, MySQL and SQL Server. SQL Data Types Get certified by completing the SQL course We just launchedW3Schools videos Get certifiedby completinga course today! If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail: [email protected] Your message has been sent to W3Schools.
[ { "code": null, "e": 88, "s": 0, "text": "SQL is a standard language for storing, manipulating and retrieving data \nin databases." }, { "code": null, "e": 233, "s": 88, "text": "Our SQL tutorial will teach you how to use SQL in:\nMySQL, SQL Server, MS Access, Oracle, Sybase, Informix, Postgres, and other database systems." }, { "code": null, "e": 336, "s": 233, "text": "With our online SQL editor, you can edit the SQL statements, and click on a button to view the result." }, { "code": null, "e": 395, "s": 336, "text": "Click on the \"Try it Yourself\" button to see how it works." }, { "code": null, "e": 473, "s": 395, "text": "Insert the missing statement to get all the columns from the Customers table." }, { "code": null, "e": 493, "s": 473, "text": " * FROM Customers;\n" }, { "code": null, "e": 512, "s": 493, "text": "Start the Exercise" }, { "code": null, "e": 600, "s": 512, "text": "Learn by examples! This tutorial supplements all explanations with clarifying examples." }, { "code": null, "e": 621, "s": 600, "text": "See All SQL Examples" }, { "code": null, "e": 656, "s": 621, "text": "Test your SQL skills at W3Schools!" }, { "code": null, "e": 672, "s": 656, "text": "Start SQL Quiz!" }, { "code": null, "e": 747, "s": 672, "text": "At W3Schools you will find a complete reference for keywords and function:" }, { "code": null, "e": 769, "s": 747, "text": "SQL Keyword Reference" }, { "code": null, "e": 785, "s": 769, "text": "MYSQL Functions" }, { "code": null, "e": 805, "s": 785, "text": "SQLServer Functions" }, { "code": null, "e": 825, "s": 805, "text": "MS Access Functions" }, { "code": null, "e": 845, "s": 825, "text": "SQL Quick Reference" }, { "code": null, "e": 911, "s": 845, "text": "Data types and ranges for Microsoft Access, MySQL and SQL Server." }, { "code": null, "e": 926, "s": 911, "text": "SQL Data Types" }, { "code": null, "e": 969, "s": 926, "text": "Get certified by completing the SQL course" }, { "code": null, "e": 1002, "s": 969, "text": "We just launchedW3Schools videos" }, { "code": null, "e": 1044, "s": 1002, "text": "Get certifiedby completinga course today!" }, { "code": null, "e": 1151, "s": 1044, "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": 1170, "s": 1151, "text": "[email protected]" } ]
How to visualize a data frame that contains missing values in R?
If a data frame contains missing value then visualising it in base R is not easily possible but we can make use of visdat package for this purpose. The vis_dat function of visdat package helps to visualize any data frame even if it contains missing values. For example, if a data frame df contains missing value then it can be visualized as vis_dat(df). Consider the below data frame − Live Demo > x1<-sample(c(NA,1:2),20,replace=TRUE) > x2<-sample(c(NA,21:24),20,replace=TRUE) > x3<-sample(c(NA,5,10),20,replace=TRUE) > df1<-data.frame(x1,x2,x3) > df1 x1 x2 x3 1 1 23 10 2 1 23 NA 3 NA NA 10 4 NA NA 10 5 1 24 NA 6 2 22 NA 7 2 24 NA 8 2 24 NA 9 2 21 NA 10 1 23 10 11 NA 24 NA 12 2 22 NA 13 2 NA 10 14 NA 24 10 15 2 NA 5 16 2 21 NA 17 2 23 NA 18 2 NA 5 19 NA 21 10 20 2 NA 5 Loading visdat package and creating the plot of the data frame − > library(visdat) > vis_dat(df1) Live Demo > y1<-sample(c(NA,rpois(5,2)),20,replace=TRUE) > y2<-rnorm(20) > y3<-sample(c(NA,rnorm(5,2,2.1)),20,replace=TRUE) > y4<-sample(c(NA,runif(5,2,3)),20,replace=TRUE) > df2<-data.frame(y1,y2,y3,y4) > df2 y1 y2 y3 y4 1 4 0.61081616 NA NA 2 3 0.97203884 NA 2.039603 3 1 -0.19848158 2.798295 2.996374 4 NA -0.06643532 1.327976 NA 5 1 -0.08782965 1.327976 2.996374 6 1 -1.74682203 NA 2.996374 7 NA -1.07706177 3.255620 2.039603 8 1 -0.47827253 1.327976 2.670070 9 1 -1.52099043 1.524140 2.773155 10 3 0.80431131 2.798295 2.773155 11 4 -0.92503650 NA 2.996374 12 1 0.09717851 1.524140 2.429227 13 NA 0.59296946 NA 2.039603 14 4 0.40156867 1.524140 2.996374 15 1 -0.25442642 NA 2.773155 16 1 -1.65687286 2.798295 2.996374 17 1 0.35774521 1.524140 2.773155 18 NA 0.09490436 1.524140 2.773155 19 4 -0.63289635 NA 2.773155 20 1 -0.48500639 1.524140 NA > vis_dat(df2)
[ { "code": null, "e": 1416, "s": 1062, "text": "If a data frame contains missing value then visualising it in base R is not easily possible but we can make use of visdat package for this purpose. The vis_dat function of visdat package helps to visualize any data frame even if it contains missing values. For example, if a data frame df contains missing value then it can be visualized as vis_dat(df)." }, { "code": null, "e": 1448, "s": 1416, "text": "Consider the below data frame −" }, { "code": null, "e": 1458, "s": 1448, "text": "Live Demo" }, { "code": null, "e": 1615, "s": 1458, "text": "> x1<-sample(c(NA,1:2),20,replace=TRUE)\n> x2<-sample(c(NA,21:24),20,replace=TRUE)\n> x3<-sample(c(NA,5,10),20,replace=TRUE)\n> df1<-data.frame(x1,x2,x3)\n> df1" }, { "code": null, "e": 1838, "s": 1615, "text": " x1 x2 x3\n1 1 23 10\n2 1 23 NA\n3 NA NA 10\n4 NA NA 10\n5 1 24 NA\n6 2 22 NA\n7 2 24 NA\n8 2 24 NA\n9 2 21 NA\n10 1 23 10\n11 NA 24 NA\n12 2 22 NA\n13 2 NA 10\n14 NA 24 10\n15 2 NA 5\n16 2 21 NA\n17 2 23 NA\n18 2 NA 5\n19 NA 21 10\n20 2 NA 5" }, { "code": null, "e": 1903, "s": 1838, "text": "Loading visdat package and creating the plot of the data frame −" }, { "code": null, "e": 1936, "s": 1903, "text": "> library(visdat)\n> vis_dat(df1)" }, { "code": null, "e": 1946, "s": 1936, "text": "Live Demo" }, { "code": null, "e": 2146, "s": 1946, "text": "> y1<-sample(c(NA,rpois(5,2)),20,replace=TRUE)\n> y2<-rnorm(20)\n> y3<-sample(c(NA,rnorm(5,2,2.1)),20,replace=TRUE)\n> y4<-sample(c(NA,runif(5,2,3)),20,replace=TRUE)\n> df2<-data.frame(y1,y2,y3,y4)\n> df2" }, { "code": null, "e": 2787, "s": 2146, "text": " y1 y2 y3 y4\n1 4 0.61081616 NA NA\n2 3 0.97203884 NA 2.039603\n3 1 -0.19848158 2.798295 2.996374\n4 NA -0.06643532 1.327976 NA\n5 1 -0.08782965 1.327976 2.996374\n6 1 -1.74682203 NA 2.996374\n7 NA -1.07706177 3.255620 2.039603\n8 1 -0.47827253 1.327976 2.670070\n9 1 -1.52099043 1.524140 2.773155\n10 3 0.80431131 2.798295 2.773155\n11 4 -0.92503650 NA 2.996374\n12 1 0.09717851 1.524140 2.429227\n13 NA 0.59296946 NA 2.039603\n14 4 0.40156867 1.524140 2.996374\n15 1 -0.25442642 NA 2.773155\n16 1 -1.65687286 2.798295 2.996374\n17 1 0.35774521 1.524140 2.773155\n18 NA 0.09490436 1.524140 2.773155\n19 4 -0.63289635 NA 2.773155\n20 1 -0.48500639 1.524140 NA" }, { "code": null, "e": 2802, "s": 2787, "text": "> vis_dat(df2)" } ]
Clojure - Java Interface
As we already know, Clojure code runs on the Java virtual environment at the end. Thus it only makes sense that Clojure is able to utilize all of the functionalities from Java. In this chapter, let’s discuss the correlation between Clojure and Java. Java methods can be called by using the dot notation. An example is strings. Since all strings in Clojure are anyway Java strings, you can call normal Java methods on strings. An example on how this is done is shown in the following program. (ns Project (:gen-class)) (defn Example [] (println (.toUpperCase "Hello World"))) (Example) The above program produces the following output. You can see from the code that if you just call the dot notation for any string method, it will also work in Clojure. HELLO WORLD You can also call Java methods with parameters. An example on how this is done is shown in the following program. (ns Project (:gen-class)) (defn Example [] (println (.indexOf "Hello World","e"))) (Example) The above program produces the following output. You can see from the above code, that we are passing the parameter “e” to the indexOf method. The above program produces the following output. 1 Objects can be created in Clojure by using the ‘new’ keyword similar to what is done in Java. An example on how this is done is shown in the following program. (ns Project (:gen-class)) (defn Example [] (def str1 (new String "Hello")) (println str1)) (Example) The above program produces the following output. You can see from the above code, that we can use the ‘new’ keyword to create a new object from the existing String class from Java. We can pass the value while creating the object, just like we do in Java. The above program produces the following output. Hello Following is another example which shows how we can create an object of the Integer class and use them in the normal Clojure commands. (ns Project (:gen-class)) (defn Example [] (def my-int(new Integer 1)) (println (+ 2 my-int))) (Example) The above program produces the following output. 3 We can also use the import command to include Java libraries in the namespace so that the classes and methods can be accessed easily. The following example shows how we can use the import command. In the example we are using the import command to import the classes from the java.util.stack library. We can then use the push and pop method of the stack class as they are. (ns Project (:gen-class)) (import java.util.Stack) (defn Example [] (let [stack (Stack.)] (.push stack "First Element") (.push stack "Second Element") (println (first stack)))) (Example) The above program produces the following output. First Element Clojure code can be run using the Java command. Following is the syntax of how this can be done. java -jar clojure-1.2.0.jar -i main.clj You have to mention the Clojure jar file, so that all Clojure-based classes will be loaded in the JVM. The ‘main.clj’ file is the Clojure code file which needs to be executed. Clojure can use many of the built-in functions of Java. Some of them are − Math PI function − Clojure can use the Math method to the value of PI. Following is an example code. (ns Project (:gen-class)) (defn Example [] (println (. Math PI))) (Example) The above code produces the following output. 3.141592653589793 System Properties − Clojure can also query the system properties. Following is an example code. (ns Project (:gen-class)) (defn Example [] (println (.. System getProperties (get "java.version")))) (Example) Depending on the version of Java on the system, the corresponding value will be displayed. Following is an example output. 1.8.0_45 Print Add Notes Bookmark this page
[ { "code": null, "e": 2624, "s": 2374, "text": "As we already know, Clojure code runs on the Java virtual environment at the end. Thus it only makes sense that Clojure is able to utilize all of the functionalities from Java. In this chapter, let’s discuss the correlation between Clojure and Java." }, { "code": null, "e": 2800, "s": 2624, "text": "Java methods can be called by using the dot notation. An example is strings. Since all strings in Clojure are anyway Java strings, you can call normal Java methods on strings." }, { "code": null, "e": 2866, "s": 2800, "text": "An example on how this is done is shown in the following program." }, { "code": null, "e": 2965, "s": 2866, "text": "(ns Project\n (:gen-class))\n(defn Example []\n (println (.toUpperCase \"Hello World\")))\n(Example)" }, { "code": null, "e": 3132, "s": 2965, "text": "The above program produces the following output. You can see from the code that if you just call the dot notation for any string method, it will also work in Clojure." }, { "code": null, "e": 3145, "s": 3132, "text": "HELLO WORLD\n" }, { "code": null, "e": 3259, "s": 3145, "text": "You can also call Java methods with parameters. An example on how this is done is shown in the following program." }, { "code": null, "e": 3358, "s": 3259, "text": "(ns Project\n (:gen-class))\n(defn Example []\n (println (.indexOf \"Hello World\",\"e\")))\n(Example)" }, { "code": null, "e": 3550, "s": 3358, "text": "The above program produces the following output. You can see from the above code, that we are passing the parameter “e” to the indexOf method. The above program produces the following output." }, { "code": null, "e": 3553, "s": 3550, "text": "1\n" }, { "code": null, "e": 3647, "s": 3553, "text": "Objects can be created in Clojure by using the ‘new’ keyword similar to what is done in Java." }, { "code": null, "e": 3713, "s": 3647, "text": "An example on how this is done is shown in the following program." }, { "code": null, "e": 3823, "s": 3713, "text": "(ns Project\n (:gen-class))\n(defn Example []\n (def str1 (new String \"Hello\"))\n (println str1))\n(Example)" }, { "code": null, "e": 4127, "s": 3823, "text": "The above program produces the following output. You can see from the above code, that we can use the ‘new’ keyword to create a new object from the existing String class from Java. We can pass the value while creating the object, just like we do in Java. The above program produces the following output." }, { "code": null, "e": 4134, "s": 4127, "text": "Hello\n" }, { "code": null, "e": 4269, "s": 4134, "text": "Following is another example which shows how we can create an object of the Integer class and use them in the normal Clojure commands." }, { "code": null, "e": 4383, "s": 4269, "text": "(ns Project\n (:gen-class))\n(defn Example []\n (def my-int(new Integer 1))\n (println (+ 2 my-int)))\n(Example)" }, { "code": null, "e": 4432, "s": 4383, "text": "The above program produces the following output." }, { "code": null, "e": 4435, "s": 4432, "text": "3\n" }, { "code": null, "e": 4569, "s": 4435, "text": "We can also use the import command to include Java libraries in the namespace so that the classes and methods can be accessed easily." }, { "code": null, "e": 4807, "s": 4569, "text": "The following example shows how we can use the import command. In the example we are using the import command to import the classes from the java.util.stack library. We can then use the push and pop method of the stack class as they are." }, { "code": null, "e": 5009, "s": 4807, "text": "(ns Project\n (:gen-class))\n(import java.util.Stack)\n(defn Example []\n (let [stack (Stack.)]\n (.push stack \"First Element\")\n (.push stack \"Second Element\")\n (println (first stack))))\n(Example)" }, { "code": null, "e": 5058, "s": 5009, "text": "The above program produces the following output." }, { "code": null, "e": 5073, "s": 5058, "text": "First Element\n" }, { "code": null, "e": 5170, "s": 5073, "text": "Clojure code can be run using the Java command. Following is the syntax of how this can be done." }, { "code": null, "e": 5211, "s": 5170, "text": "java -jar clojure-1.2.0.jar -i main.clj\n" }, { "code": null, "e": 5387, "s": 5211, "text": "You have to mention the Clojure jar file, so that all Clojure-based classes will be loaded in the JVM. The ‘main.clj’ file is the Clojure code file which needs to be executed." }, { "code": null, "e": 5462, "s": 5387, "text": "Clojure can use many of the built-in functions of Java. Some of them are −" }, { "code": null, "e": 5563, "s": 5462, "text": "Math PI function − Clojure can use the Math method to the value of PI. Following is an example code." }, { "code": null, "e": 5645, "s": 5563, "text": "(ns Project\n (:gen-class))\n(defn Example []\n (println (. Math PI)))\n(Example)" }, { "code": null, "e": 5691, "s": 5645, "text": "The above code produces the following output." }, { "code": null, "e": 5710, "s": 5691, "text": "3.141592653589793\n" }, { "code": null, "e": 5806, "s": 5710, "text": "System Properties − Clojure can also query the system properties. Following is an example code." }, { "code": null, "e": 5923, "s": 5806, "text": "(ns Project\n (:gen-class))\n(defn Example []\n (println (.. System getProperties (get \"java.version\"))))\n(Example)" }, { "code": null, "e": 6046, "s": 5923, "text": "Depending on the version of Java on the system, the corresponding value will be displayed. Following is an example output." }, { "code": null, "e": 6056, "s": 6046, "text": "1.8.0_45\n" }, { "code": null, "e": 6063, "s": 6056, "text": " Print" }, { "code": null, "e": 6074, "s": 6063, "text": " Add Notes" } ]
Data Mining - Rule Based Classification
Rule-based classifier makes use of a set of IF-THEN rules for classification. We can express a rule in the following from − Let us consider a rule R1, R1: IF age = youth AND student = yes THEN buy_computer = yes Points to remember − The IF part of the rule is called rule antecedent or precondition. The IF part of the rule is called rule antecedent or precondition. The THEN part of the rule is called rule consequent. The THEN part of the rule is called rule consequent. The antecedent part the condition consist of one or more attribute tests and these tests are logically ANDed. The antecedent part the condition consist of one or more attribute tests and these tests are logically ANDed. The consequent part consists of class prediction. The consequent part consists of class prediction. Note − We can also write rule R1 as follows − R1: (age = youth) ^ (student = yes))(buys computer = yes) If the condition holds true for a given tuple, then the antecedent is satisfied. Here we will learn how to build a rule-based classifier by extracting IF-THEN rules from a decision tree. Points to remember − To extract a rule from a decision tree − One rule is created for each path from the root to the leaf node. One rule is created for each path from the root to the leaf node. To form a rule antecedent, each splitting criterion is logically ANDed. To form a rule antecedent, each splitting criterion is logically ANDed. The leaf node holds the class prediction, forming the rule consequent. The leaf node holds the class prediction, forming the rule consequent. Sequential Covering Algorithm can be used to extract IF-THEN rules form the training data. We do not require to generate a decision tree first. In this algorithm, each rule for a given class covers many of the tuples of that class. Some of the sequential Covering Algorithms are AQ, CN2, and RIPPER. As per the general strategy the rules are learned one at a time. For each time rules are learned, a tuple covered by the rule is removed and the process continues for the rest of the tuples. This is because the path to each leaf in a decision tree corresponds to a rule. Note − The Decision tree induction can be considered as learning a set of rules simultaneously. The Following is the sequential learning Algorithm where rules are learned for one class at a time. When learning a rule from a class Ci, we want the rule to cover all the tuples from class C only and no tuple form any other class. Algorithm: Sequential Covering Input: D, a data set class-labeled tuples, Att_vals, the set of all attributes and their possible values. Output: A Set of IF-THEN rules. Method: Rule_set={ }; // initial set of rules learned is empty for each class c do repeat Rule = Learn_One_Rule(D, Att_valls, c); remove tuples covered by Rule form D; until termination condition; Rule_set=Rule_set+Rule; // add a new rule to rule-set end for return Rule_Set; The rule is pruned is due to the following reason − The Assessment of quality is made on the original set of training data. The rule may perform well on training data but less well on subsequent data. That's why the rule pruning is required. The Assessment of quality is made on the original set of training data. The rule may perform well on training data but less well on subsequent data. That's why the rule pruning is required. The rule is pruned by removing conjunct. The rule R is pruned, if pruned version of R has greater quality than what was assessed on an independent set of tuples. The rule is pruned by removing conjunct. The rule R is pruned, if pruned version of R has greater quality than what was assessed on an independent set of tuples. FOIL is one of the simple and effective method for rule pruning. For a given rule R, where pos and neg is the number of positive tuples covered by R, respectively. Note − This value will increase with the accuracy of R on the pruning set. Hence, if the FOIL_Prune value is higher for the pruned version of R, then we prune R. 42 Lectures 1.5 hours Ravi Kiran 141 Lectures 13 hours Arnab Chakraborty 26 Lectures 8.5 hours Parth Panjabi 65 Lectures 6 hours Arnab Chakraborty 75 Lectures 13 hours Eduonix Learning Solutions 64 Lectures 10.5 hours Eduonix Learning Solutions Print Add Notes Bookmark this page
[ { "code": null, "e": 2234, "s": 2110, "text": "Rule-based classifier makes use of a set of IF-THEN rules for classification. We can express a rule in the following from −" }, { "code": null, "e": 2261, "s": 2234, "text": "Let us consider a rule R1," }, { "code": null, "e": 2326, "s": 2261, "text": "R1: IF age = youth AND student = yes \n THEN buy_computer = yes" }, { "code": null, "e": 2347, "s": 2326, "text": "Points to remember −" }, { "code": null, "e": 2414, "s": 2347, "text": "The IF part of the rule is called rule antecedent or precondition." }, { "code": null, "e": 2481, "s": 2414, "text": "The IF part of the rule is called rule antecedent or precondition." }, { "code": null, "e": 2534, "s": 2481, "text": "The THEN part of the rule is called rule consequent." }, { "code": null, "e": 2587, "s": 2534, "text": "The THEN part of the rule is called rule consequent." }, { "code": null, "e": 2697, "s": 2587, "text": "The antecedent part the condition consist of one or more attribute tests and these tests are logically ANDed." }, { "code": null, "e": 2807, "s": 2697, "text": "The antecedent part the condition consist of one or more attribute tests and these tests are logically ANDed." }, { "code": null, "e": 2857, "s": 2807, "text": "The consequent part consists of class prediction." }, { "code": null, "e": 2907, "s": 2857, "text": "The consequent part consists of class prediction." }, { "code": null, "e": 2953, "s": 2907, "text": "Note − We can also write rule R1 as follows −" }, { "code": null, "e": 3012, "s": 2953, "text": "R1: (age = youth) ^ (student = yes))(buys computer = yes)\n" }, { "code": null, "e": 3093, "s": 3012, "text": "If the condition holds true for a given tuple, then the antecedent is satisfied." }, { "code": null, "e": 3199, "s": 3093, "text": "Here we will learn how to build a rule-based classifier by extracting IF-THEN rules from a decision tree." }, { "code": null, "e": 3220, "s": 3199, "text": "Points to remember −" }, { "code": null, "e": 3261, "s": 3220, "text": "To extract a rule from a decision tree −" }, { "code": null, "e": 3327, "s": 3261, "text": "One rule is created for each path from the root to the leaf node." }, { "code": null, "e": 3393, "s": 3327, "text": "One rule is created for each path from the root to the leaf node." }, { "code": null, "e": 3465, "s": 3393, "text": "To form a rule antecedent, each splitting criterion is logically ANDed." }, { "code": null, "e": 3537, "s": 3465, "text": "To form a rule antecedent, each splitting criterion is logically ANDed." }, { "code": null, "e": 3608, "s": 3537, "text": "The leaf node holds the class prediction, forming the rule consequent." }, { "code": null, "e": 3679, "s": 3608, "text": "The leaf node holds the class prediction, forming the rule consequent." }, { "code": null, "e": 3911, "s": 3679, "text": "Sequential Covering Algorithm can be used to extract IF-THEN rules form the training data. We do not require to generate a decision tree first. In this algorithm, each rule for a given class covers many of the tuples of that class." }, { "code": null, "e": 4250, "s": 3911, "text": "Some of the sequential Covering Algorithms are AQ, CN2, and RIPPER. As per the general strategy the rules are learned one at a time. For each time rules are learned, a tuple covered by the rule is removed and the process continues for the rest of the tuples. This is because the path to each leaf in a decision tree corresponds to a rule." }, { "code": null, "e": 4346, "s": 4250, "text": "Note − The Decision tree induction can be considered as learning a set of rules simultaneously." }, { "code": null, "e": 4578, "s": 4346, "text": "The Following is the sequential learning Algorithm where rules are learned for one class at a time. When learning a rule from a class Ci, we want the rule to cover all the tuples from class C only and no tuple form any other class." }, { "code": null, "e": 5058, "s": 4578, "text": "Algorithm: Sequential Covering\n\nInput: \nD, a data set class-labeled tuples,\nAtt_vals, the set of all attributes and their possible values.\n\nOutput: A Set of IF-THEN rules.\nMethod:\nRule_set={ }; // initial set of rules learned is empty\n\nfor each class c do\n \n repeat\n Rule = Learn_One_Rule(D, Att_valls, c);\n remove tuples covered by Rule form D;\n until termination condition;\n \n Rule_set=Rule_set+Rule; // add a new rule to rule-set\nend for\nreturn Rule_Set;\n" }, { "code": null, "e": 5110, "s": 5058, "text": "The rule is pruned is due to the following reason −" }, { "code": null, "e": 5300, "s": 5110, "text": "The Assessment of quality is made on the original set of training data. The rule may perform well on training data but less well on subsequent data. That's why the rule pruning is required." }, { "code": null, "e": 5490, "s": 5300, "text": "The Assessment of quality is made on the original set of training data. The rule may perform well on training data but less well on subsequent data. That's why the rule pruning is required." }, { "code": null, "e": 5652, "s": 5490, "text": "The rule is pruned by removing conjunct. The rule R is pruned, if pruned version of R has greater quality than what was assessed on an independent set of tuples." }, { "code": null, "e": 5814, "s": 5652, "text": "The rule is pruned by removing conjunct. The rule R is pruned, if pruned version of R has greater quality than what was assessed on an independent set of tuples." }, { "code": null, "e": 5899, "s": 5814, "text": "FOIL is one of the simple and effective method for rule pruning. For a given rule R," }, { "code": null, "e": 5978, "s": 5899, "text": "where pos and neg is the number of positive tuples covered by R, respectively." }, { "code": null, "e": 6140, "s": 5978, "text": "Note − This value will increase with the accuracy of R on the pruning set. Hence, if the FOIL_Prune value is higher for the pruned version of R, then we prune R." }, { "code": null, "e": 6175, "s": 6140, "text": "\n 42 Lectures \n 1.5 hours \n" }, { "code": null, "e": 6187, "s": 6175, "text": " Ravi Kiran" }, { "code": null, "e": 6222, "s": 6187, "text": "\n 141 Lectures \n 13 hours \n" }, { "code": null, "e": 6241, "s": 6222, "text": " Arnab Chakraborty" }, { "code": null, "e": 6276, "s": 6241, "text": "\n 26 Lectures \n 8.5 hours \n" }, { "code": null, "e": 6291, "s": 6276, "text": " Parth Panjabi" }, { "code": null, "e": 6324, "s": 6291, "text": "\n 65 Lectures \n 6 hours \n" }, { "code": null, "e": 6343, "s": 6324, "text": " Arnab Chakraborty" }, { "code": null, "e": 6377, "s": 6343, "text": "\n 75 Lectures \n 13 hours \n" }, { "code": null, "e": 6405, "s": 6377, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 6441, "s": 6405, "text": "\n 64 Lectures \n 10.5 hours \n" }, { "code": null, "e": 6469, "s": 6441, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 6476, "s": 6469, "text": " Print" }, { "code": null, "e": 6487, "s": 6476, "text": " Add Notes" } ]
How to use Scikit-Learn Datasets for Machine Learning | by Wafiq Syed | Towards Data Science
Scikit-Learn provides clean datasets for you to use when building ML models. And when I say clean, I mean the type of clean that’s ready to be used to train a ML model. The best part? The datasets come with the Scikit-Learn package itself. You don’t need to download anything. Within just a few lines of code, you’ll be working with the data. Having ready-made datasets is a huge asset because you can get straight to creating models, not having to spend time obtaining, cleaning, and transforming the data — something data scientists spend lots of their time on. Even with all the ground work complete, you might find using the Scikit-Learn datasets a bit confusing at first. Not to worry, in few minutes you’re going to know exactly how to use the datasets and be well on your way to exploring the world of Artificial Intelligence. This article assumes you have python, scikit-learn, pandas, and Jupyter Notebook (or you may use Google Collab) installed. Let’s begin. Scikit-Learn provides seven datasets, which they call toy datasets. Don’t be fooled by the word “toy”. These datasets are powerful and serve as a strong starting point for learning ML. Here are few of the datasets and how ML can be used: Boston House Prices — use ML to predict house prices based on attributes such as number of rooms, crime rate in that town Breast Cancer Wisconsin (diagnostic) dataset — use ML to diagnose cancer scans as benign (does not spread to the rest of the body) or malignant (spreads to rest of the body) Wine Recognition — use ML to identify the type of wine based on chemical features In this article, we’ll be working with the “Breast Cancer Wisconsin” dataset. We will import the data and understand how to read it. As a bonus, we’ll build a simple ML model that is able to classify cancer scans either as malignant or benign. To read more about the datasets, click here for Scikit-Learn’s documentation. The datasets can be found in sklearn.datasets.Let’s import the data. We first import datasets which holds all the seven datasets. from sklearn import datasets Each dataset has a corresponding function used to load the dataset. These functions follow the same format: “load_DATASET()”, where DATASET refers to the name of the dataset. For the breast cancer dataset, we use load_breast_cancer(). Similarly, for the wine dataset we would use load_wine(). Let’s load the dataset and store it into a variable called data. data = datasets.load_breast_cancer() So far, so good. These load functions (such as load_breast_cancer()) don’t return data in the tabular format we may expect. They return a Bunch object. Don’t know what a Bunch is? No worries. Think of a Bunch object as Scikit-Learn’s fancy name for a dictionary Let’s quickly refresh our memory on dictionaries. A dictionary is a type of data structure that stores data as keys and values. Think of a dictionary just like the dictionary book you’re used to. You search for words (keys), and get their definition (value). In programming, you can make the keys and values anything you choose (words, numbers, etc.). For example, to store a phonebook, the keys can be names, and the values can be phone numbers. So you see, a dictionary in Python isn’t just limited to the typical dictionary you’re familiar with, but can be applied to whatever you like. Scikit’s dictionary or Bunchis really powerful. Let’s begin this dictionary by looking at its keys. print(data.keys()) We get the following keys: data is all the feature data (the attributes of the scan that help us identify if the tumor is malignant or benign, such as radius, area, etc.) in a NumPy array target is the target data (the variable you want to predict, in this case whether the tumor is malignant or benign) in a NumPy array, These two keys are the actual data. The remaining keys (below), serve a descriptive purpose. It’s important to note that all of Scikit-Learn datasets are divided into data and target. data represents the features, which are the variables that help the model learn how to predict. target includes the actual labels. In our case, the target data is one column classifies the tumor as either 0 indicating malignant or 1 for benign. feature_names are the names of the feature variables, in other words names of the columns in data target_names is the name(s) of the target variable(s), in other words name(s) of the target column(s) DESCR , short for DESCRIPTION, is a description of the dataset filename is the path to the actual file of the data in CSV format. To look at a key’s value, you can type data.KEYNAME where KEYNAME represents the key. So if we wanted to see the description of the dataset, print(data.DESCR) Here’s a preview of the output (the full description is too long to include): You can also view the data set info by visiting Scikit-Learn’s documentation. Their documentation is much more readable and neat. Now that we understand what the load function returns, let’s see how we can use the dataset in our ML model. Before anything, if you want to explore the dataset, you can use pandas to do so. Here’s how: # Import pandasimport pandas as pd# Read the DataFrame, first using the feature datadf = pd.DataFrame(data.data, columns=data.feature_names)# Add a target column, and fill it with the target datadf['target'] = data.target# Show the first five rowsdf.head() You should be proud. You’ve loaded a dataset into a Pandas dataframe, that’s ready to be explored and used. To really see the value of this dataset, run df.info() There are a few things to observe: There aren’t any missing values, all the columns have 569 values. This saves us time from having to account for missing values. All the data types are numerical. This is important because Scikit-Learn models do not accept categorical variables. In the real world, when we get categorical variables, we transform them into numerical variables. Scikit-Learn’s datasets are free of categorical variables. Hence, Scikit-Learn takes care of the data cleansing work. Their datasets are extremely valuable. You will benefit from learning ML by using them. Finally, the exciting part. Let’s build a model that classifies cancer tumors as malignant (spreading) or benign (non-spreading). This will show you how to use the data for your own models. We’ll build a simple K-Nearest Neighbors model. First, let’s split the dataset into two, one for training the model — giving it data to learn from, and the second for testing the model — seeing how well the model performs on data (scans) it hasn’t seen before. # Store the feature dataX = data.data# store the target datay = data.target# split the data using Scikit-Learn's train_test_splitfrom sklearn.model_selection import train_test_splitX_train, X_test, y_train, y_test = train_test_split(X, y) This gives us two datasets —one for training and one for testing. Let’s get onto training the model. from sklearn.neighbors import KNeighborsClassifierlogreg = KNeighborsClassifier(n_neighbors=6)logreg.fit(X_train, y_train)logreg.score(X_test, y_test) Did you get an output of 0.909? This means the model is 91% accurate! Isn’t that amazing? In just a few minutes you made a model that classifies cancer scans with 90% accuracy. Now, of course, it’s more complicated than this in the real world, but you’re off to a great start. You will learn a lot by trying to build models using Scikit-Learn’s datasets. When in doubt, just Google any question you have. There’s a huge machine learning community, and it’s likely your question’s been asked before. Happy AI learning!
[ { "code": null, "e": 515, "s": 172, "text": "Scikit-Learn provides clean datasets for you to use when building ML models. And when I say clean, I mean the type of clean that’s ready to be used to train a ML model. The best part? The datasets come with the Scikit-Learn package itself. You don’t need to download anything. Within just a few lines of code, you’ll be working with the data." }, { "code": null, "e": 736, "s": 515, "text": "Having ready-made datasets is a huge asset because you can get straight to creating models, not having to spend time obtaining, cleaning, and transforming the data — something data scientists spend lots of their time on." }, { "code": null, "e": 1142, "s": 736, "text": "Even with all the ground work complete, you might find using the Scikit-Learn datasets a bit confusing at first. Not to worry, in few minutes you’re going to know exactly how to use the datasets and be well on your way to exploring the world of Artificial Intelligence. This article assumes you have python, scikit-learn, pandas, and Jupyter Notebook (or you may use Google Collab) installed. Let’s begin." }, { "code": null, "e": 1380, "s": 1142, "text": "Scikit-Learn provides seven datasets, which they call toy datasets. Don’t be fooled by the word “toy”. These datasets are powerful and serve as a strong starting point for learning ML. Here are few of the datasets and how ML can be used:" }, { "code": null, "e": 1502, "s": 1380, "text": "Boston House Prices — use ML to predict house prices based on attributes such as number of rooms, crime rate in that town" }, { "code": null, "e": 1676, "s": 1502, "text": "Breast Cancer Wisconsin (diagnostic) dataset — use ML to diagnose cancer scans as benign (does not spread to the rest of the body) or malignant (spreads to rest of the body)" }, { "code": null, "e": 1758, "s": 1676, "text": "Wine Recognition — use ML to identify the type of wine based on chemical features" }, { "code": null, "e": 2080, "s": 1758, "text": "In this article, we’ll be working with the “Breast Cancer Wisconsin” dataset. We will import the data and understand how to read it. As a bonus, we’ll build a simple ML model that is able to classify cancer scans either as malignant or benign. To read more about the datasets, click here for Scikit-Learn’s documentation." }, { "code": null, "e": 2210, "s": 2080, "text": "The datasets can be found in sklearn.datasets.Let’s import the data. We first import datasets which holds all the seven datasets." }, { "code": null, "e": 2239, "s": 2210, "text": "from sklearn import datasets" }, { "code": null, "e": 2597, "s": 2239, "text": "Each dataset has a corresponding function used to load the dataset. These functions follow the same format: “load_DATASET()”, where DATASET refers to the name of the dataset. For the breast cancer dataset, we use load_breast_cancer(). Similarly, for the wine dataset we would use load_wine(). Let’s load the dataset and store it into a variable called data." }, { "code": null, "e": 2634, "s": 2597, "text": "data = datasets.load_breast_cancer()" }, { "code": null, "e": 2826, "s": 2634, "text": "So far, so good. These load functions (such as load_breast_cancer()) don’t return data in the tabular format we may expect. They return a Bunch object. Don’t know what a Bunch is? No worries." }, { "code": null, "e": 2896, "s": 2826, "text": "Think of a Bunch object as Scikit-Learn’s fancy name for a dictionary" }, { "code": null, "e": 3486, "s": 2896, "text": "Let’s quickly refresh our memory on dictionaries. A dictionary is a type of data structure that stores data as keys and values. Think of a dictionary just like the dictionary book you’re used to. You search for words (keys), and get their definition (value). In programming, you can make the keys and values anything you choose (words, numbers, etc.). For example, to store a phonebook, the keys can be names, and the values can be phone numbers. So you see, a dictionary in Python isn’t just limited to the typical dictionary you’re familiar with, but can be applied to whatever you like." }, { "code": null, "e": 3586, "s": 3486, "text": "Scikit’s dictionary or Bunchis really powerful. Let’s begin this dictionary by looking at its keys." }, { "code": null, "e": 3605, "s": 3586, "text": "print(data.keys())" }, { "code": null, "e": 3632, "s": 3605, "text": "We get the following keys:" }, { "code": null, "e": 3793, "s": 3632, "text": "data is all the feature data (the attributes of the scan that help us identify if the tumor is malignant or benign, such as radius, area, etc.) in a NumPy array" }, { "code": null, "e": 3927, "s": 3793, "text": "target is the target data (the variable you want to predict, in this case whether the tumor is malignant or benign) in a NumPy array," }, { "code": null, "e": 4356, "s": 3927, "text": "These two keys are the actual data. The remaining keys (below), serve a descriptive purpose. It’s important to note that all of Scikit-Learn datasets are divided into data and target. data represents the features, which are the variables that help the model learn how to predict. target includes the actual labels. In our case, the target data is one column classifies the tumor as either 0 indicating malignant or 1 for benign." }, { "code": null, "e": 4454, "s": 4356, "text": "feature_names are the names of the feature variables, in other words names of the columns in data" }, { "code": null, "e": 4556, "s": 4454, "text": "target_names is the name(s) of the target variable(s), in other words name(s) of the target column(s)" }, { "code": null, "e": 4619, "s": 4556, "text": "DESCR , short for DESCRIPTION, is a description of the dataset" }, { "code": null, "e": 4686, "s": 4619, "text": "filename is the path to the actual file of the data in CSV format." }, { "code": null, "e": 4827, "s": 4686, "text": "To look at a key’s value, you can type data.KEYNAME where KEYNAME represents the key. So if we wanted to see the description of the dataset," }, { "code": null, "e": 4846, "s": 4827, "text": "print(data.DESCR) " }, { "code": null, "e": 4924, "s": 4846, "text": "Here’s a preview of the output (the full description is too long to include):" }, { "code": null, "e": 5054, "s": 4924, "text": "You can also view the data set info by visiting Scikit-Learn’s documentation. Their documentation is much more readable and neat." }, { "code": null, "e": 5257, "s": 5054, "text": "Now that we understand what the load function returns, let’s see how we can use the dataset in our ML model. Before anything, if you want to explore the dataset, you can use pandas to do so. Here’s how:" }, { "code": null, "e": 5514, "s": 5257, "text": "# Import pandasimport pandas as pd# Read the DataFrame, first using the feature datadf = pd.DataFrame(data.data, columns=data.feature_names)# Add a target column, and fill it with the target datadf['target'] = data.target# Show the first five rowsdf.head()" }, { "code": null, "e": 5667, "s": 5514, "text": "You should be proud. You’ve loaded a dataset into a Pandas dataframe, that’s ready to be explored and used. To really see the value of this dataset, run" }, { "code": null, "e": 5677, "s": 5667, "text": "df.info()" }, { "code": null, "e": 5712, "s": 5677, "text": "There are a few things to observe:" }, { "code": null, "e": 5840, "s": 5712, "text": "There aren’t any missing values, all the columns have 569 values. This saves us time from having to account for missing values." }, { "code": null, "e": 6114, "s": 5840, "text": "All the data types are numerical. This is important because Scikit-Learn models do not accept categorical variables. In the real world, when we get categorical variables, we transform them into numerical variables. Scikit-Learn’s datasets are free of categorical variables." }, { "code": null, "e": 6261, "s": 6114, "text": "Hence, Scikit-Learn takes care of the data cleansing work. Their datasets are extremely valuable. You will benefit from learning ML by using them." }, { "code": null, "e": 6499, "s": 6261, "text": "Finally, the exciting part. Let’s build a model that classifies cancer tumors as malignant (spreading) or benign (non-spreading). This will show you how to use the data for your own models. We’ll build a simple K-Nearest Neighbors model." }, { "code": null, "e": 6712, "s": 6499, "text": "First, let’s split the dataset into two, one for training the model — giving it data to learn from, and the second for testing the model — seeing how well the model performs on data (scans) it hasn’t seen before." }, { "code": null, "e": 6951, "s": 6712, "text": "# Store the feature dataX = data.data# store the target datay = data.target# split the data using Scikit-Learn's train_test_splitfrom sklearn.model_selection import train_test_splitX_train, X_test, y_train, y_test = train_test_split(X, y)" }, { "code": null, "e": 7052, "s": 6951, "text": "This gives us two datasets —one for training and one for testing. Let’s get onto training the model." }, { "code": null, "e": 7203, "s": 7052, "text": "from sklearn.neighbors import KNeighborsClassifierlogreg = KNeighborsClassifier(n_neighbors=6)logreg.fit(X_train, y_train)logreg.score(X_test, y_test)" } ]
Linear Regression in 6 lines of Python | by Adarsh Menon | Towards Data Science
In this quick post, I wanted to share a method with which you can perform linear as well as multiple linear regression, in literally 6 lines of Python code. In statistics, linear regression is a linear approach to modelling the relationship between a dependent variable and one or more independent variables. I you would like to know more about linear regression and how it is implemented, check out these two methods to perform Linear Regression from scratch: towardsdatascience.com towardsdatascience.com Today to perform Linear Regression quickly, we will be using the library scikit-learn. If you don’t have it already you can install it using pip: pip install scikit-learn So now lets start by making a few imports: We need numpy to perform calculations, pandas to import the data set which is in csv format in this case and matplotlib to visualize our data and regression line. We will use the LinearRegression class to perform the linear regression. Now lets perform the regression: We have our predictions in Y_pred. Now lets visualize the data set and the regression line: That’s it! You can use any data set of you choice, and even perform Multiple Linear Regression (more than one independent variable) using the LinearRegression class in sklearn.linear_model. Also this class uses the ordinary Least Squares method to perform this regression. So accuracy wont be high, when compared to other techniques. But if you want to make some quick predictions and get some insight into the data set given to you, then this is a very handy tool. Find the data set and code here: https://github.com/chasinginfinity/ml-from-scratch/tree/master/03%20Linear%20Regression%20in%202%20minutes Got questions ? Need help ? Contact me!
[ { "code": null, "e": 329, "s": 172, "text": "In this quick post, I wanted to share a method with which you can perform linear as well as multiple linear regression, in literally 6 lines of Python code." }, { "code": null, "e": 633, "s": 329, "text": "In statistics, linear regression is a linear approach to modelling the relationship between a dependent variable and one or more independent variables. I you would like to know more about linear regression and how it is implemented, check out these two methods to perform Linear Regression from scratch:" }, { "code": null, "e": 656, "s": 633, "text": "towardsdatascience.com" }, { "code": null, "e": 679, "s": 656, "text": "towardsdatascience.com" }, { "code": null, "e": 825, "s": 679, "text": "Today to perform Linear Regression quickly, we will be using the library scikit-learn. If you don’t have it already you can install it using pip:" }, { "code": null, "e": 850, "s": 825, "text": "pip install scikit-learn" }, { "code": null, "e": 893, "s": 850, "text": "So now lets start by making a few imports:" }, { "code": null, "e": 1129, "s": 893, "text": "We need numpy to perform calculations, pandas to import the data set which is in csv format in this case and matplotlib to visualize our data and regression line. We will use the LinearRegression class to perform the linear regression." }, { "code": null, "e": 1162, "s": 1129, "text": "Now lets perform the regression:" }, { "code": null, "e": 1254, "s": 1162, "text": "We have our predictions in Y_pred. Now lets visualize the data set and the regression line:" }, { "code": null, "e": 1720, "s": 1254, "text": "That’s it! You can use any data set of you choice, and even perform Multiple Linear Regression (more than one independent variable) using the LinearRegression class in sklearn.linear_model. Also this class uses the ordinary Least Squares method to perform this regression. So accuracy wont be high, when compared to other techniques. But if you want to make some quick predictions and get some insight into the data set given to you, then this is a very handy tool." }, { "code": null, "e": 1860, "s": 1720, "text": "Find the data set and code here: https://github.com/chasinginfinity/ml-from-scratch/tree/master/03%20Linear%20Regression%20in%202%20minutes" } ]
LinkedList descendingIterator() method in Java with Examples - GeeksforGeeks
10 Dec, 2018 The descendingIterator() method of java.util.LinkedList class is used to return an iterator over the elements in this LinkedList in reverse sequential order. The elements will be returned in order from last (tail) to first (head). Syntax: public Iterator descendingIterator() Return Value: This method returns an iterator over the elements in this LinkedList in reverse sequence. Below are the examples to illustrate the descendingIterator() method Example 1: // Java program to demonstrate// descendingIterator() method// for String value import java.util.*; public class GFG1 { public static void main(String[] argv) throws Exception { try { // creating object of TreeMap<Integer, String> LinkedList<String> list = new LinkedList<String>(); // add some elements to list list.add("A"); list.add("B"); list.add("C"); // print the linked list System.out.println("LinkedList:" + list); // set Iterator as descending // using descendingIterator() method Iterator x = list.descendingIterator(); // print list with descending order while (x.hasNext()) { System.out.println("Value is : " + x.next()); } } catch (NullPointerException e) { System.out.println("Exception thrown : " + e); } }} LinkedList:[A, B, C] Value is : C Value is : B Value is : A Example 2: // Java program to demonstrate// descendingIterator() method// for Integer value import java.util.*; public class GFG1 { public static void main(String[] argv) throws Exception { try { // creating object of TreeMap<Integer, String> LinkedList<Integer> list = new LinkedList<Integer>(); // add some elements to list list.add(10); list.add(20); list.add(30); // print the linked list System.out.println("LinkedList:" + list); // set Iterator as descending // using descendingIterator() method Iterator x = list.descendingIterator(); // print list with descending order while (x.hasNext()) { System.out.println("Value is : " + x.next()); } } catch (NullPointerException e) { System.out.println("Exception thrown : " + e); } }} LinkedList:[10, 20, 30] Value is : 30 Value is : 20 Value is : 10 Java - util package Java-Collections Java-Functions java-LinkedList Java Java Java-Collections Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Interfaces in Java Initialize an ArrayList in Java ArrayList in Java Stack Class in Java Multidimensional Arrays in Java Singleton Class in Java LinkedList in Java Collections in Java Overriding in Java Queue Interface In Java
[ { "code": null, "e": 24107, "s": 24079, "text": "\n10 Dec, 2018" }, { "code": null, "e": 24338, "s": 24107, "text": "The descendingIterator() method of java.util.LinkedList class is used to return an iterator over the elements in this LinkedList in reverse sequential order. The elements will be returned in order from last (tail) to first (head)." }, { "code": null, "e": 24346, "s": 24338, "text": "Syntax:" }, { "code": null, "e": 24383, "s": 24346, "text": "public Iterator descendingIterator()" }, { "code": null, "e": 24487, "s": 24383, "text": "Return Value: This method returns an iterator over the elements in this LinkedList in reverse sequence." }, { "code": null, "e": 24556, "s": 24487, "text": "Below are the examples to illustrate the descendingIterator() method" }, { "code": null, "e": 24567, "s": 24556, "text": "Example 1:" }, { "code": "// Java program to demonstrate// descendingIterator() method// for String value import java.util.*; public class GFG1 { public static void main(String[] argv) throws Exception { try { // creating object of TreeMap<Integer, String> LinkedList<String> list = new LinkedList<String>(); // add some elements to list list.add(\"A\"); list.add(\"B\"); list.add(\"C\"); // print the linked list System.out.println(\"LinkedList:\" + list); // set Iterator as descending // using descendingIterator() method Iterator x = list.descendingIterator(); // print list with descending order while (x.hasNext()) { System.out.println(\"Value is : \" + x.next()); } } catch (NullPointerException e) { System.out.println(\"Exception thrown : \" + e); } }}", "e": 25595, "s": 24567, "text": null }, { "code": null, "e": 25656, "s": 25595, "text": "LinkedList:[A, B, C]\nValue is : C\nValue is : B\nValue is : A\n" }, { "code": null, "e": 25667, "s": 25656, "text": "Example 2:" }, { "code": "// Java program to demonstrate// descendingIterator() method// for Integer value import java.util.*; public class GFG1 { public static void main(String[] argv) throws Exception { try { // creating object of TreeMap<Integer, String> LinkedList<Integer> list = new LinkedList<Integer>(); // add some elements to list list.add(10); list.add(20); list.add(30); // print the linked list System.out.println(\"LinkedList:\" + list); // set Iterator as descending // using descendingIterator() method Iterator x = list.descendingIterator(); // print list with descending order while (x.hasNext()) { System.out.println(\"Value is : \" + x.next()); } } catch (NullPointerException e) { System.out.println(\"Exception thrown : \" + e); } }}", "e": 26680, "s": 25667, "text": null }, { "code": null, "e": 26747, "s": 26680, "text": "LinkedList:[10, 20, 30]\nValue is : 30\nValue is : 20\nValue is : 10\n" }, { "code": null, "e": 26767, "s": 26747, "text": "Java - util package" }, { "code": null, "e": 26784, "s": 26767, "text": "Java-Collections" }, { "code": null, "e": 26799, "s": 26784, "text": "Java-Functions" }, { "code": null, "e": 26815, "s": 26799, "text": "java-LinkedList" }, { "code": null, "e": 26820, "s": 26815, "text": "Java" }, { "code": null, "e": 26825, "s": 26820, "text": "Java" }, { "code": null, "e": 26842, "s": 26825, "text": "Java-Collections" }, { "code": null, "e": 26940, "s": 26842, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26949, "s": 26940, "text": "Comments" }, { "code": null, "e": 26962, "s": 26949, "text": "Old Comments" }, { "code": null, "e": 26981, "s": 26962, "text": "Interfaces in Java" }, { "code": null, "e": 27013, "s": 26981, "text": "Initialize an ArrayList in Java" }, { "code": null, "e": 27031, "s": 27013, "text": "ArrayList in Java" }, { "code": null, "e": 27051, "s": 27031, "text": "Stack Class in Java" }, { "code": null, "e": 27083, "s": 27051, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 27107, "s": 27083, "text": "Singleton Class in Java" }, { "code": null, "e": 27126, "s": 27107, "text": "LinkedList in Java" }, { "code": null, "e": 27146, "s": 27126, "text": "Collections in Java" }, { "code": null, "e": 27165, "s": 27146, "text": "Overriding in Java" } ]
Reading UTF8 data from a file using Java
In general, data is stored in a computer in the form of bits (1 or, 0). There are various coding schemes available specifying the set of bytes represented by each character. Unicode (UTF) − Stands for Unicode Translation Format. It is developed by The Unicode Consortium. if you want to create documents that use characters from multiple character sets, you will be able to do so using the single Unicode character encodings. It provides 3 types of encodings. UTF-8 − It comes in 8-bit units (bytes), a character in UTF8 can be from 1 to 4 bytes long, making UTF8 variable width. UTF-8 − It comes in 8-bit units (bytes), a character in UTF8 can be from 1 to 4 bytes long, making UTF8 variable width. UTF-16 − It comes in 16-bit units (shorts), it can be 1 or 2 shorts long, making UTF16 variable width. UTF-16 − It comes in 16-bit units (shorts), it can be 1 or 2 shorts long, making UTF16 variable width. UTF-32 − It comes in 32-bit units (longs). It is a fixed-width format and is always 1 "long" in length. UTF-32 − It comes in 32-bit units (longs). It is a fixed-width format and is always 1 "long" in length. The readUTF() method of the java.io.DataOutputStream reads data that is in modified UTF-8 encoding, into a String and returns it. Therefore to read UTF-8 data to a file − Instantiate the FileInputStream class by passing a String value representing the path of the required file, as a parameter. Instantiate the FileInputStream class by passing a String value representing the path of the required file, as a parameter. Instantiate the DataInputStream class bypassing the above created FileInputStream object as a parameter. Instantiate the DataInputStream class bypassing the above created FileInputStream object as a parameter. read UTF data from the InputStream object using the readUTF() method. read UTF data from the InputStream object using the readUTF() method. import java.io.DataInputStream; import java.io.EOFException; import java.io.FileInputStream; import java.io.IOException; public class UTF8Example { public static void main(String args[]) { StringBuffer buffer = new StringBuffer(); try { //Instantiating the FileInputStream class FileInputStream fileIn = new FileInputStream("D:\\test.txt"); //Instantiating the DataInputStream class DataInputStream inputStream = new DataInputStream(fileIn); //Reading UTF data from the DataInputStream while(inputStream.available()>0) { buffer.append(inputStream.readUTF()); } } catch(EOFException ex) { System.out.println(ex.toString()); } catch(IOException ex) { System.out.println(ex.toString()); } System.out.println("Contents of the file: "+buffer.toString()); } } Contents of the file: టుటోరియల్స్ పాయింట్ కి స్వాగతిం The new bufferedReader() method of the java.nio.file.Files class accepts an object of the class Path representing the path of the file and an object of the class Charset representing the type of the character sequences that are to be read() and, returns a BufferedReader object that could read the data which is in the specified format. The value for the Charset could be StandardCharsets.UTF_8 or, StandardCharsets.UTF_16LE or, StandardCharsets.UTF_16BE or, StandardCharsets.UTF_16 or, StandardCharsets.US_ASCII or, StandardCharsets.ISO_8859_1 Therefore to read UTF-8 data to a file − Create/get an object of the Path class representing the required path using the get() method of the java.nio.file.Paths class. Create/get an object of the Path class representing the required path using the get() method of the java.nio.file.Paths class. Create/get a BufferedReader object, that could read UtF-8 data, bypassing the above-created Path object and StandardCharsets.UTF_8 as parameters. Create/get a BufferedReader object, that could read UtF-8 data, bypassing the above-created Path object and StandardCharsets.UTF_8 as parameters. Using the readLine() method of the BufferedReader object read the contents of the file. Using the readLine() method of the BufferedReader object read the contents of the file. import java.io.BufferedReader; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; public class UTF8Example { public static void main(String args[]) throws Exception{ //Getting the Path object String filePath = "D:\\samplefile.txt"; Path path = Paths.get(filePath); //Creating a BufferedReader object BufferedReader reader = Files.newBufferedReader(path, StandardCharsets.UTF_8); //Reading the UTF-8 data from the file StringBuffer buffer = new StringBuffer(); int ch = 0; while((ch = reader.read())!=-1) { buffer.append((char)ch+reader.readLine()); } System.out.println("Contents of the file: "+buffer.toString()); } } Contents of the file: టుటోరియల్స్ పాయింట్ కి స్వాగతిం
[ { "code": null, "e": 1361, "s": 1187, "text": "In general, data is stored in a computer in the form of bits (1 or, 0). There are various coding schemes available specifying the set of bytes represented by each character." }, { "code": null, "e": 1647, "s": 1361, "text": "Unicode (UTF) − Stands for Unicode Translation Format. It is developed by The Unicode Consortium. if you want to create documents that use characters from multiple character sets, you will be able to do so using the single Unicode character encodings. It provides 3 types of encodings." }, { "code": null, "e": 1767, "s": 1647, "text": "UTF-8 − It comes in 8-bit units (bytes), a character in UTF8 can be from 1 to 4 bytes long, making UTF8 variable width." }, { "code": null, "e": 1887, "s": 1767, "text": "UTF-8 − It comes in 8-bit units (bytes), a character in UTF8 can be from 1 to 4 bytes long, making UTF8 variable width." }, { "code": null, "e": 1990, "s": 1887, "text": "UTF-16 − It comes in 16-bit units (shorts), it can be 1 or 2 shorts long, making UTF16 variable width." }, { "code": null, "e": 2093, "s": 1990, "text": "UTF-16 − It comes in 16-bit units (shorts), it can be 1 or 2 shorts long, making UTF16 variable width." }, { "code": null, "e": 2197, "s": 2093, "text": "UTF-32 − It comes in 32-bit units (longs). It is a fixed-width format and is always 1 \"long\" in length." }, { "code": null, "e": 2301, "s": 2197, "text": "UTF-32 − It comes in 32-bit units (longs). It is a fixed-width format and is always 1 \"long\" in length." }, { "code": null, "e": 2472, "s": 2301, "text": "The readUTF() method of the java.io.DataOutputStream reads data that is in modified UTF-8 encoding, into a String and returns it. Therefore to read UTF-8 data to a file −" }, { "code": null, "e": 2596, "s": 2472, "text": "Instantiate the FileInputStream class by passing a String value representing the path of the required file, as a parameter." }, { "code": null, "e": 2720, "s": 2596, "text": "Instantiate the FileInputStream class by passing a String value representing the path of the required file, as a parameter." }, { "code": null, "e": 2825, "s": 2720, "text": "Instantiate the DataInputStream class bypassing the above created FileInputStream object as a parameter." }, { "code": null, "e": 2930, "s": 2825, "text": "Instantiate the DataInputStream class bypassing the above created FileInputStream object as a parameter." }, { "code": null, "e": 3000, "s": 2930, "text": "read UTF data from the InputStream object using the readUTF() method." }, { "code": null, "e": 3070, "s": 3000, "text": "read UTF data from the InputStream object using the readUTF() method." }, { "code": null, "e": 3971, "s": 3070, "text": "import java.io.DataInputStream;\nimport java.io.EOFException;\nimport java.io.FileInputStream;\nimport java.io.IOException;\npublic class UTF8Example {\n public static void main(String args[]) {\n StringBuffer buffer = new StringBuffer();\n try {\n //Instantiating the FileInputStream class\n FileInputStream fileIn = new FileInputStream(\"D:\\\\test.txt\");\n //Instantiating the DataInputStream class\n DataInputStream inputStream = new DataInputStream(fileIn);\n //Reading UTF data from the DataInputStream\n while(inputStream.available()>0) {\n buffer.append(inputStream.readUTF());\n }\n }\n catch(EOFException ex) {\n System.out.println(ex.toString());\n }\n catch(IOException ex) {\n System.out.println(ex.toString());\n }\n System.out.println(\"Contents of the file: \"+buffer.toString());\n }\n}" }, { "code": null, "e": 4025, "s": 3971, "text": "Contents of the file: టుటోరియల్స్ పాయింట్ కి స్వాగతిం" }, { "code": null, "e": 4362, "s": 4025, "text": "The new bufferedReader() method of the java.nio.file.Files class accepts an object of the class Path representing the path of the file and an object of the class Charset representing the type of the character sequences that are to be read() and, returns a BufferedReader object that could read the data which is in the specified format." }, { "code": null, "e": 4570, "s": 4362, "text": "The value for the Charset could be StandardCharsets.UTF_8 or, StandardCharsets.UTF_16LE or, StandardCharsets.UTF_16BE or, StandardCharsets.UTF_16 or, StandardCharsets.US_ASCII or, StandardCharsets.ISO_8859_1" }, { "code": null, "e": 4611, "s": 4570, "text": "Therefore to read UTF-8 data to a file −" }, { "code": null, "e": 4738, "s": 4611, "text": "Create/get an object of the Path class representing the required path using the get() method of the java.nio.file.Paths class." }, { "code": null, "e": 4865, "s": 4738, "text": "Create/get an object of the Path class representing the required path using the get() method of the java.nio.file.Paths class." }, { "code": null, "e": 5011, "s": 4865, "text": "Create/get a BufferedReader object, that could read UtF-8 data, bypassing the above-created Path object and StandardCharsets.UTF_8 as parameters." }, { "code": null, "e": 5157, "s": 5011, "text": "Create/get a BufferedReader object, that could read UtF-8 data, bypassing the above-created Path object and StandardCharsets.UTF_8 as parameters." }, { "code": null, "e": 5245, "s": 5157, "text": "Using the readLine() method of the BufferedReader object read the contents of the file." }, { "code": null, "e": 5333, "s": 5245, "text": "Using the readLine() method of the BufferedReader object read the contents of the file." }, { "code": null, "e": 6107, "s": 5333, "text": "import java.io.BufferedReader;\nimport java.nio.charset.StandardCharsets;\nimport java.nio.file.Files;\nimport java.nio.file.Path;\nimport java.nio.file.Paths;\npublic class UTF8Example {\n public static void main(String args[]) throws Exception{\n //Getting the Path object\n String filePath = \"D:\\\\samplefile.txt\";\n Path path = Paths.get(filePath);\n //Creating a BufferedReader object\n BufferedReader reader = Files.newBufferedReader(path, StandardCharsets.UTF_8);\n //Reading the UTF-8 data from the file\n StringBuffer buffer = new StringBuffer();\n int ch = 0;\n while((ch = reader.read())!=-1) {\n buffer.append((char)ch+reader.readLine());\n }\n System.out.println(\"Contents of the file: \"+buffer.toString());\n }\n}" }, { "code": null, "e": 6161, "s": 6107, "text": "Contents of the file: టుటోరియల్స్ పాయింట్ కి స్వాగతిం" } ]
Lua - for Loop
A for loop is a repetition control structure that allows you to efficiently write a loop that needs to execute a specific number of times. The syntax of a for loop in Lua programming language is as follows − for init,max/min value, increment do statement(s) end Here is the flow of control in a for loop − The init step is executed first, and only once. This step allows you to declare and initialize any loop control variables. The init step is executed first, and only once. This step allows you to declare and initialize any loop control variables. Next, the max/min. This is the maximum or minimum value till which the loop continues to execute. It creates a condition check internally to compare between the initial value and maximum/minimum value. Next, the max/min. This is the maximum or minimum value till which the loop continues to execute. It creates a condition check internally to compare between the initial value and maximum/minimum value. After the body of the for loop executes, the flow of the control jumps back up to the increment/decrement statement. This statement allows you to update any loop control variables. After the body of the for loop executes, the flow of the control jumps back up to the increment/decrement statement. This statement allows you to update any loop control variables. The condition is now evaluated again. If it is true, the loop executes and the process repeats itself (body of loop, then increment step, and then again condition). After the condition becomes false, the for loop terminates. The condition is now evaluated again. If it is true, the loop executes and the process repeats itself (body of loop, then increment step, and then again condition). After the condition becomes false, the for loop terminates. for i = 10,1,-1 do print(i) end When the above code is built and executed, it produces the following result −
[ { "code": null, "e": 2376, "s": 2237, "text": "A for loop is a repetition control structure that allows you to efficiently write a loop that needs to execute a specific number of times." }, { "code": null, "e": 2445, "s": 2376, "text": "The syntax of a for loop in Lua programming language is as follows −" }, { "code": null, "e": 2503, "s": 2445, "text": "for init,max/min value, increment\ndo\n statement(s)\nend\n" }, { "code": null, "e": 2547, "s": 2503, "text": "Here is the flow of control in a for loop −" }, { "code": null, "e": 2670, "s": 2547, "text": "The init step is executed first, and only once. This step allows you to declare and initialize any loop control variables." }, { "code": null, "e": 2793, "s": 2670, "text": "The init step is executed first, and only once. This step allows you to declare and initialize any loop control variables." }, { "code": null, "e": 2995, "s": 2793, "text": "Next, the max/min. This is the maximum or minimum value till which the loop continues to execute. It creates a condition check internally to compare between the initial value and maximum/minimum value." }, { "code": null, "e": 3197, "s": 2995, "text": "Next, the max/min. This is the maximum or minimum value till which the loop continues to execute. It creates a condition check internally to compare between the initial value and maximum/minimum value." }, { "code": null, "e": 3378, "s": 3197, "text": "After the body of the for loop executes, the flow of the control jumps back up to the increment/decrement statement. This statement allows you to update any loop control variables." }, { "code": null, "e": 3559, "s": 3378, "text": "After the body of the for loop executes, the flow of the control jumps back up to the increment/decrement statement. This statement allows you to update any loop control variables." }, { "code": null, "e": 3784, "s": 3559, "text": "The condition is now evaluated again. If it is true, the loop executes and the process repeats itself (body of loop, then increment step, and then again condition). After the condition becomes false, the for loop terminates." }, { "code": null, "e": 4009, "s": 3784, "text": "The condition is now evaluated again. If it is true, the loop executes and the process repeats itself (body of loop, then increment step, and then again condition). After the condition becomes false, the for loop terminates." }, { "code": null, "e": 4047, "s": 4009, "text": "for i = 10,1,-1 \ndo \n print(i) \nend" } ]
C++ Program For Union And Intersection Of Two Linked Lists
28 Feb, 2022 Given two Linked Lists, create union and intersection lists that contain union and intersection of the elements present in the given lists. The order of elements in output lists doesn’t matter.Example: Input: List1: 10->15->4->20 List2: 8->4->2->10 Output: Intersection List: 4->10 Union List: 2->8->20->4->15->10 Method 1 (Simple):The following are simple algorithms to get union and intersection lists respectively.1. Intersection (list1, list2):Initialize the result list as NULL. Traverse list1 and look for every element in list2, if the element is present in list2, then add the element to the result.2. Union (list1, list2):Initialize the result list as NULL. Traverse list1 and add all of its elements to the result.Traverse list2. If an element of list2 is already present in the result then do not insert it to the result, otherwise insert.This method assumes that there are no duplicates in the given lists.Thanks to Shekhu for suggesting this method. Following are C and Java implementations of this method. C++ // C++ program to find union// and intersection of two unsorted// linked lists#include <iostream>using namespace std; // Link list nodestruct Node{ int data; struct Node* next;}; /* A utility function to insert a node at the beginning ofa linked list*/void push(struct Node** head_ref, int new_data); /* A utility function to check if given data is present in a list */bool isPresent(struct Node* head, int data); /* Function to get union of two linked lists head1 and head2 */struct Node* getUnion(struct Node* head1, struct Node* head2){ struct Node* result = NULL; struct Node *t1 = head1, *t2 = head2; // Insert all elements of // list1 to the result list while (t1 != NULL) { push(&result, t1->data); t1 = t1->next; } // Insert those elements of list2 // which are not present in result list while (t2 != NULL) { if (!isPresent(result, t2->data)) push(&result, t2->data); t2 = t2->next; } return result;} /* Function to get intersection of two linked lists head1 and head2 */struct Node* getIntersection(struct Node* head1, struct Node* head2){ struct Node* result = NULL; struct Node* t1 = head1; // Traverse list1 and search each element // of it in list2. If the element is present // in list 2, then insert the element to result while (t1 != NULL) { if (isPresent(head2, t1->data)) push(&result, t1->data); t1 = t1->next; } return result;} /* A utility function to insert a node at the beginning of a linked list*/void push(struct Node** head_ref, int new_data){ // Allocate node struct Node* new_node = (struct Node*)malloc( sizeof(struct Node)); // Put in the data new_node->data = new_data; /* Link the old list off the new node */ new_node->next = (*head_ref); /* Move the head to point to the new node */ (*head_ref) = new_node;} /* A utility function to print a linked list*/void printList(struct Node* node){ while (node != NULL) { cout << " " << node->data; node = node->next; }} /* A utility function that returns true if data is present in linked list else return false */bool isPresent(struct Node* head, int data){ struct Node* t = head; while (t != NULL) { if (t->data == data) return 1; t = t->next; } return 0;} // Driver codeint main(){ // Start with the empty list struct Node* head1 = NULL; struct Node* head2 = NULL; struct Node* intersection = NULL; struct Node* unin = NULL; // Create a linked lists 10->15->5->20 push(&head1, 20); push(&head1, 4); push(&head1, 15); push(&head1, 10); // Create a linked lists 8->4->2->10 push(&head2, 10); push(&head2, 2); push(&head2, 4); push(&head2, 8); intersection = getIntersection(head1, head2); unin = getUnion(head1, head2); cout << "First list is " << endl; printList(head1); cout << "Second list is " << endl; printList(head2); cout << "Intersection list is " << endl; printList(intersection); cout << "Union list is " << endl; printList(unin); return 0;}// This code is contributed by shivanisingh2110 Output First list is 10 15 4 20 Second list is 8 4 2 10 Intersection list is 4 10 Union list is 2 8 20 4 15 10 Complexity Analysis: Time Complexity: O(m*n).Here ‘m’ and ‘n’ are number of elements present in the first and second lists respectively. For union: For every element in list-2 we check if that element is already present in the resultant list made using list-1.For intersection: For every element in list-1 we check if that element is also present in list-2. Auxiliary Space: O(1). No use of any data structure for storing values. Method 2 (Use Merge Sort):In this method, algorithms for Union and Intersection are very similar. First, we sort the given lists, then we traverse the sorted lists to get union and intersection. The following are the steps to be followed to get union and intersection lists. Sort the first Linked List using merge sort. This step takes O(mLogm) time. Refer this post for details of this step.Sort the second Linked List using merge sort. This step takes O(nLogn) time. Refer this post for details of this step.Linearly scan both sorted lists to get the union and intersection. This step takes O(m + n) time. This step can be implemented using the same algorithm as sorted arrays algorithm discussed here. Sort the first Linked List using merge sort. This step takes O(mLogm) time. Refer this post for details of this step. Sort the second Linked List using merge sort. This step takes O(nLogn) time. Refer this post for details of this step. Linearly scan both sorted lists to get the union and intersection. This step takes O(m + n) time. This step can be implemented using the same algorithm as sorted arrays algorithm discussed here. The time complexity of this method is O(mLogm + nLogn) which is better than method 1’s time complexity. Please refer complete article on Union and Intersection of two Linked Lists for more details! rkbhola5 sumitgumber28 24*7 Innovation Labs Accolite Amazon Flipkart Komli Media Microsoft Taxi4Sure VMWare Walmart C++ Programs Hash Linked List Sorting VMWare Flipkart Accolite Amazon Microsoft 24*7 Innovation Labs Walmart Komli Media Taxi4Sure Linked List Hash Sorting Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Passing a function as a parameter in C++ Const keyword in C++ Program to implement Singly Linked List in C++ using class cout in C++ Different ways to print elements of vector Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum) What is Hashing | A Complete Tutorial Internal Working of HashMap in Java Hashing | Set 1 (Introduction) Count pairs with given sum
[ { "code": null, "e": 28, "s": 0, "text": "\n28 Feb, 2022" }, { "code": null, "e": 230, "s": 28, "text": "Given two Linked Lists, create union and intersection lists that contain union and intersection of the elements present in the given lists. The order of elements in output lists doesn’t matter.Example:" }, { "code": null, "e": 343, "s": 230, "text": "Input:\nList1: 10->15->4->20\nList2: 8->4->2->10\nOutput:\nIntersection List: 4->10\nUnion List: 2->8->20->4->15->10" }, { "code": null, "e": 1049, "s": 343, "text": "Method 1 (Simple):The following are simple algorithms to get union and intersection lists respectively.1. Intersection (list1, list2):Initialize the result list as NULL. Traverse list1 and look for every element in list2, if the element is present in list2, then add the element to the result.2. Union (list1, list2):Initialize the result list as NULL. Traverse list1 and add all of its elements to the result.Traverse list2. If an element of list2 is already present in the result then do not insert it to the result, otherwise insert.This method assumes that there are no duplicates in the given lists.Thanks to Shekhu for suggesting this method. Following are C and Java implementations of this method." }, { "code": null, "e": 1053, "s": 1049, "text": "C++" }, { "code": "// C++ program to find union// and intersection of two unsorted// linked lists#include <iostream>using namespace std; // Link list nodestruct Node{ int data; struct Node* next;}; /* A utility function to insert a node at the beginning ofa linked list*/void push(struct Node** head_ref, int new_data); /* A utility function to check if given data is present in a list */bool isPresent(struct Node* head, int data); /* Function to get union of two linked lists head1 and head2 */struct Node* getUnion(struct Node* head1, struct Node* head2){ struct Node* result = NULL; struct Node *t1 = head1, *t2 = head2; // Insert all elements of // list1 to the result list while (t1 != NULL) { push(&result, t1->data); t1 = t1->next; } // Insert those elements of list2 // which are not present in result list while (t2 != NULL) { if (!isPresent(result, t2->data)) push(&result, t2->data); t2 = t2->next; } return result;} /* Function to get intersection of two linked lists head1 and head2 */struct Node* getIntersection(struct Node* head1, struct Node* head2){ struct Node* result = NULL; struct Node* t1 = head1; // Traverse list1 and search each element // of it in list2. If the element is present // in list 2, then insert the element to result while (t1 != NULL) { if (isPresent(head2, t1->data)) push(&result, t1->data); t1 = t1->next; } return result;} /* A utility function to insert a node at the beginning of a linked list*/void push(struct Node** head_ref, int new_data){ // Allocate node struct Node* new_node = (struct Node*)malloc( sizeof(struct Node)); // Put in the data new_node->data = new_data; /* Link the old list off the new node */ new_node->next = (*head_ref); /* Move the head to point to the new node */ (*head_ref) = new_node;} /* A utility function to print a linked list*/void printList(struct Node* node){ while (node != NULL) { cout << \" \" << node->data; node = node->next; }} /* A utility function that returns true if data is present in linked list else return false */bool isPresent(struct Node* head, int data){ struct Node* t = head; while (t != NULL) { if (t->data == data) return 1; t = t->next; } return 0;} // Driver codeint main(){ // Start with the empty list struct Node* head1 = NULL; struct Node* head2 = NULL; struct Node* intersection = NULL; struct Node* unin = NULL; // Create a linked lists 10->15->5->20 push(&head1, 20); push(&head1, 4); push(&head1, 15); push(&head1, 10); // Create a linked lists 8->4->2->10 push(&head2, 10); push(&head2, 2); push(&head2, 4); push(&head2, 8); intersection = getIntersection(head1, head2); unin = getUnion(head1, head2); cout << \"First list is \" << endl; printList(head1); cout << \"Second list is \" << endl; printList(head2); cout << \"Intersection list is \" << endl; printList(intersection); cout << \"Union list is \" << endl; printList(unin); return 0;}// This code is contributed by shivanisingh2110", "e": 4377, "s": 1053, "text": null }, { "code": null, "e": 4384, "s": 4377, "text": "Output" }, { "code": null, "e": 4496, "s": 4384, "text": " First list is \n10 15 4 20 \nSecond list is \n8 4 2 10 \nIntersection list is \n4 10 \nUnion list is \n2 8 20 4 15 10" }, { "code": null, "e": 4517, "s": 4496, "text": "Complexity Analysis:" }, { "code": null, "e": 4854, "s": 4517, "text": "Time Complexity: O(m*n).Here ‘m’ and ‘n’ are number of elements present in the first and second lists respectively. For union: For every element in list-2 we check if that element is already present in the resultant list made using list-1.For intersection: For every element in list-1 we check if that element is also present in list-2." }, { "code": null, "e": 4926, "s": 4854, "text": "Auxiliary Space: O(1). No use of any data structure for storing values." }, { "code": null, "e": 5201, "s": 4926, "text": "Method 2 (Use Merge Sort):In this method, algorithms for Union and Intersection are very similar. First, we sort the given lists, then we traverse the sorted lists to get union and intersection. The following are the steps to be followed to get union and intersection lists." }, { "code": null, "e": 5631, "s": 5201, "text": "Sort the first Linked List using merge sort. This step takes O(mLogm) time. Refer this post for details of this step.Sort the second Linked List using merge sort. This step takes O(nLogn) time. Refer this post for details of this step.Linearly scan both sorted lists to get the union and intersection. This step takes O(m + n) time. This step can be implemented using the same algorithm as sorted arrays algorithm discussed here." }, { "code": null, "e": 5749, "s": 5631, "text": "Sort the first Linked List using merge sort. This step takes O(mLogm) time. Refer this post for details of this step." }, { "code": null, "e": 5868, "s": 5749, "text": "Sort the second Linked List using merge sort. This step takes O(nLogn) time. Refer this post for details of this step." }, { "code": null, "e": 6063, "s": 5868, "text": "Linearly scan both sorted lists to get the union and intersection. This step takes O(m + n) time. This step can be implemented using the same algorithm as sorted arrays algorithm discussed here." }, { "code": null, "e": 6262, "s": 6063, "text": "The time complexity of this method is O(mLogm + nLogn) which is better than method 1’s time complexity. Please refer complete article on Union and Intersection of two Linked Lists for more details! " }, { "code": null, "e": 6271, "s": 6262, "text": "rkbhola5" }, { "code": null, "e": 6285, "s": 6271, "text": "sumitgumber28" }, { "code": null, "e": 6306, "s": 6285, "text": "24*7 Innovation Labs" }, { "code": null, "e": 6315, "s": 6306, "text": "Accolite" }, { "code": null, "e": 6322, "s": 6315, "text": "Amazon" }, { "code": null, "e": 6331, "s": 6322, "text": "Flipkart" }, { "code": null, "e": 6343, "s": 6331, "text": "Komli Media" }, { "code": null, "e": 6353, "s": 6343, "text": "Microsoft" }, { "code": null, "e": 6363, "s": 6353, "text": "Taxi4Sure" }, { "code": null, "e": 6370, "s": 6363, "text": "VMWare" }, { "code": null, "e": 6378, "s": 6370, "text": "Walmart" }, { "code": null, "e": 6391, "s": 6378, "text": "C++ Programs" }, { "code": null, "e": 6396, "s": 6391, "text": "Hash" }, { "code": null, "e": 6408, "s": 6396, "text": "Linked List" }, { "code": null, "e": 6416, "s": 6408, "text": "Sorting" }, { "code": null, "e": 6423, "s": 6416, "text": "VMWare" }, { "code": null, "e": 6432, "s": 6423, "text": "Flipkart" }, { "code": null, "e": 6441, "s": 6432, "text": "Accolite" }, { "code": null, "e": 6448, "s": 6441, "text": "Amazon" }, { "code": null, "e": 6458, "s": 6448, "text": "Microsoft" }, { "code": null, "e": 6479, "s": 6458, "text": "24*7 Innovation Labs" }, { "code": null, "e": 6487, "s": 6479, "text": "Walmart" }, { "code": null, "e": 6499, "s": 6487, "text": "Komli Media" }, { "code": null, "e": 6509, "s": 6499, "text": "Taxi4Sure" }, { "code": null, "e": 6521, "s": 6509, "text": "Linked List" }, { "code": null, "e": 6526, "s": 6521, "text": "Hash" }, { "code": null, "e": 6534, "s": 6526, "text": "Sorting" }, { "code": null, "e": 6632, "s": 6534, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 6673, "s": 6632, "text": "Passing a function as a parameter in C++" }, { "code": null, "e": 6694, "s": 6673, "text": "Const keyword in C++" }, { "code": null, "e": 6753, "s": 6694, "text": "Program to implement Singly Linked List in C++ using class" }, { "code": null, "e": 6765, "s": 6753, "text": "cout in C++" }, { "code": null, "e": 6808, "s": 6765, "text": "Different ways to print elements of vector" }, { "code": null, "e": 6893, "s": 6808, "text": "Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)" }, { "code": null, "e": 6931, "s": 6893, "text": "What is Hashing | A Complete Tutorial" }, { "code": null, "e": 6967, "s": 6931, "text": "Internal Working of HashMap in Java" }, { "code": null, "e": 6998, "s": 6967, "text": "Hashing | Set 1 (Introduction)" } ]
GATE | GATE-CS-2015 (Set 3) | Question 65
28 Jun, 2021 Consider the following array of elements. 〈89, 19, 50, 17, 12, 15, 2, 5, 7, 11, 6, 9, 100〉. The minimum number of interchanges needed to convert it into a max-heap is(A) 4(B) 5(C) 2(D) 3Answer: (D)Explanation: 〈89, 19, 50, 17, 12, 15, 2, 5, 7, 11, 6, 9, 100〉 89 / \ 19 50 / \ / \ 17 12 15 2 / \ / \ / \ 5 7 11 6 9 100 Minimum number of swaps required to convert above tree to Max heap is 3. Below are 3 swap operations. Swap 100 with 15 Swap 100 with 50 Swap 100 with 89 100 / \ 19 89 / \ / \ 17 12 50 5 / \ / \ / \ 7 11 6 9 2 15 Quiz of this Question GATE-CS-2015 (Set 3) GATE-GATE-CS-2015 (Set 3) GATE Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. GATE | GATE-CS-2014-(Set-2) | Question 65 GATE | Sudo GATE 2020 Mock I (27 December 2019) | Question 33 GATE | GATE-CS-2014-(Set-3) | Question 65 GATE | GATE-CS-2015 (Set 3) | Question 65 GATE | GATE CS 2008 | Question 46 GATE | GATE CS 2011 | Question 49 GATE | GATE CS 1996 | Question 38 GATE | GATE-CS-2004 | Question 31 GATE | GATE IT 2006 | Question 20 GATE | GATE-CS-2016 (Set 1) | Question 45
[ { "code": null, "e": 54, "s": 26, "text": "\n28 Jun, 2021" }, { "code": null, "e": 313, "s": 54, "text": "Consider the following array of elements. 〈89, 19, 50, 17, 12, 15, 2, 5, 7, 11, 6, 9, 100〉. The minimum number of interchanges needed to convert it into a max-heap is(A) 4(B) 5(C) 2(D) 3Answer: (D)Explanation: 〈89, 19, 50, 17, 12, 15, 2, 5, 7, 11, 6, 9, 100〉" }, { "code": null, "e": 749, "s": 313, "text": "\n 89\n / \\\n 19 50\n / \\ / \\ \n 17 12 15 2\n / \\ / \\ / \\\n5 7 11 6 9 100\n\nMinimum number of swaps required to convert above tree \nto Max heap is 3. Below are 3 swap operations.\nSwap 100 with 15\nSwap 100 with 50\nSwap 100 with 89 \n\n 100\n / \\\n 19 89\n / \\ / \\ \n 17 12 50 5 \n / \\ / \\ / \\\n7 11 6 9 2 15" }, { "code": null, "e": 771, "s": 749, "text": "Quiz of this Question" }, { "code": null, "e": 792, "s": 771, "text": "GATE-CS-2015 (Set 3)" }, { "code": null, "e": 818, "s": 792, "text": "GATE-GATE-CS-2015 (Set 3)" }, { "code": null, "e": 823, "s": 818, "text": "GATE" }, { "code": null, "e": 921, "s": 823, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 963, "s": 921, "text": "GATE | GATE-CS-2014-(Set-2) | Question 65" }, { "code": null, "e": 1025, "s": 963, "text": "GATE | Sudo GATE 2020 Mock I (27 December 2019) | Question 33" }, { "code": null, "e": 1067, "s": 1025, "text": "GATE | GATE-CS-2014-(Set-3) | Question 65" }, { "code": null, "e": 1109, "s": 1067, "text": "GATE | GATE-CS-2015 (Set 3) | Question 65" }, { "code": null, "e": 1143, "s": 1109, "text": "GATE | GATE CS 2008 | Question 46" }, { "code": null, "e": 1177, "s": 1143, "text": "GATE | GATE CS 2011 | Question 49" }, { "code": null, "e": 1211, "s": 1177, "text": "GATE | GATE CS 1996 | Question 38" }, { "code": null, "e": 1245, "s": 1211, "text": "GATE | GATE-CS-2004 | Question 31" }, { "code": null, "e": 1279, "s": 1245, "text": "GATE | GATE IT 2006 | Question 20" } ]
Java program to merge two files into a third file
30 May, 2018 Prerequisite : PrintWriter , BufferedReader Let the given two files be file1.txt and file2.txt. Our Task is to merge both files into third file say file3.txt. The following are steps to merge. Create PrintWriter object for file3.txtOpen BufferedReader for file1.txtRun a loop to copy each line of file1.txt to file3.txtOpen BufferedReader for file2.txtRun a loop to copy each line of file2.txt to file3.txtFlush PrintWriter stream and close resources. Create PrintWriter object for file3.txt Open BufferedReader for file1.txt Run a loop to copy each line of file1.txt to file3.txt Open BufferedReader for file2.txt Run a loop to copy each line of file2.txt to file3.txt Flush PrintWriter stream and close resources. To successfully run the below program file1.txt and file2.txt must exits in same folder OR provide full path for them. // Java program to merge two // files into third file import java.io.*; public class FileMerge { public static void main(String[] args) throws IOException { // PrintWriter object for file3.txt PrintWriter pw = new PrintWriter("file3.txt"); // BufferedReader object for file1.txt BufferedReader br = new BufferedReader(new FileReader("file1.txt")); String line = br.readLine(); // loop to copy each line of // file1.txt to file3.txt while (line != null) { pw.println(line); line = br.readLine(); } br = new BufferedReader(new FileReader("file2.txt")); line = br.readLine(); // loop to copy each line of // file2.txt to file3.txt while(line != null) { pw.println(line); line = br.readLine(); } pw.flush(); // closing resources br.close(); pw.close(); System.out.println("Merged file1.txt and file2.txt into file3.txt"); }} Output: Merged file1.txt and file2.txt into file3.txt Note : If file3.txt exist in cwd(current working directory) then it will be overwritten by above program otherwise new file will be created. Related Article : C Program to merge contents of two files into a third file Java program to merge two files alternatively into third file This article is contributed by Gaurav Miglani. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. java-file-handling Java-I/O Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Interfaces in Java ArrayList in Java Stream In Java Collections in Java Singleton Class in Java Multidimensional Arrays in Java Stack Class in Java Set in Java Introduction to Java Initialize an ArrayList in Java
[ { "code": null, "e": 52, "s": 24, "text": "\n30 May, 2018" }, { "code": null, "e": 96, "s": 52, "text": "Prerequisite : PrintWriter , BufferedReader" }, { "code": null, "e": 245, "s": 96, "text": "Let the given two files be file1.txt and file2.txt. Our Task is to merge both files into third file say file3.txt. The following are steps to merge." }, { "code": null, "e": 504, "s": 245, "text": "Create PrintWriter object for file3.txtOpen BufferedReader for file1.txtRun a loop to copy each line of file1.txt to file3.txtOpen BufferedReader for file2.txtRun a loop to copy each line of file2.txt to file3.txtFlush PrintWriter stream and close resources." }, { "code": null, "e": 544, "s": 504, "text": "Create PrintWriter object for file3.txt" }, { "code": null, "e": 578, "s": 544, "text": "Open BufferedReader for file1.txt" }, { "code": null, "e": 633, "s": 578, "text": "Run a loop to copy each line of file1.txt to file3.txt" }, { "code": null, "e": 667, "s": 633, "text": "Open BufferedReader for file2.txt" }, { "code": null, "e": 722, "s": 667, "text": "Run a loop to copy each line of file2.txt to file3.txt" }, { "code": null, "e": 768, "s": 722, "text": "Flush PrintWriter stream and close resources." }, { "code": null, "e": 887, "s": 768, "text": "To successfully run the below program file1.txt and file2.txt must exits in same folder OR provide full path for them." }, { "code": "// Java program to merge two // files into third file import java.io.*; public class FileMerge { public static void main(String[] args) throws IOException { // PrintWriter object for file3.txt PrintWriter pw = new PrintWriter(\"file3.txt\"); // BufferedReader object for file1.txt BufferedReader br = new BufferedReader(new FileReader(\"file1.txt\")); String line = br.readLine(); // loop to copy each line of // file1.txt to file3.txt while (line != null) { pw.println(line); line = br.readLine(); } br = new BufferedReader(new FileReader(\"file2.txt\")); line = br.readLine(); // loop to copy each line of // file2.txt to file3.txt while(line != null) { pw.println(line); line = br.readLine(); } pw.flush(); // closing resources br.close(); pw.close(); System.out.println(\"Merged file1.txt and file2.txt into file3.txt\"); }}", "e": 2013, "s": 887, "text": null }, { "code": null, "e": 2021, "s": 2013, "text": "Output:" }, { "code": null, "e": 2068, "s": 2021, "text": "Merged file1.txt and file2.txt into file3.txt\n" }, { "code": null, "e": 2209, "s": 2068, "text": "Note : If file3.txt exist in cwd(current working directory) then it will be overwritten by above program otherwise new file will be created." }, { "code": null, "e": 2227, "s": 2209, "text": "Related Article :" }, { "code": null, "e": 2286, "s": 2227, "text": "C Program to merge contents of two files into a third file" }, { "code": null, "e": 2348, "s": 2286, "text": "Java program to merge two files alternatively into third file" }, { "code": null, "e": 2650, "s": 2348, "text": "This article is contributed by Gaurav Miglani. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks." }, { "code": null, "e": 2775, "s": 2650, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 2794, "s": 2775, "text": "java-file-handling" }, { "code": null, "e": 2803, "s": 2794, "text": "Java-I/O" }, { "code": null, "e": 2808, "s": 2803, "text": "Java" }, { "code": null, "e": 2813, "s": 2808, "text": "Java" }, { "code": null, "e": 2911, "s": 2813, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2930, "s": 2911, "text": "Interfaces in Java" }, { "code": null, "e": 2948, "s": 2930, "text": "ArrayList in Java" }, { "code": null, "e": 2963, "s": 2948, "text": "Stream In Java" }, { "code": null, "e": 2983, "s": 2963, "text": "Collections in Java" }, { "code": null, "e": 3007, "s": 2983, "text": "Singleton Class in Java" }, { "code": null, "e": 3039, "s": 3007, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 3059, "s": 3039, "text": "Stack Class in Java" }, { "code": null, "e": 3071, "s": 3059, "text": "Set in Java" }, { "code": null, "e": 3092, "s": 3071, "text": "Introduction to Java" } ]
How to Create and Add Data to Firebase Firestore in Android?
17 Jan, 2021 Firebase is a famous product of Google which is used by so many developers to add backend functionality for their website as well as apps. The Firebase will make your job really easier for backend database and handling the database. In this article, we will take a look at the implementation of Firebase Firestore in Android. This is a series of 4 articles in which we are going to perform the basic CRUD (Create, Read, Update, and Delete) operation with Firebase Firestore in Android. We are going to cover the following 4 articles in this series: How to Create and Add Data to Firebase Firestore in Android?How to Read Data from Firebase Firestore in Android?How to Update Data in Firebase Firestore in Android?How to Delete Data from Firebase Firestore in Android? How to Create and Add Data to Firebase Firestore in Android? How to Read Data from Firebase Firestore in Android? How to Update Data in Firebase Firestore in Android? How to Delete Data from Firebase Firestore in Android? Firebase Firestore is a cloud NoSQL database that is used to add, retrieve, and update data inside your application. Basically, it is a database that is used to store data inside your Firebase console. The data in the Firestore is stored in the form of documents, so it becomes easy to manage this data inside Firebase. Firestore is having a better query than that of Firebase Realtime Database. It is highly scalable and data can be managed properly inside Firebase Firestore. It becomes easy to access data on the server-side inside the Firebase Firestore database. Firebase Firestore is much easier in comparison to Firebase Realtime Database. You can check a more detailed guide on Firebase Realtime Database vs Firestore database. In this article, we will be building a simple Android Application in which we will be collecting the data from users via some TextFields and we will send that data to our Firebase Cloud Firestore console and that data will get store in our Firebase database. 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: Connect your app to Firebase After creating a new project. Navigate to the Tools option on the top bar. Inside that click on Firebase. After clicking on Firebase, you can get to see the right column mentioned below in the screenshot. Inside that column Navigate to Firebase Cloud Firestore. Click on that option and you will get to see two options on Connect app to Firebase and Add Cloud Firestore to your app. Click on Connect now option and your app will be connected to Firebase. After that click on the second option and now your App is connected to Firebase. After connecting your app to Firebase you will get to see the below screen. After that verify that dependency for Firebase Firestore database has been added to our Gradle file. Navigate to the app > Gradle Scripts inside that file. Check whether the below dependency is added or not. If the below dependency is not present in your build.gradle file. Add the below dependency in the dependencies section. implementation ‘com.google.firebase:firebase-firestore:22.0.1’ After adding this dependency sync your project and now we are ready for creating our app. If you want to know more about connecting your app to Firebase. Refer to this article to get in detail about How to add Firebase to Android App. Step 3: Working with the AndroidManifest.xml file For adding data to Firebase we should have to give permissions for accessing the internet. For adding these permissions navigate to the app > AndroidManifest.xml. Inside that file add the below permissions to it. XML <!--Permissions for internet--><uses-permission android:name="android.permission.INTERNET" /><uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> Step 4: Working with the activity_main.xml file Go to the activity_main.xml file and refer to the following code. Below is the code for the activity_main.xml file. XML <?xml version="1.0" encoding="utf-8"?><LinearLayout 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:orientation="vertical" tools:context=".MainActivity"> <!--Edittext for getting course Name--> <EditText android:id="@+id/idEdtCourseName" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginStart="10dp" android:layout_marginTop="20dp" android:layout_marginEnd="10dp" android:hint="Course Name" android:importantForAutofill="no" android:inputType="text" /> <!--Edittext for getting course Duration--> <EditText android:id="@+id/idEdtCourseDuration" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginStart="10dp" android:layout_marginTop="20dp" android:layout_marginEnd="10dp" android:hint="Course Duration in min" android:importantForAutofill="no" android:inputType="time" /> <!--Edittext for getting course Description--> <EditText android:id="@+id/idEdtCourseDescription" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginStart="10dp" android:layout_marginTop="20dp" android:layout_marginEnd="10dp" android:hint="Course Description" android:importantForAutofill="no" android:inputType="text" /> <!--Button for adding your course to Firebase--> <Button android:id="@+id/idBtnSubmitCourse" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_margin="10dp" android:text="Submit Course Details" android:textAllCaps="false" /> </LinearLayout> Step 5: Create a new Java class for storing the data For sending data to the Firebase Firestore database we have to create an Object class and send that whole object class to Firebase. For creating an object class navigate to the app > java > your app’s package name > Right-click on it and click on New > Java Class > Give a name to your class. Here we named it Courses and add the below code to it. Java public class Courses { // variables for storing our data. private String courseName, courseDescription, courseDuration; public Courses() { // empty constructor // required for Firebase. } // Constructor for all variables. public Courses(String courseName, String courseDescription, String courseDuration) { this.courseName = courseName; this.courseDescription = courseDescription; this.courseDuration = courseDuration; } // getter methods for all variables. public String getCourseName() { return courseName; } public void setCourseName(String courseName) { this.courseName = courseName; } public String getCourseDescription() { return courseDescription; } // setter method for all variables. public void setCourseDescription(String courseDescription) { this.courseDescription = courseDescription; } public String getCourseDuration() { return courseDuration; } public void setCourseDuration(String courseDuration) { this.courseDuration = courseDuration; }} Step 6: Working with the MainActivity.java file Go to the MainActivity.java file and refer to the following code. Below is the code for the MainActivity.java file. Comments are added inside the code to understand the code in more detail. Java import android.os.Bundle;import android.text.TextUtils;import android.view.View;import android.widget.Button;import android.widget.EditText;import android.widget.Toast; import androidx.annotation.NonNull;import androidx.appcompat.app.AppCompatActivity; import com.google.android.gms.tasks.OnFailureListener;import com.google.android.gms.tasks.OnSuccessListener;import com.google.firebase.firestore.CollectionReference;import com.google.firebase.firestore.DocumentReference;import com.google.firebase.firestore.FirebaseFirestore; public class MainActivity extends AppCompatActivity { // creating variables for our edit text private EditText courseNameEdt, courseDurationEdt, courseDescriptionEdt; // creating variable for button private Button submitCourseBtn; // creating a strings for storing // our values from edittext fields. private String courseName, courseDuration, courseDescription; // creating a variable // for firebasefirestore. private FirebaseFirestore db; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // getting our instance // from Firebase Firestore. db = FirebaseFirestore.getInstance(); // initializing our edittext and buttons courseNameEdt = findViewById(R.id.idEdtCourseName); courseDescriptionEdt = findViewById(R.id.idEdtCourseDescription); courseDurationEdt = findViewById(R.id.idEdtCourseDuration); submitCourseBtn = findViewById(R.id.idBtnSubmitCourse); // adding on click listener for button submitCourseBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // getting data from edittext fields. courseName = courseNameEdt.getText().toString(); courseDescription = courseDescriptionEdt.getText().toString(); courseDuration = courseDurationEdt.getText().toString(); // validating the text fields if empty or not. if (TextUtils.isEmpty(courseName)) { courseNameEdt.setError("Please enter Course Name"); } else if (TextUtils.isEmpty(courseDescription)) { courseDescriptionEdt.setError("Please enter Course Description"); } else if (TextUtils.isEmpty(courseDuration)) { courseDurationEdt.setError("Please enter Course Duration"); } else { // calling method to add data to Firebase Firestore. addDataToFirestore(courseName, courseDescription, courseDuration); } } }); } private void addDataToFirestore(String courseName, String courseDescription, String courseDuration) { // creating a collection reference // for our Firebase Firetore database. CollectionReference dbCourses = db.collection("Courses"); // adding our data to our courses object class. Courses courses = new Courses(courseName, courseDescription, courseDuration); // below method is use to add data to Firebase Firestore. dbCourses.add(courses).addOnSuccessListener(new OnSuccessListener<DocumentReference>() { @Override public void onSuccess(DocumentReference documentReference) { // after the data addition is successful // we are displaying a success toast message. Toast.makeText(MainActivity.this, "Your Course has been added to Firebase Firestore", Toast.LENGTH_SHORT).show(); } }).addOnFailureListener(new OnFailureListener() { @Override public void onFailure(@NonNull Exception e) { // this method is called when the data addition process is failed. // displaying a toast message when data addition is failed. Toast.makeText(MainActivity.this, "Fail to add course \n" + e, Toast.LENGTH_SHORT).show(); } }); }} After adding this code go to this link to open Firebase. After clicking on this link you will get to see the below page and on this page Click on Go to Console option in the top right corner. After clicking on this screen you will get to see the below screen with your all project inside that select your project. Inside that screen click n Firebase Firestore Database in the left window. After clicking on the Create Database option you will get to see the below screen. Inside this screen, we have to select the Start in test mode option. We are using test mode because we are not setting authentication inside our app. So we are selecting Start in test mode. After selecting on test mode click on the Next option and you will get to see the below screen. Inside this screen, we just have to click on the Enable button to enable our Firebase Firestore database. After completing this process we just have to run our application and add data inside our app and click on the submit button. You will get to see the data added inside the Firebase Console. Below is the output of the app. AmiyaRanjanRout android Technical Scripter 2020 Android Java Technical Scripter Java Android Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Add Views Dynamically and Store Data in Arraylist in Android? Android RecyclerView in Kotlin Broadcast Receiver in Android With Example Android SDK and it's Components How to Communicate Between Fragments in Android? Arrays in Java Split() String method in Java with examples Arrays.sort() in Java with examples Object Oriented Programming (OOPs) Concept in Java Reverse a string in Java
[ { "code": null, "e": 54, "s": 26, "text": "\n17 Jan, 2021" }, { "code": null, "e": 603, "s": 54, "text": "Firebase is a famous product of Google which is used by so many developers to add backend functionality for their website as well as apps. The Firebase will make your job really easier for backend database and handling the database. In this article, we will take a look at the implementation of Firebase Firestore in Android. This is a series of 4 articles in which we are going to perform the basic CRUD (Create, Read, Update, and Delete) operation with Firebase Firestore in Android. We are going to cover the following 4 articles in this series:" }, { "code": null, "e": 822, "s": 603, "text": "How to Create and Add Data to Firebase Firestore in Android?How to Read Data from Firebase Firestore in Android?How to Update Data in Firebase Firestore in Android?How to Delete Data from Firebase Firestore in Android?" }, { "code": null, "e": 883, "s": 822, "text": "How to Create and Add Data to Firebase Firestore in Android?" }, { "code": null, "e": 936, "s": 883, "text": "How to Read Data from Firebase Firestore in Android?" }, { "code": null, "e": 989, "s": 936, "text": "How to Update Data in Firebase Firestore in Android?" }, { "code": null, "e": 1044, "s": 989, "text": "How to Delete Data from Firebase Firestore in Android?" }, { "code": null, "e": 1365, "s": 1044, "text": "Firebase Firestore is a cloud NoSQL database that is used to add, retrieve, and update data inside your application. Basically, it is a database that is used to store data inside your Firebase console. The data in the Firestore is stored in the form of documents, so it becomes easy to manage this data inside Firebase. " }, { "code": null, "e": 1782, "s": 1365, "text": "Firestore is having a better query than that of Firebase Realtime Database. It is highly scalable and data can be managed properly inside Firebase Firestore. It becomes easy to access data on the server-side inside the Firebase Firestore database. Firebase Firestore is much easier in comparison to Firebase Realtime Database. You can check a more detailed guide on Firebase Realtime Database vs Firestore database. " }, { "code": null, "e": 2042, "s": 1782, "text": "In this article, we will be building a simple Android Application in which we will be collecting the data from users via some TextFields and we will send that data to our Firebase Cloud Firestore console and that data will get store in our Firebase database. " }, { "code": null, "e": 2071, "s": 2042, "text": "Step 1: Create a new Project" }, { "code": null, "e": 2235, "s": 2071, "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": 2272, "s": 2235, "text": "Step 2: Connect your app to Firebase" }, { "code": null, "e": 2477, "s": 2272, "text": "After creating a new project. Navigate to the Tools option on the top bar. Inside that click on Firebase. After clicking on Firebase, you can get to see the right column mentioned below in the screenshot." }, { "code": null, "e": 2886, "s": 2477, "text": "Inside that column Navigate to Firebase Cloud Firestore. Click on that option and you will get to see two options on Connect app to Firebase and Add Cloud Firestore to your app. Click on Connect now option and your app will be connected to Firebase. After that click on the second option and now your App is connected to Firebase. After connecting your app to Firebase you will get to see the below screen. " }, { "code": null, "e": 3215, "s": 2886, "text": "After that verify that dependency for Firebase Firestore database has been added to our Gradle file. Navigate to the app > Gradle Scripts inside that file. Check whether the below dependency is added or not. If the below dependency is not present in your build.gradle file. Add the below dependency in the dependencies section. " }, { "code": null, "e": 3278, "s": 3215, "text": "implementation ‘com.google.firebase:firebase-firestore:22.0.1’" }, { "code": null, "e": 3515, "s": 3278, "text": "After adding this dependency sync your project and now we are ready for creating our app. If you want to know more about connecting your app to Firebase. Refer to this article to get in detail about How to add Firebase to Android App. " }, { "code": null, "e": 3565, "s": 3515, "text": "Step 3: Working with the AndroidManifest.xml file" }, { "code": null, "e": 3780, "s": 3565, "text": "For adding data to Firebase we should have to give permissions for accessing the internet. For adding these permissions navigate to the app > AndroidManifest.xml. Inside that file add the below permissions to it. " }, { "code": null, "e": 3784, "s": 3780, "text": "XML" }, { "code": "<!--Permissions for internet--><uses-permission android:name=\"android.permission.INTERNET\" /><uses-permission android:name=\"android.permission.ACCESS_NETWORK_STATE\" />", "e": 3952, "s": 3784, "text": null }, { "code": null, "e": 4001, "s": 3952, "text": " Step 4: Working with the activity_main.xml file" }, { "code": null, "e": 4118, "s": 4001, "text": "Go to the activity_main.xml file and refer to the following code. Below is the code for the activity_main.xml file. " }, { "code": null, "e": 4122, "s": 4118, "text": "XML" }, { "code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><LinearLayout 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:orientation=\"vertical\" tools:context=\".MainActivity\"> <!--Edittext for getting course Name--> <EditText android:id=\"@+id/idEdtCourseName\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_marginStart=\"10dp\" android:layout_marginTop=\"20dp\" android:layout_marginEnd=\"10dp\" android:hint=\"Course Name\" android:importantForAutofill=\"no\" android:inputType=\"text\" /> <!--Edittext for getting course Duration--> <EditText android:id=\"@+id/idEdtCourseDuration\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_marginStart=\"10dp\" android:layout_marginTop=\"20dp\" android:layout_marginEnd=\"10dp\" android:hint=\"Course Duration in min\" android:importantForAutofill=\"no\" android:inputType=\"time\" /> <!--Edittext for getting course Description--> <EditText android:id=\"@+id/idEdtCourseDescription\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_marginStart=\"10dp\" android:layout_marginTop=\"20dp\" android:layout_marginEnd=\"10dp\" android:hint=\"Course Description\" android:importantForAutofill=\"no\" android:inputType=\"text\" /> <!--Button for adding your course to Firebase--> <Button android:id=\"@+id/idBtnSubmitCourse\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_margin=\"10dp\" android:text=\"Submit Course Details\" android:textAllCaps=\"false\" /> </LinearLayout>", "e": 6043, "s": 4122, "text": null }, { "code": null, "e": 6096, "s": 6043, "text": "Step 5: Create a new Java class for storing the data" }, { "code": null, "e": 6447, "s": 6096, "text": "For sending data to the Firebase Firestore database we have to create an Object class and send that whole object class to Firebase. For creating an object class navigate to the app > java > your app’s package name > Right-click on it and click on New > Java Class > Give a name to your class. Here we named it Courses and add the below code to it. " }, { "code": null, "e": 6452, "s": 6447, "text": "Java" }, { "code": "public class Courses { // variables for storing our data. private String courseName, courseDescription, courseDuration; public Courses() { // empty constructor // required for Firebase. } // Constructor for all variables. public Courses(String courseName, String courseDescription, String courseDuration) { this.courseName = courseName; this.courseDescription = courseDescription; this.courseDuration = courseDuration; } // getter methods for all variables. public String getCourseName() { return courseName; } public void setCourseName(String courseName) { this.courseName = courseName; } public String getCourseDescription() { return courseDescription; } // setter method for all variables. public void setCourseDescription(String courseDescription) { this.courseDescription = courseDescription; } public String getCourseDuration() { return courseDuration; } public void setCourseDuration(String courseDuration) { this.courseDuration = courseDuration; }}", "e": 7558, "s": 6452, "text": null }, { "code": null, "e": 7606, "s": 7558, "text": "Step 6: Working with the MainActivity.java file" }, { "code": null, "e": 7797, "s": 7606, "text": "Go to the MainActivity.java file and refer to the following code. Below is the code for the MainActivity.java file. Comments are added inside the code to understand the code in more detail. " }, { "code": null, "e": 7802, "s": 7797, "text": "Java" }, { "code": "import android.os.Bundle;import android.text.TextUtils;import android.view.View;import android.widget.Button;import android.widget.EditText;import android.widget.Toast; import androidx.annotation.NonNull;import androidx.appcompat.app.AppCompatActivity; import com.google.android.gms.tasks.OnFailureListener;import com.google.android.gms.tasks.OnSuccessListener;import com.google.firebase.firestore.CollectionReference;import com.google.firebase.firestore.DocumentReference;import com.google.firebase.firestore.FirebaseFirestore; public class MainActivity extends AppCompatActivity { // creating variables for our edit text private EditText courseNameEdt, courseDurationEdt, courseDescriptionEdt; // creating variable for button private Button submitCourseBtn; // creating a strings for storing // our values from edittext fields. private String courseName, courseDuration, courseDescription; // creating a variable // for firebasefirestore. private FirebaseFirestore db; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // getting our instance // from Firebase Firestore. db = FirebaseFirestore.getInstance(); // initializing our edittext and buttons courseNameEdt = findViewById(R.id.idEdtCourseName); courseDescriptionEdt = findViewById(R.id.idEdtCourseDescription); courseDurationEdt = findViewById(R.id.idEdtCourseDuration); submitCourseBtn = findViewById(R.id.idBtnSubmitCourse); // adding on click listener for button submitCourseBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // getting data from edittext fields. courseName = courseNameEdt.getText().toString(); courseDescription = courseDescriptionEdt.getText().toString(); courseDuration = courseDurationEdt.getText().toString(); // validating the text fields if empty or not. if (TextUtils.isEmpty(courseName)) { courseNameEdt.setError(\"Please enter Course Name\"); } else if (TextUtils.isEmpty(courseDescription)) { courseDescriptionEdt.setError(\"Please enter Course Description\"); } else if (TextUtils.isEmpty(courseDuration)) { courseDurationEdt.setError(\"Please enter Course Duration\"); } else { // calling method to add data to Firebase Firestore. addDataToFirestore(courseName, courseDescription, courseDuration); } } }); } private void addDataToFirestore(String courseName, String courseDescription, String courseDuration) { // creating a collection reference // for our Firebase Firetore database. CollectionReference dbCourses = db.collection(\"Courses\"); // adding our data to our courses object class. Courses courses = new Courses(courseName, courseDescription, courseDuration); // below method is use to add data to Firebase Firestore. dbCourses.add(courses).addOnSuccessListener(new OnSuccessListener<DocumentReference>() { @Override public void onSuccess(DocumentReference documentReference) { // after the data addition is successful // we are displaying a success toast message. Toast.makeText(MainActivity.this, \"Your Course has been added to Firebase Firestore\", Toast.LENGTH_SHORT).show(); } }).addOnFailureListener(new OnFailureListener() { @Override public void onFailure(@NonNull Exception e) { // this method is called when the data addition process is failed. // displaying a toast message when data addition is failed. Toast.makeText(MainActivity.this, \"Fail to add course \\n\" + e, Toast.LENGTH_SHORT).show(); } }); }}", "e": 11888, "s": 7802, "text": null }, { "code": null, "e": 12082, "s": 11888, "text": "After adding this code go to this link to open Firebase. After clicking on this link you will get to see the below page and on this page Click on Go to Console option in the top right corner. " }, { "code": null, "e": 12207, "s": 12082, "text": "After clicking on this screen you will get to see the below screen with your all project inside that select your project. " }, { "code": null, "e": 12284, "s": 12207, "text": "Inside that screen click n Firebase Firestore Database in the left window. " }, { "code": null, "e": 12368, "s": 12284, "text": "After clicking on the Create Database option you will get to see the below screen. " }, { "code": null, "e": 12656, "s": 12368, "text": "Inside this screen, we have to select the Start in test mode option. We are using test mode because we are not setting authentication inside our app. So we are selecting Start in test mode. After selecting on test mode click on the Next option and you will get to see the below screen. " }, { "code": null, "e": 12954, "s": 12656, "text": "Inside this screen, we just have to click on the Enable button to enable our Firebase Firestore database. After completing this process we just have to run our application and add data inside our app and click on the submit button. You will get to see the data added inside the Firebase Console. " }, { "code": null, "e": 12986, "s": 12954, "text": "Below is the output of the app." }, { "code": null, "e": 13002, "s": 12986, "text": "AmiyaRanjanRout" }, { "code": null, "e": 13010, "s": 13002, "text": "android" }, { "code": null, "e": 13034, "s": 13010, "text": "Technical Scripter 2020" }, { "code": null, "e": 13042, "s": 13034, "text": "Android" }, { "code": null, "e": 13047, "s": 13042, "text": "Java" }, { "code": null, "e": 13066, "s": 13047, "text": "Technical Scripter" }, { "code": null, "e": 13071, "s": 13066, "text": "Java" }, { "code": null, "e": 13079, "s": 13071, "text": "Android" }, { "code": null, "e": 13177, "s": 13079, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 13246, "s": 13177, "text": "How to Add Views Dynamically and Store Data in Arraylist in Android?" }, { "code": null, "e": 13277, "s": 13246, "text": "Android RecyclerView in Kotlin" }, { "code": null, "e": 13320, "s": 13277, "text": "Broadcast Receiver in Android With Example" }, { "code": null, "e": 13352, "s": 13320, "text": "Android SDK and it's Components" }, { "code": null, "e": 13401, "s": 13352, "text": "How to Communicate Between Fragments in Android?" }, { "code": null, "e": 13416, "s": 13401, "text": "Arrays in Java" }, { "code": null, "e": 13460, "s": 13416, "text": "Split() String method in Java with examples" }, { "code": null, "e": 13496, "s": 13460, "text": "Arrays.sort() in Java with examples" }, { "code": null, "e": 13547, "s": 13496, "text": "Object Oriented Programming (OOPs) Concept in Java" } ]
Create 2D Pixel Plot in Python
08 May, 2021 Pixel plots are the representation of a 2-dimension data set. In these plots, each pixel refers to a different value in a data set. In this article, we will discuss how to generate 2D pixel plots from data. A pixel plot of raw data can be generated by using the cmap and interpolation parameters of the imshow() method in matplot.pyplot module. matplotlib.pyplot.imshow(X, cmap=None, norm=None, aspect=None, interpolation=None, alpha=None, vmin=None, vmax=None, origin=None, extent=None, shape=, filternorm=1, filterrad=4.0, imlim=, resample=None, url=None, \*, data=None, \*\*kwargs) The basic steps to create 2D pixel plots in python using Matplotlib are as follows: Step 1: Importing Required Libraries We are importing NumPy library for creating a dataset and a ‘pyplot’ module from a matplotlib library for plotting pixel plots import numpy as np import matplotlib.pyplot as plt Step 2: Preparing data For plotting, we need 2-dimensional data. Let’s create a 2d array using the random method in NumPy. Here data1 array is of three sub arrays with no of elements equal to 7, while data2 is an array of four sub-arrays with each array consisting of five elements having random value ranges between zero and one. The random method takes a maximum of five arguments. data1 = np.random.random((3,7)) data2 = np.random.random((4,5)) We can also import a CSV file, text file, or image. Step 2.1: For importing a text file: data_file = np.loadtxt("myfile.txt") Step 2.2: For importing CSV files: data_file = np.genfromtxt("my_file.csv", delimiter=',') Step 2.3: For importing images: img = np.load('my_img.png') Step 3: Creating a plot All plotting is done with respect to an axis. In most cases, a subplot which is an axes on a grid system will fit your needs. Hence, we are adding axes to the plot. Given data will be divided into nrows and ncols provided by the user. pixel_plot = plt.figure() pixel_plot.add_axes() axes = plt.subplots(nrows,ncols) Step 4: Plotting a plot For plotting a plot plt.plot(pixel_plot) Step 5: Customize a plot: We can customize a plot by giving a title for plot, x-axes, y-axes, numbers, and in various ways. For the pixel plot, we can add a color bar that determines the value of each pixel. The imshow() method’s attribute named interpolation with attribute value none or nearest helps to plot a plot in pixels. Here cmap attribute for the coloring of the map. plt.title("pixel_plot") pixel_plot = plt.imshow(pixel_plot,cmap='',interpolation='') plt.colorbar(pixel_plot) Step 6: Save plot For saving a transparent image we need to set a transparent attribute to value true by default it is false plt.savefig('pixel_plot.png') plt.savefig('pixel_plot.png',transparent=True) Step 7: Show plot: And finally, for showing a plot a simple function is used plt.show(pixel_plot) Below are some examples that depict how to generate 2D pixel plots using matplotlib. Example 1: In this program, we generate a 2D pixel plot from a matrix created using random() method. Python3 # importing modulesimport numpy as npimport matplotlib.pyplot as plt # creating a dataset# data is an array with four sub # arrays with 10 elements in eachdata = np.random.random((4, 10)) # creating a plotpixel_plot = plt.figure() # plotting a plotpixel_plot.add_axes() # customizing plotplt.title("pixel_plot")pixel_plot = plt.imshow( data, cmap='twilight', interpolation='nearest') plt.colorbar(pixel_plot) # save a plotplt.savefig('pixel_plot.png') # show plotplt.show(pixel_plot) Output: Example 2: In this example, we are taking input of a randomly generated 3D array and generate a 2D pixel plot out of it. Python3 # importing modulesimport numpy as npimport matplotlib.pyplot as plt # creating a datasetdata = np.random.random((10, 12, 10)) # data is an 3d array with # 10x12x10=1200 elements.# reshape this 3d array in 2d# array for plottingnrows, ncols = 40, 30data = data.reshape(nrows, ncols) # creating a plotpixel_plot = plt.figure() # plotting a plotpixel_plot.add_axes() # customizing plotplt.title("pixel_plot")pixel_plot = plt.imshow( data, cmap='Greens', interpolation='nearest', origin='lower') plt.colorbar(pixel_plot) # save a plotplt.savefig('pixel_plot.png') # show plotplt.show(pixel_plot) Output: Example 3: In this example, we manually create a 3D array and generate its pixel plot. Python3 # importing modulesimport numpy as npimport matplotlib.pyplot as plt # creating a datasetdata = np.random.random((10, 12, 10)) # data is an 3d array # with 10x12x10=1200 elements.# reshape this 3d array in 2d# array for plottingnrows, ncols = 40, 30data = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] # creating a plotpixel_plot = plt.figure() # plotting a plotpixel_plot.add_axes() # customizing plotplt.title("pixel_plot")pixel_plot = plt.imshow( data, cmap='Greens', interpolation='nearest', origin='lower') plt.colorbar(pixel_plot) # save a plotplt.savefig('pixel_plot.png') # show plotplt.show(pixel_plot) Output: Picked Python-matplotlib Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Python Classes and Objects Python OOPs Concepts Introduction To PYTHON Python | os.path.join() method How to drop one or multiple columns in Pandas Dataframe How To Convert Python Dictionary To JSON? Check if element exists in list in Python Python | Get unique values from a list Python | datetime.timedelta() function
[ { "code": null, "e": 28, "s": 0, "text": "\n08 May, 2021" }, { "code": null, "e": 373, "s": 28, "text": "Pixel plots are the representation of a 2-dimension data set. In these plots, each pixel refers to a different value in a data set. In this article, we will discuss how to generate 2D pixel plots from data. A pixel plot of raw data can be generated by using the cmap and interpolation parameters of the imshow() method in matplot.pyplot module." }, { "code": null, "e": 613, "s": 373, "text": "matplotlib.pyplot.imshow(X, cmap=None, norm=None, aspect=None, interpolation=None, alpha=None, vmin=None, vmax=None, origin=None, extent=None, shape=, filternorm=1, filterrad=4.0, imlim=, resample=None, url=None, \\*, data=None, \\*\\*kwargs)" }, { "code": null, "e": 697, "s": 613, "text": "The basic steps to create 2D pixel plots in python using Matplotlib are as follows:" }, { "code": null, "e": 734, "s": 697, "text": "Step 1: Importing Required Libraries" }, { "code": null, "e": 861, "s": 734, "text": "We are importing NumPy library for creating a dataset and a ‘pyplot’ module from a matplotlib library for plotting pixel plots" }, { "code": null, "e": 912, "s": 861, "text": "import numpy as np\nimport matplotlib.pyplot as plt" }, { "code": null, "e": 935, "s": 912, "text": "Step 2: Preparing data" }, { "code": null, "e": 1296, "s": 935, "text": "For plotting, we need 2-dimensional data. Let’s create a 2d array using the random method in NumPy. Here data1 array is of three sub arrays with no of elements equal to 7, while data2 is an array of four sub-arrays with each array consisting of five elements having random value ranges between zero and one. The random method takes a maximum of five arguments." }, { "code": null, "e": 1366, "s": 1296, "text": "data1 = np.random.random((3,7)) \ndata2 = np.random.random((4,5)) " }, { "code": null, "e": 1419, "s": 1366, "text": "We can also import a CSV file, text file, or image. " }, { "code": null, "e": 1456, "s": 1419, "text": "Step 2.1: For importing a text file:" }, { "code": null, "e": 1493, "s": 1456, "text": "data_file = np.loadtxt(\"myfile.txt\")" }, { "code": null, "e": 1528, "s": 1493, "text": "Step 2.2: For importing CSV files:" }, { "code": null, "e": 1584, "s": 1528, "text": "data_file = np.genfromtxt(\"my_file.csv\", delimiter=',')" }, { "code": null, "e": 1616, "s": 1584, "text": "Step 2.3: For importing images:" }, { "code": null, "e": 1645, "s": 1616, "text": " img = np.load('my_img.png')" }, { "code": null, "e": 1669, "s": 1645, "text": "Step 3: Creating a plot" }, { "code": null, "e": 1904, "s": 1669, "text": "All plotting is done with respect to an axis. In most cases, a subplot which is an axes on a grid system will fit your needs. Hence, we are adding axes to the plot. Given data will be divided into nrows and ncols provided by the user." }, { "code": null, "e": 1985, "s": 1904, "text": "pixel_plot = plt.figure()\npixel_plot.add_axes()\naxes = plt.subplots(nrows,ncols)" }, { "code": null, "e": 2009, "s": 1985, "text": "Step 4: Plotting a plot" }, { "code": null, "e": 2030, "s": 2009, "text": " For plotting a plot" }, { "code": null, "e": 2052, "s": 2030, "text": " plt.plot(pixel_plot)" }, { "code": null, "e": 2080, "s": 2052, "text": " Step 5: Customize a plot: " }, { "code": null, "e": 2432, "s": 2080, "text": "We can customize a plot by giving a title for plot, x-axes, y-axes, numbers, and in various ways. For the pixel plot, we can add a color bar that determines the value of each pixel. The imshow() method’s attribute named interpolation with attribute value none or nearest helps to plot a plot in pixels. Here cmap attribute for the coloring of the map." }, { "code": null, "e": 2545, "s": 2432, "text": " plt.title(\"pixel_plot\")\n pixel_plot = plt.imshow(pixel_plot,cmap='',interpolation='')\n plt.colorbar(pixel_plot)" }, { "code": null, "e": 2563, "s": 2545, "text": "Step 6: Save plot" }, { "code": null, "e": 2670, "s": 2563, "text": "For saving a transparent image we need to set a transparent attribute to value true by default it is false" }, { "code": null, "e": 2747, "s": 2670, "text": "plt.savefig('pixel_plot.png')\nplt.savefig('pixel_plot.png',transparent=True)" }, { "code": null, "e": 2766, "s": 2747, "text": "Step 7: Show plot:" }, { "code": null, "e": 2825, "s": 2766, "text": " And finally, for showing a plot a simple function is used" }, { "code": null, "e": 2846, "s": 2825, "text": "plt.show(pixel_plot)" }, { "code": null, "e": 2931, "s": 2846, "text": "Below are some examples that depict how to generate 2D pixel plots using matplotlib." }, { "code": null, "e": 3032, "s": 2931, "text": "Example 1: In this program, we generate a 2D pixel plot from a matrix created using random() method." }, { "code": null, "e": 3040, "s": 3032, "text": "Python3" }, { "code": "# importing modulesimport numpy as npimport matplotlib.pyplot as plt # creating a dataset# data is an array with four sub # arrays with 10 elements in eachdata = np.random.random((4, 10)) # creating a plotpixel_plot = plt.figure() # plotting a plotpixel_plot.add_axes() # customizing plotplt.title(\"pixel_plot\")pixel_plot = plt.imshow( data, cmap='twilight', interpolation='nearest') plt.colorbar(pixel_plot) # save a plotplt.savefig('pixel_plot.png') # show plotplt.show(pixel_plot)", "e": 3532, "s": 3040, "text": null }, { "code": null, "e": 3540, "s": 3532, "text": "Output:" }, { "code": null, "e": 3661, "s": 3540, "text": "Example 2: In this example, we are taking input of a randomly generated 3D array and generate a 2D pixel plot out of it." }, { "code": null, "e": 3669, "s": 3661, "text": "Python3" }, { "code": "# importing modulesimport numpy as npimport matplotlib.pyplot as plt # creating a datasetdata = np.random.random((10, 12, 10)) # data is an 3d array with # 10x12x10=1200 elements.# reshape this 3d array in 2d# array for plottingnrows, ncols = 40, 30data = data.reshape(nrows, ncols) # creating a plotpixel_plot = plt.figure() # plotting a plotpixel_plot.add_axes() # customizing plotplt.title(\"pixel_plot\")pixel_plot = plt.imshow( data, cmap='Greens', interpolation='nearest', origin='lower') plt.colorbar(pixel_plot) # save a plotplt.savefig('pixel_plot.png') # show plotplt.show(pixel_plot)", "e": 4272, "s": 3669, "text": null }, { "code": null, "e": 4280, "s": 4272, "text": "Output:" }, { "code": null, "e": 4367, "s": 4280, "text": "Example 3: In this example, we manually create a 3D array and generate its pixel plot." }, { "code": null, "e": 4375, "s": 4367, "text": "Python3" }, { "code": "# importing modulesimport numpy as npimport matplotlib.pyplot as plt # creating a datasetdata = np.random.random((10, 12, 10)) # data is an 3d array # with 10x12x10=1200 elements.# reshape this 3d array in 2d# array for plottingnrows, ncols = 40, 30data = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] # creating a plotpixel_plot = plt.figure() # plotting a plotpixel_plot.add_axes() # customizing plotplt.title(\"pixel_plot\")pixel_plot = plt.imshow( data, cmap='Greens', interpolation='nearest', origin='lower') plt.colorbar(pixel_plot) # save a plotplt.savefig('pixel_plot.png') # show plotplt.show(pixel_plot)", "e": 4984, "s": 4375, "text": null }, { "code": null, "e": 4992, "s": 4984, "text": "Output:" }, { "code": null, "e": 4999, "s": 4992, "text": "Picked" }, { "code": null, "e": 5017, "s": 4999, "text": "Python-matplotlib" }, { "code": null, "e": 5024, "s": 5017, "text": "Python" }, { "code": null, "e": 5122, "s": 5024, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 5154, "s": 5122, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 5181, "s": 5154, "text": "Python Classes and Objects" }, { "code": null, "e": 5202, "s": 5181, "text": "Python OOPs Concepts" }, { "code": null, "e": 5225, "s": 5202, "text": "Introduction To PYTHON" }, { "code": null, "e": 5256, "s": 5225, "text": "Python | os.path.join() method" }, { "code": null, "e": 5312, "s": 5256, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 5354, "s": 5312, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 5396, "s": 5354, "text": "Check if element exists in list in Python" }, { "code": null, "e": 5435, "s": 5396, "text": "Python | Get unique values from a list" } ]