title
stringlengths
3
221
text
stringlengths
17
477k
parsed
listlengths
0
3.17k
How to Remove an Event Handler using jQuery ? - GeeksforGeeks
24 Oct, 2021 Here, the task is to remove an event handler in the jQuery/JavaScript. There are three methods to solve this problem which are discussed below:Using unbind() method: It is an inbuilt method in jQuery which is used to remove any selected event handlers. Syntax: $(selector).unbind(event, function, eventObj) Approach: Select the selector on which the event handler is to be removed. Use the unbind() method to remove event. After click on the function under which unbind works will remove the event handler. Example 1: html <!DOCTYPE html> <html> <head> <title> jQuery | How to remove an event handler? </title> </head> <body style = "text-align:center;"> <h1 style = "color:green;" > GeeksForGeeks </h1> <h3> Remove an event handler using unbind method </h3> <h4>Element to remove</h4> <button> Click Here </button> <script> $(document).ready(function() { $("h4").click(function() { $(this).slideToggle(); }); $("button").click(function() { $("h4").unbind(); }); }); </script></body> </html> Output: Before click anywhere: After click on the element h4: After clicking on the button event will not work: Using off() Method: It is used to remove event handlers attached with the on() method. Syntax: $(selector).off(event, selector, function(eventObj), map) Approach: Select the selector on which the event handler is to be removed. Use the off() method to remove event. After click on the function under which unbind works will remove the event handler. Example 2: html <!DOCTYPE html> <html> <head> <title> jQuery | How to remove an event handler? </title> </head> <body style = "text-align:center;"> <h1 style = "color:green;" > GeeksForGeeks </h1> <h3> Remove an event handler using off method </h3> <h4>Element to remove</h4> <button> Click Here </button> <script> $(document).ready(function() { $("h4").click(function() { $(this).slideToggle(); }); $("button").click(function() { $("h4").off(); }); }); </script></body> </html> Output: Before click anywhere: After click on the element h4: After clicking on the button event will not work: saurabh1990aror jQuery-Misc JQuery Web Technologies Web technologies Questions Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments How to prevent Body from scrolling when a modal is opened using jQuery ? jQuery | ajax() Method Difference Between JavaScript and jQuery How to get the value in an input text box using jQuery ? jQuery | parent() & parents() with Examples Top 10 Front End Developer Skills That You Need in 2022 Installation of Node.js on Linux Top 10 Projects For Beginners To Practice HTML and CSS Skills How to fetch data from an API in ReactJS ? How to insert spaces/tabs in text using HTML/CSS?
[ { "code": null, "e": 25364, "s": 25336, "text": "\n24 Oct, 2021" }, { "code": null, "e": 25627, "s": 25364, "text": "Here, the task is to remove an event handler in the jQuery/JavaScript. There are three methods to solve this problem which are discussed below:Using unbind() method: It is an inbuilt method in jQuery which is used to remove any selected event handlers. Syntax: " }, { "code": null, "e": 25673, "s": 25627, "text": "$(selector).unbind(event, function, eventObj)" }, { "code": null, "e": 25685, "s": 25673, "text": "Approach: " }, { "code": null, "e": 25750, "s": 25685, "text": "Select the selector on which the event handler is to be removed." }, { "code": null, "e": 25791, "s": 25750, "text": "Use the unbind() method to remove event." }, { "code": null, "e": 25875, "s": 25791, "text": "After click on the function under which unbind works will remove the event handler." }, { "code": null, "e": 25888, "s": 25875, "text": "Example 1: " }, { "code": null, "e": 25893, "s": 25888, "text": "html" }, { "code": "<!DOCTYPE html> <html> <head> <title> jQuery | How to remove an event handler? </title> </head> <body style = \"text-align:center;\"> <h1 style = \"color:green;\" > GeeksForGeeks </h1> <h3> Remove an event handler using unbind method </h3> <h4>Element to remove</h4> <button> Click Here </button> <script> $(document).ready(function() { $(\"h4\").click(function() { $(this).slideToggle(); }); $(\"button\").click(function() { $(\"h4\").unbind(); }); }); </script></body> </html> ", "e": 26597, "s": 25893, "text": null }, { "code": null, "e": 26607, "s": 26597, "text": "Output: " }, { "code": null, "e": 26632, "s": 26607, "text": "Before click anywhere: " }, { "code": null, "e": 26665, "s": 26632, "text": "After click on the element h4: " }, { "code": null, "e": 26717, "s": 26665, "text": "After clicking on the button event will not work: " }, { "code": null, "e": 26814, "s": 26717, "text": "Using off() Method: It is used to remove event handlers attached with the on() method. Syntax: " }, { "code": null, "e": 26872, "s": 26814, "text": "$(selector).off(event, selector, function(eventObj), map)" }, { "code": null, "e": 26884, "s": 26872, "text": "Approach: " }, { "code": null, "e": 26949, "s": 26884, "text": "Select the selector on which the event handler is to be removed." }, { "code": null, "e": 26987, "s": 26949, "text": "Use the off() method to remove event." }, { "code": null, "e": 27071, "s": 26987, "text": "After click on the function under which unbind works will remove the event handler." }, { "code": null, "e": 27084, "s": 27071, "text": "Example 2: " }, { "code": null, "e": 27089, "s": 27084, "text": "html" }, { "code": "<!DOCTYPE html> <html> <head> <title> jQuery | How to remove an event handler? </title> </head> <body style = \"text-align:center;\"> <h1 style = \"color:green;\" > GeeksForGeeks </h1> <h3> Remove an event handler using off method </h3> <h4>Element to remove</h4> <button> Click Here </button> <script> $(document).ready(function() { $(\"h4\").click(function() { $(this).slideToggle(); }); $(\"button\").click(function() { $(\"h4\").off(); }); }); </script></body> </html> ", "e": 27787, "s": 27089, "text": null }, { "code": null, "e": 27797, "s": 27787, "text": "Output: " }, { "code": null, "e": 27822, "s": 27797, "text": "Before click anywhere: " }, { "code": null, "e": 27855, "s": 27822, "text": "After click on the element h4: " }, { "code": null, "e": 27907, "s": 27855, "text": "After clicking on the button event will not work: " }, { "code": null, "e": 27925, "s": 27909, "text": "saurabh1990aror" }, { "code": null, "e": 27937, "s": 27925, "text": "jQuery-Misc" }, { "code": null, "e": 27944, "s": 27937, "text": "JQuery" }, { "code": null, "e": 27961, "s": 27944, "text": "Web Technologies" }, { "code": null, "e": 27988, "s": 27961, "text": "Web technologies Questions" }, { "code": null, "e": 28086, "s": 27988, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28095, "s": 28086, "text": "Comments" }, { "code": null, "e": 28108, "s": 28095, "text": "Old Comments" }, { "code": null, "e": 28181, "s": 28108, "text": "How to prevent Body from scrolling when a modal is opened using jQuery ?" }, { "code": null, "e": 28204, "s": 28181, "text": "jQuery | ajax() Method" }, { "code": null, "e": 28245, "s": 28204, "text": "Difference Between JavaScript and jQuery" }, { "code": null, "e": 28302, "s": 28245, "text": "How to get the value in an input text box using jQuery ?" }, { "code": null, "e": 28346, "s": 28302, "text": "jQuery | parent() & parents() with Examples" }, { "code": null, "e": 28402, "s": 28346, "text": "Top 10 Front End Developer Skills That You Need in 2022" }, { "code": null, "e": 28435, "s": 28402, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 28497, "s": 28435, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 28540, "s": 28497, "text": "How to fetch data from an API in ReactJS ?" } ]
What is autoFlush attribute in JSP?
The autoFlush attribute specifies whether the buffered output should be flushed automatically when the buffer is filled, or whether an exception should be raised to indicate the buffer overflow. A value of true (default) indicates automatic buffer flushing and a value of false throws an exception. The following directive causes the servlet to throw an exception when the servlet's output buffer is full − <%@ page autoFlush = "false" %> This directive causes the servlet to flush the output buffer when full − <%@ page autoFlush = "true" %> Usually, the buffer and the autoFlush attributes are coded on a single page directive as follows − <%@ page buffer = "16kb" autoflush = "true" %>
[ { "code": null, "e": 1257, "s": 1062, "text": "The autoFlush attribute specifies whether the buffered output should be flushed automatically when the buffer is filled, or whether an exception should be raised to indicate the buffer overflow." }, { "code": null, "e": 1361, "s": 1257, "text": "A value of true (default) indicates automatic buffer flushing and a value of false throws an exception." }, { "code": null, "e": 1469, "s": 1361, "text": "The following directive causes the servlet to throw an exception when the servlet's output buffer is full −" }, { "code": null, "e": 1501, "s": 1469, "text": "<%@ page autoFlush = \"false\" %>" }, { "code": null, "e": 1574, "s": 1501, "text": "This directive causes the servlet to flush the output buffer when full −" }, { "code": null, "e": 1605, "s": 1574, "text": "<%@ page autoFlush = \"true\" %>" }, { "code": null, "e": 1704, "s": 1605, "text": "Usually, the buffer and the autoFlush attributes are coded on a single page directive as follows −" }, { "code": null, "e": 1751, "s": 1704, "text": "<%@ page buffer = \"16kb\" autoflush = \"true\" %>" } ]
How to Use Variance Thresholding For Robust Feature Selection | by Bex T. | Towards Data Science
Today, it is common for datasets to have hundreds if not thousands of features. On the surface, this might seem like a good thing — more features give more information about each sample. But more often than not, these additional features don’t provide that much value and introduce unnecessary complexity. The biggest challenge of Machine Learning is to create models that have robust predictive power by using as few features as possible. But given the massive sizes of today’s datasets, it is easy to lose the oversight of which features are important and which ones aren’t. That’s why there is an entire skill to be learned in the ML field — feature selection. Feature selection is the process of choosing a subset of the most important features while trying to retain as much information as possible. As an example, let’s say we have a dataset of body measurements such as weight, height, BMI, etc. Basic feature selection techniques should be able to drop BMI by finding out that BMI can be represented by weight and height. In this article, we will explore one such feature selection technique called Variance Thresholding. This technique is a quick and lightweight way of eliminating features with very low variance, i. e. features with not much useful information. For those who are not familiar, variance, as the name suggests, shows the variability in a distribution in a single metric. It shows how spread out the distribution is and shows the average squared distance from the mean: Obviously, distributions with bigger values yield a bigger variance because each difference is squared. But the main thing we care about in ML is that the distribution actually contains useful information. For example, consider this distribution: Computing the variance with Numpy shows us that the distribution has 0 variance or in other words completely useless. Using a feature with zero-variance only adds to model complexity, not to its predictive power. Consider another one: Similarly, this one is almost made up of a single constant. Distributions that go around a single constant with a few exceptions are also useless. In other words, any feature or distribution with close to 0 variance should be dropped. Manually computing variances and thresholding them can be a lot of work. Fortunately, Scikit-learn provides VarianceThreshold estimator which can do all the work for us. Just pass a threshold cut-off and all features below that threshold will be dropped. To demonstrate VarianceThreshold, we will be working with the Ansur dataset. This dataset records measurements of the human body in every imaginable way. Both male and female datasets contain 108 features or measurements of almost 6000 (4000 male, 2000 female) US Army Personnel. We will be focusing on the male dataset: First, let’s get rid of the features with zero-variance. We will import VarianceThreshold from sklearn.feature_selection: We initialize it just like any other Scikit-learn estimator. The default value for the threshold is always 0. Also, the estimator only works with numeric data obviously and it will raise an error if there are categorical features present in the dataframe. That’s why, for now, we will subset the numeric features into another dataframe: So, we have got 98 numeric features. Let’s now fit the estimator to the data and get its results: Directly calling fit_transform will return the dataframe as a numpy array with features dropped. But sometimes, we don't want the result in that format because the column names will be removed. Consider the alternative: First, we fit the estimator to data and call its get_support() method. It returns a boolean mask with True values for columns which are not dropped. We can then use this mask to subset our DataFrame like so: Let’s check the shape of the DataFrame to see if there were any constant columns: >>> ansur_male_num.shape(4082, 98) Nope, we still have the same number of features. Now, let’s drop features with variances close to 0: With a threshold of 1, only 1 feature got dropped. Often, it is not fair to compare the variance of a feature to another. The reason is that as the values in the distribution get bigger, the variance grows exponentially. In other words, the variances will not be on the same scale. Consider this example: The above features all have different medians, quartiles, and ranges — completely different distributions. We cannot compare these features to each other. One method we can use is normalizing all features by dividing them by their mean: This method ensures that all variances are on the same scale: Now, we can use the estimator with a lower threshold like 0.005 or 0.003: As you can see, we were able to drop 50 features from the dataset. Now, let’s test if we did the right thing by dropping so many features. We will check this by training two RandomForestRegressor to predict a person’s weight in pounds: the first one on the final, feature selected dataset and the second one on the full, numeric-feature only dataset. Both training and test score suggest a really high performance without overfitting. Now, let’s train the same model on the full numeric-only dataset: As you can see, even by dropping 50 features we were able to build a pretty powerful model. Even though Variance Thresholding is a simple method, it can go a long way when performing a feature selection. However, keep in mind that this technique does not take into account the relationship between features or the connection between features and target. Therefore, always double-check that using VT brings performance increase or at least lowers model complexity by doing something like we did with RandomForestRegressor. Also, check out the official user guide on feature selection by Scikit-learn — there, you can learn how to insert VT estimators in pipeline instances. The guide contains information on other feature selection techniques as well. If you don’t know what to read next, here, I have picked some for you:
[ { "code": null, "e": 478, "s": 172, "text": "Today, it is common for datasets to have hundreds if not thousands of features. On the surface, this might seem like a good thing — more features give more information about each sample. But more often than not, these additional features don’t provide that much value and introduce unnecessary complexity." }, { "code": null, "e": 749, "s": 478, "text": "The biggest challenge of Machine Learning is to create models that have robust predictive power by using as few features as possible. But given the massive sizes of today’s datasets, it is easy to lose the oversight of which features are important and which ones aren’t." }, { "code": null, "e": 977, "s": 749, "text": "That’s why there is an entire skill to be learned in the ML field — feature selection. Feature selection is the process of choosing a subset of the most important features while trying to retain as much information as possible." }, { "code": null, "e": 1202, "s": 977, "text": "As an example, let’s say we have a dataset of body measurements such as weight, height, BMI, etc. Basic feature selection techniques should be able to drop BMI by finding out that BMI can be represented by weight and height." }, { "code": null, "e": 1445, "s": 1202, "text": "In this article, we will explore one such feature selection technique called Variance Thresholding. This technique is a quick and lightweight way of eliminating features with very low variance, i. e. features with not much useful information." }, { "code": null, "e": 1667, "s": 1445, "text": "For those who are not familiar, variance, as the name suggests, shows the variability in a distribution in a single metric. It shows how spread out the distribution is and shows the average squared distance from the mean:" }, { "code": null, "e": 1914, "s": 1667, "text": "Obviously, distributions with bigger values yield a bigger variance because each difference is squared. But the main thing we care about in ML is that the distribution actually contains useful information. For example, consider this distribution:" }, { "code": null, "e": 2149, "s": 1914, "text": "Computing the variance with Numpy shows us that the distribution has 0 variance or in other words completely useless. Using a feature with zero-variance only adds to model complexity, not to its predictive power. Consider another one:" }, { "code": null, "e": 2384, "s": 2149, "text": "Similarly, this one is almost made up of a single constant. Distributions that go around a single constant with a few exceptions are also useless. In other words, any feature or distribution with close to 0 variance should be dropped." }, { "code": null, "e": 2639, "s": 2384, "text": "Manually computing variances and thresholding them can be a lot of work. Fortunately, Scikit-learn provides VarianceThreshold estimator which can do all the work for us. Just pass a threshold cut-off and all features below that threshold will be dropped." }, { "code": null, "e": 2960, "s": 2639, "text": "To demonstrate VarianceThreshold, we will be working with the Ansur dataset. This dataset records measurements of the human body in every imaginable way. Both male and female datasets contain 108 features or measurements of almost 6000 (4000 male, 2000 female) US Army Personnel. We will be focusing on the male dataset:" }, { "code": null, "e": 3082, "s": 2960, "text": "First, let’s get rid of the features with zero-variance. We will import VarianceThreshold from sklearn.feature_selection:" }, { "code": null, "e": 3419, "s": 3082, "text": "We initialize it just like any other Scikit-learn estimator. The default value for the threshold is always 0. Also, the estimator only works with numeric data obviously and it will raise an error if there are categorical features present in the dataframe. That’s why, for now, we will subset the numeric features into another dataframe:" }, { "code": null, "e": 3517, "s": 3419, "text": "So, we have got 98 numeric features. Let’s now fit the estimator to the data and get its results:" }, { "code": null, "e": 3737, "s": 3517, "text": "Directly calling fit_transform will return the dataframe as a numpy array with features dropped. But sometimes, we don't want the result in that format because the column names will be removed. Consider the alternative:" }, { "code": null, "e": 3945, "s": 3737, "text": "First, we fit the estimator to data and call its get_support() method. It returns a boolean mask with True values for columns which are not dropped. We can then use this mask to subset our DataFrame like so:" }, { "code": null, "e": 4027, "s": 3945, "text": "Let’s check the shape of the DataFrame to see if there were any constant columns:" }, { "code": null, "e": 4062, "s": 4027, "text": ">>> ansur_male_num.shape(4082, 98)" }, { "code": null, "e": 4163, "s": 4062, "text": "Nope, we still have the same number of features. Now, let’s drop features with variances close to 0:" }, { "code": null, "e": 4214, "s": 4163, "text": "With a threshold of 1, only 1 feature got dropped." }, { "code": null, "e": 4468, "s": 4214, "text": "Often, it is not fair to compare the variance of a feature to another. The reason is that as the values in the distribution get bigger, the variance grows exponentially. In other words, the variances will not be on the same scale. Consider this example:" }, { "code": null, "e": 4623, "s": 4468, "text": "The above features all have different medians, quartiles, and ranges — completely different distributions. We cannot compare these features to each other." }, { "code": null, "e": 4705, "s": 4623, "text": "One method we can use is normalizing all features by dividing them by their mean:" }, { "code": null, "e": 4767, "s": 4705, "text": "This method ensures that all variances are on the same scale:" }, { "code": null, "e": 4841, "s": 4767, "text": "Now, we can use the estimator with a lower threshold like 0.005 or 0.003:" }, { "code": null, "e": 4980, "s": 4841, "text": "As you can see, we were able to drop 50 features from the dataset. Now, let’s test if we did the right thing by dropping so many features." }, { "code": null, "e": 5192, "s": 4980, "text": "We will check this by training two RandomForestRegressor to predict a person’s weight in pounds: the first one on the final, feature selected dataset and the second one on the full, numeric-feature only dataset." }, { "code": null, "e": 5342, "s": 5192, "text": "Both training and test score suggest a really high performance without overfitting. Now, let’s train the same model on the full numeric-only dataset:" }, { "code": null, "e": 5434, "s": 5342, "text": "As you can see, even by dropping 50 features we were able to build a pretty powerful model." }, { "code": null, "e": 5864, "s": 5434, "text": "Even though Variance Thresholding is a simple method, it can go a long way when performing a feature selection. However, keep in mind that this technique does not take into account the relationship between features or the connection between features and target. Therefore, always double-check that using VT brings performance increase or at least lowers model complexity by doing something like we did with RandomForestRegressor." }, { "code": null, "e": 6093, "s": 5864, "text": "Also, check out the official user guide on feature selection by Scikit-learn — there, you can learn how to insert VT estimators in pipeline instances. The guide contains information on other feature selection techniques as well." } ]
Introduction to NLP - Part 4: Supervised text classification model in Python | by Zolzaya Luvsandorj | Towards Data Science
This post will show you a simplified example of building a basic supervised text classification model. If this sounds a little gibberish, let’s see some definitions: 💡 supervised: we know the correct output class for each text in sample data💡 text: input data is in a text format💡 classification model: a model that uses input data to predict output classEach input text is also known as ‘document’ and output is also known as ‘target’ (the term, not the shop! 😄). Does supervised text classification model sound more meaningful now? Maybe? Among supervised text classification models, we will focus on one particular type in this post. Here, we will build a supervised sentiment classifier as we will be using a sentiment polarity data on movie reviews with a binary target. This post assumes that you have access to and are familiar with Python including installing packages, defining functions and other basic tasks. If you are new to Python, this is a good place to get started. I have used and tested the scripts in Python 3.7.1. Let’s make sure you have the right tools before we get started. We will use the following powerful third party packages: pandas: Data analysis library, nltk: Natural Language Tool Kit library and sklearn: Machine Learning library. The script below can help you download these corpora. If you have already downloaded, running this will notify you that they are up-to-date: import nltknltk.download('stopwords') nltk.download('wordnet')nltk.download('movie_reviews') Firstly, let’s prepare the environment by importing the required packages: import pandas as pdfrom nltk.corpus import movie_reviews, stopwordsfrom nltk.stem import WordNetLemmatizerfrom nltk.tokenize import RegexpTokenizerfrom sklearn.model_selection import train_test_split, cross_val_score, cross_val_predict, GridSearchCVfrom sklearn.feature_extraction.text import TfidfVectorizerfrom sklearn.linear_model import SGDClassifierfrom sklearn.pipeline import Pipelinefrom sklearn.metrics import confusion_matrix, accuracy_score We will transform movie_reviews tagged corpus from nltk to a pandas dataframe with the script below: # Script copied from herereviews = []for fileid in movie_reviews.fileids(): tag, filename = fileid.split('/') reviews.append((tag, movie_reviews.raw(fileid)))sample = pd.DataFrame(reviews, columns=['target', 'document'])print(f'Dimensions: {sample.shape}')sample.head() You will see that the dataframe has 2 columns: a column for the targets, the polarity sentiment, and a column for the reviews (i.e. documents) for 2000 reviews. Each review is either tagged as positive or negative review. Let’s check the counts of the target classes: sample[‘target’].value_counts() Each class (i.e. ‘pos’, ‘neg’) has 1000 records each, perfectly balanced. Let’s ensure that the classes are binary coded: sample['target'] = np.where(sample['target']=='pos', 1, 0)sample['target'].value_counts() This looks good, let’s proceed to partitioning the data. When it comes to partitioning data, we have 2 options: Split the sample data into 3 groups: train, validation and test, where train is used to fit the model, validation is used to evaluate fitness of interim models, and test is used to assess final model fitness.Split the sample data into 2 groups: train and test, where train is further split into train and validation set k times using k-fold cross validation, and test is used to assess final model fitness. With k-fold cross validation:First: Train is split into k pieces.Second: Take one piece for validation set to evaluate fitness of interim models after fitting the model to the remaining k-1 pieces.Third: Repeat the second step k-1 times using a different piece for the validation set each time and the remaining for the train set such that each piece of train is used as validation set only once. Split the sample data into 3 groups: train, validation and test, where train is used to fit the model, validation is used to evaluate fitness of interim models, and test is used to assess final model fitness. Split the sample data into 2 groups: train and test, where train is further split into train and validation set k times using k-fold cross validation, and test is used to assess final model fitness. With k-fold cross validation:First: Train is split into k pieces.Second: Take one piece for validation set to evaluate fitness of interim models after fitting the model to the remaining k-1 pieces.Third: Repeat the second step k-1 times using a different piece for the validation set each time and the remaining for the train set such that each piece of train is used as validation set only once. Interim models here refer to the models created during the iterative process of comparing different machine learning classifiers as well as trying different hyperparameters for a given classifier to find the best model. We will be using the second option to partition the sample data. Let’s put aside some test data so that we could check how well the final model generalises on unseen data later: X_train, X_test, y_train, y_test = train_test_split(sample['document'], sample['target'], test_size=0.3, random_state=123)print(f'Train dimensions: {X_train.shape, y_train.shape}')print(f'Test dimensions: {X_test.shape, y_test.shape}')# Check out target distributionprint(y_train.value_counts())print(y_test.value_counts()) We have 1400 documents in train and 600 documents in test dataset. The target is evenly distributed in both train and test dataset. If you are slightly confused about this section on data partitioning, you may want to check this awesome article to learn more. It’s time to preprocess training documents, that is to transform unstructured data to a matrix of numbers. Let’s preprocess the text using an approach called bag-of-word where each text is represented by its words regardless of the order in which they are presented or the embedded grammar with the following steps: TokeniseNormaliseRemove stop wordsCount vectoriseTransform to tf-idf representation Tokenise Normalise Remove stop words Count vectorise Transform to tf-idf representation 🔗 I have provided a detailed explanation on the preprocessing steps including the breakdown of the code chunk below in the first part of the series. These sequential steps are accomplished with the code chunk below: def preprocess_text(text): # Tokenise words while ignoring punctuation tokeniser = RegexpTokenizer(r'\w+') tokens = tokeniser.tokenize(text) # Lowercase and lemmatise lemmatiser = WordNetLemmatizer() lemmas = [lemmatiser.lemmatize(token.lower(), pos='v') for token in tokens] # Remove stop words keywords= [lemma for lemma in lemmas if lemma not in stopwords.words('english')] return keywords# Create an instance of TfidfVectorizervectoriser = TfidfVectorizer(analyzer=preprocess_text)# Fit to the data and transform to feature matrixX_train_tfidf = vectoriser.fit_transform(X_train)X_train_tfidf.shape 🔗 If you are not sure what tf-idf is, I have provided a detailed explanation in the third part of the series. Once we preprocess the text, our training data is now a 1400 x 27676 feature matrix stored in a sparse matrix format. This format provides an efficient storage of the data and speeds up subsequent processes. We have 27676 features that represent the unique words from the training dataset. Now, the training data is ready for modelling! Let’s build a baseline model using Stochastic Gradient Descent Classifier. I have chosen this classifier because it is fast and works well with sparse matrix. Using 5-fold cross validation, let’s fit the model to the data and evaluate it: sgd_clf = SGDClassifier(random_state=123)sgf_clf_scores = cross_val_score(sgd_clf, X_train_tfidf, y_train, cv=5)print(sgf_clf_scores)print("Accuracy: %0.2f (+/- %0.2f)" % (sgf_clf_scores.mean(), sgf_clf_scores.std() * 2)) Given the data is perfectly balanced and we want both labels to be predicted as correctly as possible, we will use accuracy as a metric to evaluate the model fitness. However, accuracy is not always the best measure depending on the distribution of the target and relative misclassification costs of the classes. In which case, other evaluation metrics such as precision, recall or f1 may be more appropriate. The initial performance does not look bad. The baseline model can predict accurately ~83% +/- 3% of the time. Of note, the default metric used is accuracy in cross_val_score hence we don’t need to specify it unless you want to explicitly say so like below: cross_val_score(sgd_clf, X_train_tfidf, y_train, cv=5, scoring='accuracy') Let’s understand the predictions a bit further by looking at confusion matrix: sgf_clf_pred = cross_val_predict(sgd_clf, X_train_tfidf, y_train, cv=5)print(confusion_matrix(y_train, sgf_clf_pred)) The accuracy of predictions is similar for both classes. The purpose of this section is to find the best machine learning algorithm as well as its hyperparameters. Let’s see if we are able to improve the model by tweaking some hyperparameters. We will leave most of the hyperparameters to its sensible default value. With the help of grid search, we will run a model with every combination o the hyperparameters specified below and cross validate the results to get a feel of its accuracy: grid = {'fit_intercept': [True,False], 'early_stopping': [True, False], 'loss' : ['hinge', 'log', 'squared_hinge'], 'penalty' : ['l2', 'l1', 'none']}search = GridSearchCV(estimator=sgd_clf, param_grid=grid, cv=5)search.fit(X_train_tfidf, y_train)search.best_params_ These are the best values for the hyperparameters specified above. Let’s train and validate the model using these values for the selected hyperparameters: grid_sgd_clf_scores = cross_val_score(search.best_estimator_, X_train_tfidf, y_train, cv=5)print(grid_sgd_clf_scores)print("Accuracy: %0.2f (+/- %0.2f)" % (grid_sgd_clf_scores.mean(), grid_sgd_clf_scores.std() * 2)) The model fitness is slightly better compared to baseline (small yay❕). We will choose these hyperparameter combiantion for our final model and stop this section here in the interest of time. However, this section could be extended further by trying different modelling techniques and finding optimal values for the hyperparameters of the model using a grid search. 📌 Exercise: See if you can further improve this model’s accuracy by using different modelling techniques and/or optimising the hyperparameters. Now that we have finalised the model, let’s put the data transformation step as well as the model in a pipeline: pipe = Pipeline([('vectoriser', vectoriser), ('classifier', search.best_estimator_)])pipe.fit(X_train, y_train) In the code shown above, the pipeline first transforms the unstructured data to a feature matrix, then fits the preprocessed data to the model. This is an elegant way of putting together the essential steps in a single pipeline. Let’s assess the predictive power of the model on the test set. Here, we will pass the test data to the pipeline, which will first preprocess the data then make predictions using the previously fitted model: y_test_pred = pipe.predict(X_test)print("Accuracy: %0.2f" % (accuracy_score(y_test, y_test_pred)))print(confusion_matrix(y_test, y_test_pred)) The accuracy of the final model on unseen data is ~85%. If this test data is representative of future data, the predictive power of the model is decent given the effort we have put in so far, don’t you think? Either way, congratulations! You have just built a simple supervised text classification model! 🎓 Would you like to access more content like this? Medium members get unlimited access to any articles on Medium. If you become a member using my referral link, a portion of your membership fee will directly go to support me. Thank you for taking the time to go through this post. I hope that you learned something from reading it. Links to the rest of the posts are collated below:◼️ Part 1: Preprocessing text in Python◼️ Part 2: Difference between lemmatisation and stemming◼️ Part 3: TF-IDF explained◼️ Part 4: Supervised text classification model in Python◼️ Part 5A: Unsupervised topic model in Python (sklearn)◼️ Part 5B: Unsupervised topic model in Python (gensim) Happy modelling! Bye for now 🏃💨 Christopher D. Manning, Prabhakar Raghavan and Hinrich Schütze, Introduction to Information Retrieval, Cambridge University Press, 2008 Bird, Steven, Edward Loper and Ewan Klein, Natural Language Processing with Python. O’Reilly Media Inc, 2009 Jason Brownlee, What is the Difference Between Test and Validation Datasets?, Machine Learning Mastery, 2017
[ { "code": null, "e": 337, "s": 171, "text": "This post will show you a simplified example of building a basic supervised text classification model. If this sounds a little gibberish, let’s see some definitions:" }, { "code": null, "e": 636, "s": 337, "text": "💡 supervised: we know the correct output class for each text in sample data💡 text: input data is in a text format💡 classification model: a model that uses input data to predict output classEach input text is also known as ‘document’ and output is also known as ‘target’ (the term, not the shop! 😄)." }, { "code": null, "e": 947, "s": 636, "text": "Does supervised text classification model sound more meaningful now? Maybe? Among supervised text classification models, we will focus on one particular type in this post. Here, we will build a supervised sentiment classifier as we will be using a sentiment polarity data on movie reviews with a binary target." }, { "code": null, "e": 1154, "s": 947, "text": "This post assumes that you have access to and are familiar with Python including installing packages, defining functions and other basic tasks. If you are new to Python, this is a good place to get started." }, { "code": null, "e": 1270, "s": 1154, "text": "I have used and tested the scripts in Python 3.7.1. Let’s make sure you have the right tools before we get started." }, { "code": null, "e": 1327, "s": 1270, "text": "We will use the following powerful third party packages:" }, { "code": null, "e": 1358, "s": 1327, "text": "pandas: Data analysis library," }, { "code": null, "e": 1402, "s": 1358, "text": "nltk: Natural Language Tool Kit library and" }, { "code": null, "e": 1437, "s": 1402, "text": "sklearn: Machine Learning library." }, { "code": null, "e": 1578, "s": 1437, "text": "The script below can help you download these corpora. If you have already downloaded, running this will notify you that they are up-to-date:" }, { "code": null, "e": 1671, "s": 1578, "text": "import nltknltk.download('stopwords') nltk.download('wordnet')nltk.download('movie_reviews')" }, { "code": null, "e": 1746, "s": 1671, "text": "Firstly, let’s prepare the environment by importing the required packages:" }, { "code": null, "e": 2198, "s": 1746, "text": "import pandas as pdfrom nltk.corpus import movie_reviews, stopwordsfrom nltk.stem import WordNetLemmatizerfrom nltk.tokenize import RegexpTokenizerfrom sklearn.model_selection import train_test_split, cross_val_score, cross_val_predict, GridSearchCVfrom sklearn.feature_extraction.text import TfidfVectorizerfrom sklearn.linear_model import SGDClassifierfrom sklearn.pipeline import Pipelinefrom sklearn.metrics import confusion_matrix, accuracy_score" }, { "code": null, "e": 2299, "s": 2198, "text": "We will transform movie_reviews tagged corpus from nltk to a pandas dataframe with the script below:" }, { "code": null, "e": 2575, "s": 2299, "text": "# Script copied from herereviews = []for fileid in movie_reviews.fileids(): tag, filename = fileid.split('/') reviews.append((tag, movie_reviews.raw(fileid)))sample = pd.DataFrame(reviews, columns=['target', 'document'])print(f'Dimensions: {sample.shape}')sample.head()" }, { "code": null, "e": 2843, "s": 2575, "text": "You will see that the dataframe has 2 columns: a column for the targets, the polarity sentiment, and a column for the reviews (i.e. documents) for 2000 reviews. Each review is either tagged as positive or negative review. Let’s check the counts of the target classes:" }, { "code": null, "e": 2875, "s": 2843, "text": "sample[‘target’].value_counts()" }, { "code": null, "e": 2997, "s": 2875, "text": "Each class (i.e. ‘pos’, ‘neg’) has 1000 records each, perfectly balanced. Let’s ensure that the classes are binary coded:" }, { "code": null, "e": 3087, "s": 2997, "text": "sample['target'] = np.where(sample['target']=='pos', 1, 0)sample['target'].value_counts()" }, { "code": null, "e": 3144, "s": 3087, "text": "This looks good, let’s proceed to partitioning the data." }, { "code": null, "e": 3199, "s": 3144, "text": "When it comes to partitioning data, we have 2 options:" }, { "code": null, "e": 4003, "s": 3199, "text": "Split the sample data into 3 groups: train, validation and test, where train is used to fit the model, validation is used to evaluate fitness of interim models, and test is used to assess final model fitness.Split the sample data into 2 groups: train and test, where train is further split into train and validation set k times using k-fold cross validation, and test is used to assess final model fitness. With k-fold cross validation:First: Train is split into k pieces.Second: Take one piece for validation set to evaluate fitness of interim models after fitting the model to the remaining k-1 pieces.Third: Repeat the second step k-1 times using a different piece for the validation set each time and the remaining for the train set such that each piece of train is used as validation set only once." }, { "code": null, "e": 4212, "s": 4003, "text": "Split the sample data into 3 groups: train, validation and test, where train is used to fit the model, validation is used to evaluate fitness of interim models, and test is used to assess final model fitness." }, { "code": null, "e": 4808, "s": 4212, "text": "Split the sample data into 2 groups: train and test, where train is further split into train and validation set k times using k-fold cross validation, and test is used to assess final model fitness. With k-fold cross validation:First: Train is split into k pieces.Second: Take one piece for validation set to evaluate fitness of interim models after fitting the model to the remaining k-1 pieces.Third: Repeat the second step k-1 times using a different piece for the validation set each time and the remaining for the train set such that each piece of train is used as validation set only once." }, { "code": null, "e": 5028, "s": 4808, "text": "Interim models here refer to the models created during the iterative process of comparing different machine learning classifiers as well as trying different hyperparameters for a given classifier to find the best model." }, { "code": null, "e": 5206, "s": 5028, "text": "We will be using the second option to partition the sample data. Let’s put aside some test data so that we could check how well the final model generalises on unseen data later:" }, { "code": null, "e": 5530, "s": 5206, "text": "X_train, X_test, y_train, y_test = train_test_split(sample['document'], sample['target'], test_size=0.3, random_state=123)print(f'Train dimensions: {X_train.shape, y_train.shape}')print(f'Test dimensions: {X_test.shape, y_test.shape}')# Check out target distributionprint(y_train.value_counts())print(y_test.value_counts())" }, { "code": null, "e": 5662, "s": 5530, "text": "We have 1400 documents in train and 600 documents in test dataset. The target is evenly distributed in both train and test dataset." }, { "code": null, "e": 5790, "s": 5662, "text": "If you are slightly confused about this section on data partitioning, you may want to check this awesome article to learn more." }, { "code": null, "e": 6106, "s": 5790, "text": "It’s time to preprocess training documents, that is to transform unstructured data to a matrix of numbers. Let’s preprocess the text using an approach called bag-of-word where each text is represented by its words regardless of the order in which they are presented or the embedded grammar with the following steps:" }, { "code": null, "e": 6190, "s": 6106, "text": "TokeniseNormaliseRemove stop wordsCount vectoriseTransform to tf-idf representation" }, { "code": null, "e": 6199, "s": 6190, "text": "Tokenise" }, { "code": null, "e": 6209, "s": 6199, "text": "Normalise" }, { "code": null, "e": 6227, "s": 6209, "text": "Remove stop words" }, { "code": null, "e": 6243, "s": 6227, "text": "Count vectorise" }, { "code": null, "e": 6278, "s": 6243, "text": "Transform to tf-idf representation" }, { "code": null, "e": 6427, "s": 6278, "text": "🔗 I have provided a detailed explanation on the preprocessing steps including the breakdown of the code chunk below in the first part of the series." }, { "code": null, "e": 6494, "s": 6427, "text": "These sequential steps are accomplished with the code chunk below:" }, { "code": null, "e": 7133, "s": 6494, "text": "def preprocess_text(text): # Tokenise words while ignoring punctuation tokeniser = RegexpTokenizer(r'\\w+') tokens = tokeniser.tokenize(text) # Lowercase and lemmatise lemmatiser = WordNetLemmatizer() lemmas = [lemmatiser.lemmatize(token.lower(), pos='v') for token in tokens] # Remove stop words keywords= [lemma for lemma in lemmas if lemma not in stopwords.words('english')] return keywords# Create an instance of TfidfVectorizervectoriser = TfidfVectorizer(analyzer=preprocess_text)# Fit to the data and transform to feature matrixX_train_tfidf = vectoriser.fit_transform(X_train)X_train_tfidf.shape" }, { "code": null, "e": 7243, "s": 7133, "text": "🔗 If you are not sure what tf-idf is, I have provided a detailed explanation in the third part of the series." }, { "code": null, "e": 7580, "s": 7243, "text": "Once we preprocess the text, our training data is now a 1400 x 27676 feature matrix stored in a sparse matrix format. This format provides an efficient storage of the data and speeds up subsequent processes. We have 27676 features that represent the unique words from the training dataset. Now, the training data is ready for modelling!" }, { "code": null, "e": 7819, "s": 7580, "text": "Let’s build a baseline model using Stochastic Gradient Descent Classifier. I have chosen this classifier because it is fast and works well with sparse matrix. Using 5-fold cross validation, let’s fit the model to the data and evaluate it:" }, { "code": null, "e": 8041, "s": 7819, "text": "sgd_clf = SGDClassifier(random_state=123)sgf_clf_scores = cross_val_score(sgd_clf, X_train_tfidf, y_train, cv=5)print(sgf_clf_scores)print(\"Accuracy: %0.2f (+/- %0.2f)\" % (sgf_clf_scores.mean(), sgf_clf_scores.std() * 2))" }, { "code": null, "e": 8451, "s": 8041, "text": "Given the data is perfectly balanced and we want both labels to be predicted as correctly as possible, we will use accuracy as a metric to evaluate the model fitness. However, accuracy is not always the best measure depending on the distribution of the target and relative misclassification costs of the classes. In which case, other evaluation metrics such as precision, recall or f1 may be more appropriate." }, { "code": null, "e": 8561, "s": 8451, "text": "The initial performance does not look bad. The baseline model can predict accurately ~83% +/- 3% of the time." }, { "code": null, "e": 8708, "s": 8561, "text": "Of note, the default metric used is accuracy in cross_val_score hence we don’t need to specify it unless you want to explicitly say so like below:" }, { "code": null, "e": 8783, "s": 8708, "text": "cross_val_score(sgd_clf, X_train_tfidf, y_train, cv=5, scoring='accuracy')" }, { "code": null, "e": 8862, "s": 8783, "text": "Let’s understand the predictions a bit further by looking at confusion matrix:" }, { "code": null, "e": 8980, "s": 8862, "text": "sgf_clf_pred = cross_val_predict(sgd_clf, X_train_tfidf, y_train, cv=5)print(confusion_matrix(y_train, sgf_clf_pred))" }, { "code": null, "e": 9037, "s": 8980, "text": "The accuracy of predictions is similar for both classes." }, { "code": null, "e": 9470, "s": 9037, "text": "The purpose of this section is to find the best machine learning algorithm as well as its hyperparameters. Let’s see if we are able to improve the model by tweaking some hyperparameters. We will leave most of the hyperparameters to its sensible default value. With the help of grid search, we will run a model with every combination o the hyperparameters specified below and cross validate the results to get a feel of its accuracy:" }, { "code": null, "e": 9757, "s": 9470, "text": "grid = {'fit_intercept': [True,False], 'early_stopping': [True, False], 'loss' : ['hinge', 'log', 'squared_hinge'], 'penalty' : ['l2', 'l1', 'none']}search = GridSearchCV(estimator=sgd_clf, param_grid=grid, cv=5)search.fit(X_train_tfidf, y_train)search.best_params_" }, { "code": null, "e": 9912, "s": 9757, "text": "These are the best values for the hyperparameters specified above. Let’s train and validate the model using these values for the selected hyperparameters:" }, { "code": null, "e": 10128, "s": 9912, "text": "grid_sgd_clf_scores = cross_val_score(search.best_estimator_, X_train_tfidf, y_train, cv=5)print(grid_sgd_clf_scores)print(\"Accuracy: %0.2f (+/- %0.2f)\" % (grid_sgd_clf_scores.mean(), grid_sgd_clf_scores.std() * 2))" }, { "code": null, "e": 10200, "s": 10128, "text": "The model fitness is slightly better compared to baseline (small yay❕)." }, { "code": null, "e": 10494, "s": 10200, "text": "We will choose these hyperparameter combiantion for our final model and stop this section here in the interest of time. However, this section could be extended further by trying different modelling techniques and finding optimal values for the hyperparameters of the model using a grid search." }, { "code": null, "e": 10638, "s": 10494, "text": "📌 Exercise: See if you can further improve this model’s accuracy by using different modelling techniques and/or optimising the hyperparameters." }, { "code": null, "e": 10751, "s": 10638, "text": "Now that we have finalised the model, let’s put the data transformation step as well as the model in a pipeline:" }, { "code": null, "e": 10879, "s": 10751, "text": "pipe = Pipeline([('vectoriser', vectoriser), ('classifier', search.best_estimator_)])pipe.fit(X_train, y_train)" }, { "code": null, "e": 11108, "s": 10879, "text": "In the code shown above, the pipeline first transforms the unstructured data to a feature matrix, then fits the preprocessed data to the model. This is an elegant way of putting together the essential steps in a single pipeline." }, { "code": null, "e": 11316, "s": 11108, "text": "Let’s assess the predictive power of the model on the test set. Here, we will pass the test data to the pipeline, which will first preprocess the data then make predictions using the previously fitted model:" }, { "code": null, "e": 11459, "s": 11316, "text": "y_test_pred = pipe.predict(X_test)print(\"Accuracy: %0.2f\" % (accuracy_score(y_test, y_test_pred)))print(confusion_matrix(y_test, y_test_pred))" }, { "code": null, "e": 11766, "s": 11459, "text": "The accuracy of the final model on unseen data is ~85%. If this test data is representative of future data, the predictive power of the model is decent given the effort we have put in so far, don’t you think? Either way, congratulations! You have just built a simple supervised text classification model! 🎓" }, { "code": null, "e": 11990, "s": 11766, "text": "Would you like to access more content like this? Medium members get unlimited access to any articles on Medium. If you become a member using my referral link, a portion of your membership fee will directly go to support me." }, { "code": null, "e": 12437, "s": 11990, "text": "Thank you for taking the time to go through this post. I hope that you learned something from reading it. Links to the rest of the posts are collated below:◼️ Part 1: Preprocessing text in Python◼️ Part 2: Difference between lemmatisation and stemming◼️ Part 3: TF-IDF explained◼️ Part 4: Supervised text classification model in Python◼️ Part 5A: Unsupervised topic model in Python (sklearn)◼️ Part 5B: Unsupervised topic model in Python (gensim)" }, { "code": null, "e": 12469, "s": 12437, "text": "Happy modelling! Bye for now 🏃💨" }, { "code": null, "e": 12606, "s": 12469, "text": "Christopher D. Manning, Prabhakar Raghavan and Hinrich Schütze, Introduction to Information Retrieval, Cambridge University Press, 2008" }, { "code": null, "e": 12715, "s": 12606, "text": "Bird, Steven, Edward Loper and Ewan Klein, Natural Language Processing with Python. O’Reilly Media Inc, 2009" } ]
0/1 Knapsack using Branch and Bound in C++
The idea is to implement the fact that the Greedy approach provides the best solution for Fractional Knapsack problem. To check whether a particular node can give us a better solution or not, we calculate the optimal solution (through the node) implementing Greedy approach. If the solution calculated by Greedy approach itself is more than the best so far, then we can’t obtain a better solution through the node. Complete Algorithm is given below − Sort all items according to decreasing order of ratio of value per unit weight so that an upper bound can becalculated implementing Greedy Approach. Sort all items according to decreasing order of ratio of value per unit weight so that an upper bound can becalculated implementing Greedy Approach. Initialize maximum profit, such as maxProfit = 0 Initialize maximum profit, such as maxProfit = 0 An empty queue, Q, is created. An empty queue, Q, is created. A dummy node of decision tree is created and insert or enqueue it to Q. Profit and weight of dummy node be 0. A dummy node of decision tree is created and insert or enqueue it to Q. Profit and weight of dummy node be 0. Do following while Q is not vacant or empty.An item from Q is created. Let the extracted item be u.Calculate profit of next level node. If the profit is higher than maxProfit, then modify maxProfit.Calculate bound of next level node. If bound is higher than maxProfit, then add next level node to Q.Consider the case when next level node is not treated or considered as part of solution and add a node to queue with level as next, but weight and profit without treating or considering next level nodes. Do following while Q is not vacant or empty. An item from Q is created. Let the extracted item be u. An item from Q is created. Let the extracted item be u. Calculate profit of next level node. If the profit is higher than maxProfit, then modify maxProfit. Calculate profit of next level node. If the profit is higher than maxProfit, then modify maxProfit. Calculate bound of next level node. If bound is higher than maxProfit, then add next level node to Q. Calculate bound of next level node. If bound is higher than maxProfit, then add next level node to Q. Consider the case when next level node is not treated or considered as part of solution and add a node to queue with level as next, but weight and profit without treating or considering next level nodes. Consider the case when next level node is not treated or considered as part of solution and add a node to queue with level as next, but weight and profit without treating or considering next level nodes. Illustrationis given below − // First thing in every pair is treated as weight of item // and second thing is treated as value of item Item arr1[] = {{2, 40}, {3.14, 50}, {1.98, 100}, {5, 95}, {3, 30}}; Knapsack Capacity W1 = 10 The maximum possible profit = 235
[ { "code": null, "e": 1181, "s": 1062, "text": "The idea is to implement the fact that the Greedy approach provides the best solution for Fractional Knapsack problem." }, { "code": null, "e": 1477, "s": 1181, "text": "To check whether a particular node can give us a better solution or not, we calculate the optimal solution (through the node) implementing Greedy approach. If the solution calculated by Greedy approach itself is more than the best so far, then we can’t obtain a better solution through the node." }, { "code": null, "e": 1513, "s": 1477, "text": "Complete Algorithm is given below −" }, { "code": null, "e": 1662, "s": 1513, "text": "Sort all items according to decreasing order of ratio of value per unit weight so that an upper bound can becalculated implementing Greedy Approach." }, { "code": null, "e": 1811, "s": 1662, "text": "Sort all items according to decreasing order of ratio of value per unit weight so that an upper bound can becalculated implementing Greedy Approach." }, { "code": null, "e": 1860, "s": 1811, "text": "Initialize maximum profit, such as maxProfit = 0" }, { "code": null, "e": 1909, "s": 1860, "text": "Initialize maximum profit, such as maxProfit = 0" }, { "code": null, "e": 1940, "s": 1909, "text": "An empty queue, Q, is created." }, { "code": null, "e": 1971, "s": 1940, "text": "An empty queue, Q, is created." }, { "code": null, "e": 2081, "s": 1971, "text": "A dummy node of decision tree is created and insert or enqueue it to Q. Profit and weight of dummy node be 0." }, { "code": null, "e": 2191, "s": 2081, "text": "A dummy node of decision tree is created and insert or enqueue it to Q. Profit and weight of dummy node be 0." }, { "code": null, "e": 2694, "s": 2191, "text": "Do following while Q is not vacant or empty.An item from Q is created. Let the extracted item be u.Calculate profit of next level node. If the profit is higher than maxProfit, then modify maxProfit.Calculate bound of next level node. If bound is higher than maxProfit, then add next level node to Q.Consider the case when next level node is not treated or considered as part of solution and add a node to queue with level as next, but weight and profit without treating or considering next level nodes." }, { "code": null, "e": 2739, "s": 2694, "text": "Do following while Q is not vacant or empty." }, { "code": null, "e": 2795, "s": 2739, "text": "An item from Q is created. Let the extracted item be u." }, { "code": null, "e": 2851, "s": 2795, "text": "An item from Q is created. Let the extracted item be u." }, { "code": null, "e": 2951, "s": 2851, "text": "Calculate profit of next level node. If the profit is higher than maxProfit, then modify maxProfit." }, { "code": null, "e": 3051, "s": 2951, "text": "Calculate profit of next level node. If the profit is higher than maxProfit, then modify maxProfit." }, { "code": null, "e": 3153, "s": 3051, "text": "Calculate bound of next level node. If bound is higher than maxProfit, then add next level node to Q." }, { "code": null, "e": 3255, "s": 3153, "text": "Calculate bound of next level node. If bound is higher than maxProfit, then add next level node to Q." }, { "code": null, "e": 3459, "s": 3255, "text": "Consider the case when next level node is not treated or considered as part of solution and add a node to queue with level as next, but weight and profit without treating or considering next level nodes." }, { "code": null, "e": 3663, "s": 3459, "text": "Consider the case when next level node is not treated or considered as part of solution and add a node to queue with level as next, but weight and profit without treating or considering next level nodes." }, { "code": null, "e": 3692, "s": 3663, "text": "Illustrationis given below −" }, { "code": null, "e": 3893, "s": 3692, "text": "// First thing in every pair is treated as weight of item\n// and second thing is treated as value of item\nItem arr1[] = {{2, 40}, {3.14, 50}, {1.98, 100},\n{5, 95}, {3, 30}};\nKnapsack Capacity W1 = 10\n" }, { "code": null, "e": 3927, "s": 3893, "text": "The maximum possible profit = 235" } ]
Numba: JIT Compilation, But For Python | by Emmett Boudreau | Towards Data Science
Statistical computing has always been a very difficult discipline for programmers and computer-scientists to provide for. There are certain attributes and characteristics that programmers look for in not only a statistical programming language, but also a general-purpose programming language. The rise of statistical computing with the popularity of machine-learning and data science applications has also exacerbated these critical issues in the development of the “ perfect language.” Going back ten years, nobody could have anticipated what the rise of machine-learning in Python would have been like. Most scientists were using the R programming language for statistical analysis and things of that nature. MATLAB is of course also a very popular choice for the statistical computing world, as well as Scala. Python has recently become very popular in this regard for its strong statistical capabilities Of course, Python is interpreted by C. This means that Python isn’t as fast as many as its competitors, and not as suitable for big data solutions. Python by nature is not a language with a compiler built to satisfy many of the needs of modern scientific computing. While Python is a great application in for most statistical applications, the primary factor in Python’s short-comings is usually its speed when working with large amounts of data and recursively training machine-learning models. If Python has issues with processing large amounts of data, and is by nature an interpreted, high-level language, then why is it that many scientists are enjoying the spoil of the language today? The answer is quite simple, at this current time, Python is the best solution available. While Python is relatively slow compared to many other languages, it is also very high-level when compared with other languages, and has only been getting faster and more optimized in the past couple of years. To add to that beauty, Python has one of the strongest ecosystems for statistical computing available today. Most of these packages are written in C, as well, which can make Python often be a simple interface to very fast code. Regardless of how great the ecosystem is, however, it cannot help with processing enormous levels of data and writing Pythonic algorithms to clean and edit data. Unless you have been living under a programming turtle shell, you might be familiar with — or at least heard of a compiler concept called JIT. JIT, or Just In Time compilation is a compiler feature that allows a language to be interpreted and compiled during runtime, rather than at execution. This means that rather than preparing all of the code to work, deciding what the code is going to do, and then doing it, a JIT compiler will be compiling the language as it is executing the logic prior to the code it is compiling. The benefit to such a compiler is of course speed. Less time spent on initial compilation means that the code can be interpreted a lot faster. For an analogy, pretend that you have a list of things cooking for dinner. Rather than cooking all of the things individually, you could take a multi-tasking approach where multiple things are being worked on at the same time. The Numba JIT compiler, similar to the Julia JIT compiler, uses the standard LLVM compiler library. Although it does have some short-comings in that regard, in that the focus of LLVM isn’t necessarily JIT, it does mean that the compiler is incredibly fast and precise. Numba-compiled Pythonic algorithms can approach speeds that are often seen in lower-level languages like C. This might sound complicated, and it is — but that doesn’t mean that Numba is hard to use. As a matter of a fact, Numba is incredibly easy to use! In order to try it out, you are of course going to need to add it with Python’s package manager, PIP. sudo pip3 install numba After installing Numba, you can access it via the jit function: from numba import jitimport random@jit(nopython=True)def monte_carlo_pi(nsamples): acc = 0 for i in range(nsamples): x = random.random() y = random.random() if (x ** 2 + y ** 2) < 1.0: acc += 1 return 4.0 * acc / nsamples For most code, Numba does an incredible job at optimizing Python code. As Julia developers discussed at JuliaCon, however, in its current version, Numba still has a long way to go and presents [problems with certain code. Some issues can’t be fixed with a simple Python call, and although Numba has done a great job at creating an optimized compiler for Python that can be imported easily, there are certainly improvements to be made. Regardless as to whether or not Python will always be the go-to programming language for scientific purposes and statistical computing, it is clear that Python is certainly that for now. While Python isn’t the quickest programming language out there and has its fair share of minor issues with scientific computing, it is still a great choice for those wishing to do statistics or machine-learning. This is mostly due to its ecosystem and overall popularity. Fortunately, many of Python’s flaws are being directly targeted by talented and driven developers. Over time, there is a pretty good chance that the technology will be so far along that many of these issues might not even be felt anymore when using Python for Data Science. One of Python’s biggest problems is its speed. Numba is one of a series of awesome tools that help counter this problem and bring Python up to snuff to counter other statistical languages, especially newer languages like Julia. What is exciting about Numba is how simple it is to use, like a light-switch that makes your code run faster. This, in turn, can be used to breathe new life into applications that otherwise might not even be able to run.
[ { "code": null, "e": 660, "s": 172, "text": "Statistical computing has always been a very difficult discipline for programmers and computer-scientists to provide for. There are certain attributes and characteristics that programmers look for in not only a statistical programming language, but also a general-purpose programming language. The rise of statistical computing with the popularity of machine-learning and data science applications has also exacerbated these critical issues in the development of the “ perfect language.”" }, { "code": null, "e": 1081, "s": 660, "text": "Going back ten years, nobody could have anticipated what the rise of machine-learning in Python would have been like. Most scientists were using the R programming language for statistical analysis and things of that nature. MATLAB is of course also a very popular choice for the statistical computing world, as well as Scala. Python has recently become very popular in this regard for its strong statistical capabilities" }, { "code": null, "e": 1577, "s": 1081, "text": "Of course, Python is interpreted by C. This means that Python isn’t as fast as many as its competitors, and not as suitable for big data solutions. Python by nature is not a language with a compiler built to satisfy many of the needs of modern scientific computing. While Python is a great application in for most statistical applications, the primary factor in Python’s short-comings is usually its speed when working with large amounts of data and recursively training machine-learning models." }, { "code": null, "e": 2072, "s": 1577, "text": "If Python has issues with processing large amounts of data, and is by nature an interpreted, high-level language, then why is it that many scientists are enjoying the spoil of the language today? The answer is quite simple, at this current time, Python is the best solution available. While Python is relatively slow compared to many other languages, it is also very high-level when compared with other languages, and has only been getting faster and more optimized in the past couple of years." }, { "code": null, "e": 2462, "s": 2072, "text": "To add to that beauty, Python has one of the strongest ecosystems for statistical computing available today. Most of these packages are written in C, as well, which can make Python often be a simple interface to very fast code. Regardless of how great the ecosystem is, however, it cannot help with processing enormous levels of data and writing Pythonic algorithms to clean and edit data." }, { "code": null, "e": 2987, "s": 2462, "text": "Unless you have been living under a programming turtle shell, you might be familiar with — or at least heard of a compiler concept called JIT. JIT, or Just In Time compilation is a compiler feature that allows a language to be interpreted and compiled during runtime, rather than at execution. This means that rather than preparing all of the code to work, deciding what the code is going to do, and then doing it, a JIT compiler will be compiling the language as it is executing the logic prior to the code it is compiling." }, { "code": null, "e": 3357, "s": 2987, "text": "The benefit to such a compiler is of course speed. Less time spent on initial compilation means that the code can be interpreted a lot faster. For an analogy, pretend that you have a list of things cooking for dinner. Rather than cooking all of the things individually, you could take a multi-tasking approach where multiple things are being worked on at the same time." }, { "code": null, "e": 3734, "s": 3357, "text": "The Numba JIT compiler, similar to the Julia JIT compiler, uses the standard LLVM compiler library. Although it does have some short-comings in that regard, in that the focus of LLVM isn’t necessarily JIT, it does mean that the compiler is incredibly fast and precise. Numba-compiled Pythonic algorithms can approach speeds that are often seen in lower-level languages like C." }, { "code": null, "e": 3983, "s": 3734, "text": "This might sound complicated, and it is — but that doesn’t mean that Numba is hard to use. As a matter of a fact, Numba is incredibly easy to use! In order to try it out, you are of course going to need to add it with Python’s package manager, PIP." }, { "code": null, "e": 4007, "s": 3983, "text": "sudo pip3 install numba" }, { "code": null, "e": 4071, "s": 4007, "text": "After installing Numba, you can access it via the jit function:" }, { "code": null, "e": 4334, "s": 4071, "text": "from numba import jitimport random@jit(nopython=True)def monte_carlo_pi(nsamples): acc = 0 for i in range(nsamples): x = random.random() y = random.random() if (x ** 2 + y ** 2) < 1.0: acc += 1 return 4.0 * acc / nsamples" }, { "code": null, "e": 4769, "s": 4334, "text": "For most code, Numba does an incredible job at optimizing Python code. As Julia developers discussed at JuliaCon, however, in its current version, Numba still has a long way to go and presents [problems with certain code. Some issues can’t be fixed with a simple Python call, and although Numba has done a great job at creating an optimized compiler for Python that can be imported easily, there are certainly improvements to be made." }, { "code": null, "e": 5228, "s": 4769, "text": "Regardless as to whether or not Python will always be the go-to programming language for scientific purposes and statistical computing, it is clear that Python is certainly that for now. While Python isn’t the quickest programming language out there and has its fair share of minor issues with scientific computing, it is still a great choice for those wishing to do statistics or machine-learning. This is mostly due to its ecosystem and overall popularity." }, { "code": null, "e": 5502, "s": 5228, "text": "Fortunately, many of Python’s flaws are being directly targeted by talented and driven developers. Over time, there is a pretty good chance that the technology will be so far along that many of these issues might not even be felt anymore when using Python for Data Science." } ]
Javascript Program for Find k pairs with smallest sums in two arrays - GeeksforGeeks
14 Feb, 2022 Given two integer arrays arr1[] and arr2[] sorted in ascending order and an integer k. Find k pairs with smallest sums such that one element of a pair belongs to arr1[] and other element belongs to arr2[]Examples: Input : arr1[] = {1, 7, 11} arr2[] = {2, 4, 6} k = 3 Output : [1, 2], [1, 4], [1, 6] Explanation: The first 3 pairs are returned from the sequence [1, 2], [1, 4], [1, 6], [7, 2], [7, 4], [11, 2], [7, 6], [11, 4], [11, 6] Method 1 (Simple) Find all pairs and store their sums. Time complexity of this step is O(n1 * n2) where n1 and n2 are sizes of input arrays.Then sort pairs according to sum. Time complexity of this step is O(n1 * n2 * log (n1 * n2)) Find all pairs and store their sums. Time complexity of this step is O(n1 * n2) where n1 and n2 are sizes of input arrays. Then sort pairs according to sum. Time complexity of this step is O(n1 * n2 * log (n1 * n2)) Overall Time Complexity : O(n1 * n2 * log (n1 * n2))Method 2 (Efficient): We one by one find k smallest sum pairs, starting from least sum pair. The idea is to keep track of all elements of arr2[] which have been already considered for every element arr1[i1] so that in an iteration we only consider next element. For this purpose, we use an index array index2[] to track the indexes of next elements in the other array. It simply means that which element of second array to be added with the element of first array in each and every iteration. We increment value in index array for the element that forms next minimum value pair. Javascript <script>// javascript program to prints first k pairs with least sum from two// arrays.// Function to find k pairs with least sum such// that one element of a pair is from arr1[] and// other element is from arr2[]function kSmallestPair(arr1,n1,arr2,n2,k){ if (k > n1*n2) { document.write("k pairs don't exist"); return ; } // Stores current index in arr2[] for // every element of arr1[]. Initially // all values are considered 0. // Here current index is the index before // which all elements are considered as // part of output. let index2 = new Array(n1); index2.fill(0); while (k > 0) { // Initialize current pair sum as infinite let min_sum = Number.MAX_VALUE; let min_index = 0; // To pick next pair, traverse for all elements // of arr1[], for every element, find corresponding // current element in arr2[] and pick minimum of // all formed pairs. for (let i1 = 0; i1 < n1; i1++) { // Check if current element of arr1[] plus // element of array2 to be used gives minimum // sum if (index2[i1] < n2 && arr1[i1] + arr2[index2[i1]] < min_sum) { // Update index that gives minimum min_index = i1; // update minimum sum min_sum = arr1[i1] + arr2[index2[i1]]; } } document.write("(" + arr1[min_index] + ", " + arr2[index2[min_index]] + ") "); index2[min_index]++; k--; }} let arr1 = [1, 3, 11]; let n1 = arr1.length; let arr2 = [2, 4, 8]; let n2 = arr2.length; let k = 4; kSmallestPair( arr1, n1, arr2, n2, k); </script> (1, 2) (1, 4) (3, 2) (3, 4) Time Complexity : O(k*n1)Please refer complete article on Find k pairs with smallest sums in two arrays for more details! arorakashish0911 Order-Statistics Arrays JavaScript Arrays Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Next Greater Element Window Sliding Technique Count pairs with given sum Program to find sum of elements in a given array Reversal algorithm for array rotation Difference between var, let and const keywords in JavaScript Convert a string to an integer in JavaScript Differences between Functional Components and Class Components in React How to calculate the number of days between two dates in javascript? File uploading in React.js
[ { "code": null, "e": 24405, "s": 24377, "text": "\n14 Feb, 2022" }, { "code": null, "e": 24620, "s": 24405, "text": "Given two integer arrays arr1[] and arr2[] sorted in ascending order and an integer k. Find k pairs with smallest sums such that one element of a pair belongs to arr1[] and other element belongs to arr2[]Examples: " }, { "code": null, "e": 24881, "s": 24620, "text": "Input : arr1[] = {1, 7, 11}\n arr2[] = {2, 4, 6}\n k = 3\nOutput : [1, 2],\n [1, 4],\n [1, 6]\nExplanation: The first 3 pairs are returned \nfrom the sequence [1, 2], [1, 4], [1, 6], \n[7, 2], [7, 4], [11, 2], [7, 6], [11, 4], \n[11, 6]" }, { "code": null, "e": 24901, "s": 24881, "text": "Method 1 (Simple) " }, { "code": null, "e": 25116, "s": 24901, "text": "Find all pairs and store their sums. Time complexity of this step is O(n1 * n2) where n1 and n2 are sizes of input arrays.Then sort pairs according to sum. Time complexity of this step is O(n1 * n2 * log (n1 * n2))" }, { "code": null, "e": 25239, "s": 25116, "text": "Find all pairs and store their sums. Time complexity of this step is O(n1 * n2) where n1 and n2 are sizes of input arrays." }, { "code": null, "e": 25332, "s": 25239, "text": "Then sort pairs according to sum. Time complexity of this step is O(n1 * n2 * log (n1 * n2))" }, { "code": null, "e": 25965, "s": 25332, "text": "Overall Time Complexity : O(n1 * n2 * log (n1 * n2))Method 2 (Efficient): We one by one find k smallest sum pairs, starting from least sum pair. The idea is to keep track of all elements of arr2[] which have been already considered for every element arr1[i1] so that in an iteration we only consider next element. For this purpose, we use an index array index2[] to track the indexes of next elements in the other array. It simply means that which element of second array to be added with the element of first array in each and every iteration. We increment value in index array for the element that forms next minimum value pair. " }, { "code": null, "e": 25976, "s": 25965, "text": "Javascript" }, { "code": "<script>// javascript program to prints first k pairs with least sum from two// arrays.// Function to find k pairs with least sum such// that one element of a pair is from arr1[] and// other element is from arr2[]function kSmallestPair(arr1,n1,arr2,n2,k){ if (k > n1*n2) { document.write(\"k pairs don't exist\"); return ; } // Stores current index in arr2[] for // every element of arr1[]. Initially // all values are considered 0. // Here current index is the index before // which all elements are considered as // part of output. let index2 = new Array(n1); index2.fill(0); while (k > 0) { // Initialize current pair sum as infinite let min_sum = Number.MAX_VALUE; let min_index = 0; // To pick next pair, traverse for all elements // of arr1[], for every element, find corresponding // current element in arr2[] and pick minimum of // all formed pairs. for (let i1 = 0; i1 < n1; i1++) { // Check if current element of arr1[] plus // element of array2 to be used gives minimum // sum if (index2[i1] < n2 && arr1[i1] + arr2[index2[i1]] < min_sum) { // Update index that gives minimum min_index = i1; // update minimum sum min_sum = arr1[i1] + arr2[index2[i1]]; } } document.write(\"(\" + arr1[min_index] + \", \" + arr2[index2[min_index]] + \") \"); index2[min_index]++; k--; }} let arr1 = [1, 3, 11]; let n1 = arr1.length; let arr2 = [2, 4, 8]; let n2 = arr2.length; let k = 4; kSmallestPair( arr1, n1, arr2, n2, k); </script>", "e": 27732, "s": 25976, "text": null }, { "code": null, "e": 27764, "s": 27735, "text": "(1, 2) (1, 4) (3, 2) (3, 4) " }, { "code": null, "e": 27889, "s": 27766, "text": "Time Complexity : O(k*n1)Please refer complete article on Find k pairs with smallest sums in two arrays for more details! " }, { "code": null, "e": 27906, "s": 27889, "text": "arorakashish0911" }, { "code": null, "e": 27923, "s": 27906, "text": "Order-Statistics" }, { "code": null, "e": 27930, "s": 27923, "text": "Arrays" }, { "code": null, "e": 27941, "s": 27930, "text": "JavaScript" }, { "code": null, "e": 27948, "s": 27941, "text": "Arrays" }, { "code": null, "e": 28046, "s": 27948, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28055, "s": 28046, "text": "Comments" }, { "code": null, "e": 28068, "s": 28055, "text": "Old Comments" }, { "code": null, "e": 28089, "s": 28068, "text": "Next Greater Element" }, { "code": null, "e": 28114, "s": 28089, "text": "Window Sliding Technique" }, { "code": null, "e": 28141, "s": 28114, "text": "Count pairs with given sum" }, { "code": null, "e": 28190, "s": 28141, "text": "Program to find sum of elements in a given array" }, { "code": null, "e": 28228, "s": 28190, "text": "Reversal algorithm for array rotation" }, { "code": null, "e": 28289, "s": 28228, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 28334, "s": 28289, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 28406, "s": 28334, "text": "Differences between Functional Components and Class Components in React" }, { "code": null, "e": 28475, "s": 28406, "text": "How to calculate the number of days between two dates in javascript?" } ]
C Program for efficiently print all prime factors of a given number?
In this section, we will see how we can get all the prime factors of a number in an efficient way. There is a number say n = 1092, we have to get all prime factors of this. The prime factors of 1092 are 2, 2, 3, 7, 13. To solve this problem, we have to follow this rule − When the number is divisible by 2, then print 2, and divide the number by 2 repeatedly. When the number is divisible by 2, then print 2, and divide the number by 2 repeatedly. Now the number must be odd. Now starting from 3 to square root of the number, if the number is divisible by current value, then print, and change the number by divide it with the current number then continue. Now the number must be odd. Now starting from 3 to square root of the number, if the number is divisible by current value, then print, and change the number by divide it with the current number then continue. Let us see the algorithm to get a better idea. begin while n is divisible by 2, do print 2 n := n / 2 done for i := 3 to √n, increase i by 2, do while n is divisible by i, do print i n := n / i done done if n > 2, then print n end if end #include<stdio.h> #include<math.h> void primeFactors(int n) { int i; while(n % 2 == 0) { printf("%d, ", 2); n = n/2; //reduce n by dividing this by 2 } for(i = 3; i <= sqrt(n); i=i+2){ //i will increase by 2, to get only odd numbers while(n % i == 0) { printf("%d, ", i); n = n/i; } } if(n > 2) { printf("%d, ", n); } } main() { int n; printf("Enter a number: "); scanf("%d", &n); primeFactors(n); } Enter a number: 24024 2, 2, 2, 3, 7, 11, 13,
[ { "code": null, "e": 1334, "s": 1062, "text": "In this section, we will see how we can get all the prime factors of a number in an efficient way. There is a number say n = 1092, we have to get all prime factors of this. The prime factors of 1092 are 2, 2, 3, 7, 13. To solve this problem, we have to follow this rule −" }, { "code": null, "e": 1422, "s": 1334, "text": "When the number is divisible by 2, then print 2, and divide the number by 2 repeatedly." }, { "code": null, "e": 1510, "s": 1422, "text": "When the number is divisible by 2, then print 2, and divide the number by 2 repeatedly." }, { "code": null, "e": 1719, "s": 1510, "text": "Now the number must be odd. Now starting from 3 to square root of the number, if the number is divisible by current value, then print, and change the number by divide it with the current number then continue." }, { "code": null, "e": 1928, "s": 1719, "text": "Now the number must be odd. Now starting from 3 to square root of the number, if the number is divisible by current value, then print, and change the number by divide it with the current number then continue." }, { "code": null, "e": 1975, "s": 1928, "text": "Let us see the algorithm to get a better idea." }, { "code": null, "e": 2232, "s": 1975, "text": "begin\n while n is divisible by 2, do\n print 2\n n := n / 2\n done\n for i := 3 to √n, increase i by 2, do\n while n is divisible by i, do\n print i\n n := n / i\n done\n done\n if n > 2, then\n print n\n end if\nend" }, { "code": null, "e": 2713, "s": 2232, "text": "#include<stdio.h>\n#include<math.h>\nvoid primeFactors(int n) {\n int i;\n while(n % 2 == 0) {\n printf(\"%d, \", 2);\n n = n/2; //reduce n by dividing this by 2\n }\n for(i = 3; i <= sqrt(n); i=i+2){ //i will increase by 2, to get only odd numbers\n while(n % i == 0) {\n printf(\"%d, \", i);\n n = n/i;\n }\n }\n if(n > 2) {\n printf(\"%d, \", n);\n }\n}\nmain() {\n int n;\n printf(\"Enter a number: \");\n scanf(\"%d\", &n);\n primeFactors(n);\n}" }, { "code": null, "e": 2758, "s": 2713, "text": "Enter a number: 24024\n2, 2, 2, 3, 7, 11, 13," } ]
Relative Positioning in CSS
With relative positioning, the element is positioned relative to its normal position. For this, use position: relative Let us now see an example − Live Demo <!DOCTYPE html> <html> <head> <style> div.demo { position: relative; color: white; background-color: orange; border: 2px dashed blue; left: 50px; } </style> </head> <body> <h2>Demo Heading</h2> <p>This is demo text.</p> <p>This is demo text.</p> <div class="demo"> position: relative; </div> <p>This is another demo text.</p> </body> </html>
[ { "code": null, "e": 1181, "s": 1062, "text": "With relative positioning, the element is positioned relative to its normal position. For this, use position: relative" }, { "code": null, "e": 1209, "s": 1181, "text": "Let us now see an example −" }, { "code": null, "e": 1220, "s": 1209, "text": " Live Demo" }, { "code": null, "e": 1577, "s": 1220, "text": "<!DOCTYPE html>\n<html>\n<head>\n<style>\ndiv.demo {\n position: relative;\n color: white;\n background-color: orange;\n border: 2px dashed blue;\n left: 50px;\n}\n</style>\n</head>\n<body>\n<h2>Demo Heading</h2>\n<p>This is demo text.</p>\n<p>This is demo text.</p>\n<div class=\"demo\">\nposition: relative;\n</div>\n<p>This is another demo text.</p>\n</body>\n</html>" } ]
Urban Sound Classification using Neural Networks | by Shubham Gupta | Towards Data Science
Every day we hear different sounds and it is part of our life. Humans can differentiate between sounds easily but how cool it will be if computer can also classify the sounds into categories. In this blog post, we’ll learn techniques for classifying urban sounds into categories using machine learning with neural networks. The dataset is taken from a competition in analytics vidya called Urban Sound. This dataset contains 8732 labelled sound excerpts of urban sounds from 10 classes: air_conditioner, car_horn, children_playing, dog_bark, drilling, enginge_idling, gun_shot, jackhammer, siren, and street_music. I will use the python librosa library to extract numerical features from audio clips and use those features to train a neural network model. First, let us get all the required libraries, import IPython.display as ipdimport osimport numpy as npimport pandas as pdimport matplotlib.pyplot as pltimport librosafrom tqdm import tqdmfrom sklearn.preprocessing import StandardScalerfrom keras.models import Sequentialfrom keras.layers import Dense, Dropout, Activationfrom keras.optimizers import Adam The dataset is available in a google drive, it can be downloaded from here. The dataset contain train, test folder in which sound excerpts are saved and there are train.csv and test.csv which have labels of each sound excerpts. I will be using only train folder for training, validation and testing, it contains 5435 labelled sounds. Now let’s read the train.csv which contains labelled information about sound excerpts. data=pd.read_csv('/content/drive/MyDrive/colab_notebook/train.csv')data.head()#To see the dataset Let’s hear any random sound from the dataset, ipd.Audio(‘/content/drive/My Drive/colab_notebook/Train/123.wav’) Now, the main step is to extract features from the dataset. For this, I will be using librosa library. It is a good library to use with audio files. Using librosa library, I will be extracting four features from the audio files. These features are Mel-frequency cepstral coefficients (MFCCs), tonnetz, mel-scaled spectrogram and chromagram from a waveform. mfc=[]chr=[]me=[]ton=[]lab=[]for i in tqdm(range(len(data))): f_name='/content/drive/My Drive/colab_notebook/Train/'+str(data.ID[i])+'.wav' X, s_rate = librosa.load(f_name, res_type='kaiser_fast') mf = np.mean(librosa.feature.mfcc(y=X, sr=s_rate).T,axis=0) mfc.append(mf) l=data.Class[i] lab.append(l) try: t = np.mean(librosa.feature.tonnetz( y=librosa.effects.harmonic(X), sr=s_rate).T,axis=0) ton.append(t) except: print(f_name) m = np.mean(librosa.feature.melspectrogram(X, sr=s_rate).T,axis=0) me.append(m) s = np.abs(librosa.stft(X)) c = np.mean(librosa.feature.chroma_stft(S=s, sr=s_rate).T,axis=0) chr.append(c) I have got 186 features for each audio files with their respective labels. After extracting features from the audio files save the features because it will take a lot of time to extract features. mfcc = pd.DataFrame(mfc)mfcc.to_csv('/content/drive/My Drive/colab_notebook/mfc.csv', index=False)chrr = pd.DataFrame(chr)chrr.to_csv('/content/drive/My Drive/colab_notebook/chr.csv', index=False)mee = pd.DataFrame(me)mee.to_csv('/content/drive/My Drive/colab_notebook/me.csv', index=False)tonn = pd.DataFrame(ton)tonn.to_csv('/content/drive/My Drive/colab_notebook/ton.csv', index=False)la = pd.DataFrame(lab)la.to_csv('/content/drive/My Drive/colab_notebook/labels.csv', index=False) Concatenate features into one array so that it can be passed to the model. features = []for i in range(len(ton)): features.append(np.concatenate((me[i], mfc[i], ton[i], chr[i]), axis=0)) Encode the labels so that model can understand. la = pd.get_dummies(lab)label_columns=la.columns #To get the classestarget = la.to_numpy() #Convert labels to numpy array Now normalize the features so that gradient descents can converge more quickly. tran = StandardScaler()features_train = tran.fit_transform(features) Now I will create train, validation and test dataset. feat_train=features_train[:4434]target_train=target[:4434]y_train=features_train[4434:5330]y_val=target[4434:5330]test_data=features_train[5330:]test_label=lab['0'][5330:]print("Training",feat_train.shape)print(target_train.shape)print("Validation",y_train.shape)print(y_val.shape)print("Test",test_data.shape)print(test_label.shape) Next step is to build the model. model = Sequential()model.add(Dense(186, input_shape=(186,), activation = 'relu'))model.add(Dense(256, activation = 'relu'))model.add(Dropout(0.6))model.add(Dense(128, activation = 'relu'))model.add(Dropout(0.5))model.add(Dense(10, activation = 'softmax'))model.compile(loss='categorical_crossentropy', metrics=['accuracy'], optimizer='adam') This is the final model which will be used for training. history = model.fit(feat_train, target_train, batch_size=64, epochs=30, validation_data=(y_train, y_val)) The model will train for epoch =30 and has a batch size of 64. After training the model it gives the validation accuracy of 92%. Now let’s see how our model will perform on test dataset. predict = model.predict_classes(test_data) #To predict labels This will get the values now to get the prediction as classes. prediction=[]for i in predict: j=label_columns[i] prediction.append(j) Prediction has 104 test label, and now calculate how many are correctly predicted. k=0for i, j in zip(test_label,prediction): if i==j: k=k+1 Out of 104 labels, this model has correctly predicted 94 labels, which is very good. In this blog, we have discussed how to extract features from audio files using librosa library and then build a model to classify audio files in different classes. All the code in this article resides on this Github link:
[ { "code": null, "e": 239, "s": 47, "text": "Every day we hear different sounds and it is part of our life. Humans can differentiate between sounds easily but how cool it will be if computer can also classify the sounds into categories." }, { "code": null, "e": 662, "s": 239, "text": "In this blog post, we’ll learn techniques for classifying urban sounds into categories using machine learning with neural networks. The dataset is taken from a competition in analytics vidya called Urban Sound. This dataset contains 8732 labelled sound excerpts of urban sounds from 10 classes: air_conditioner, car_horn, children_playing, dog_bark, drilling, enginge_idling, gun_shot, jackhammer, siren, and street_music." }, { "code": null, "e": 803, "s": 662, "text": "I will use the python librosa library to extract numerical features from audio clips and use those features to train a neural network model." }, { "code": null, "e": 849, "s": 803, "text": "First, let us get all the required libraries," }, { "code": null, "e": 1158, "s": 849, "text": "import IPython.display as ipdimport osimport numpy as npimport pandas as pdimport matplotlib.pyplot as pltimport librosafrom tqdm import tqdmfrom sklearn.preprocessing import StandardScalerfrom keras.models import Sequentialfrom keras.layers import Dense, Dropout, Activationfrom keras.optimizers import Adam" }, { "code": null, "e": 1234, "s": 1158, "text": "The dataset is available in a google drive, it can be downloaded from here." }, { "code": null, "e": 1492, "s": 1234, "text": "The dataset contain train, test folder in which sound excerpts are saved and there are train.csv and test.csv which have labels of each sound excerpts. I will be using only train folder for training, validation and testing, it contains 5435 labelled sounds." }, { "code": null, "e": 1579, "s": 1492, "text": "Now let’s read the train.csv which contains labelled information about sound excerpts." }, { "code": null, "e": 1677, "s": 1579, "text": "data=pd.read_csv('/content/drive/MyDrive/colab_notebook/train.csv')data.head()#To see the dataset" }, { "code": null, "e": 1723, "s": 1677, "text": "Let’s hear any random sound from the dataset," }, { "code": null, "e": 1789, "s": 1723, "text": "ipd.Audio(‘/content/drive/My Drive/colab_notebook/Train/123.wav’)" }, { "code": null, "e": 1938, "s": 1789, "text": "Now, the main step is to extract features from the dataset. For this, I will be using librosa library. It is a good library to use with audio files." }, { "code": null, "e": 2146, "s": 1938, "text": "Using librosa library, I will be extracting four features from the audio files. These features are Mel-frequency cepstral coefficients (MFCCs), tonnetz, mel-scaled spectrogram and chromagram from a waveform." }, { "code": null, "e": 2875, "s": 2146, "text": "mfc=[]chr=[]me=[]ton=[]lab=[]for i in tqdm(range(len(data))): f_name='/content/drive/My Drive/colab_notebook/Train/'+str(data.ID[i])+'.wav' X, s_rate = librosa.load(f_name, res_type='kaiser_fast') mf = np.mean(librosa.feature.mfcc(y=X, sr=s_rate).T,axis=0) mfc.append(mf) l=data.Class[i] lab.append(l) try: t = np.mean(librosa.feature.tonnetz( y=librosa.effects.harmonic(X), sr=s_rate).T,axis=0) ton.append(t) except: print(f_name) m = np.mean(librosa.feature.melspectrogram(X, sr=s_rate).T,axis=0) me.append(m) s = np.abs(librosa.stft(X)) c = np.mean(librosa.feature.chroma_stft(S=s, sr=s_rate).T,axis=0) chr.append(c)" }, { "code": null, "e": 2950, "s": 2875, "text": "I have got 186 features for each audio files with their respective labels." }, { "code": null, "e": 3071, "s": 2950, "text": "After extracting features from the audio files save the features because it will take a lot of time to extract features." }, { "code": null, "e": 3557, "s": 3071, "text": "mfcc = pd.DataFrame(mfc)mfcc.to_csv('/content/drive/My Drive/colab_notebook/mfc.csv', index=False)chrr = pd.DataFrame(chr)chrr.to_csv('/content/drive/My Drive/colab_notebook/chr.csv', index=False)mee = pd.DataFrame(me)mee.to_csv('/content/drive/My Drive/colab_notebook/me.csv', index=False)tonn = pd.DataFrame(ton)tonn.to_csv('/content/drive/My Drive/colab_notebook/ton.csv', index=False)la = pd.DataFrame(lab)la.to_csv('/content/drive/My Drive/colab_notebook/labels.csv', index=False)" }, { "code": null, "e": 3632, "s": 3557, "text": "Concatenate features into one array so that it can be passed to the model." }, { "code": null, "e": 3763, "s": 3632, "text": "features = []for i in range(len(ton)): features.append(np.concatenate((me[i], mfc[i], ton[i], chr[i]), axis=0))" }, { "code": null, "e": 3811, "s": 3763, "text": "Encode the labels so that model can understand." }, { "code": null, "e": 3933, "s": 3811, "text": "la = pd.get_dummies(lab)label_columns=la.columns #To get the classestarget = la.to_numpy() #Convert labels to numpy array" }, { "code": null, "e": 4013, "s": 3933, "text": "Now normalize the features so that gradient descents can converge more quickly." }, { "code": null, "e": 4082, "s": 4013, "text": "tran = StandardScaler()features_train = tran.fit_transform(features)" }, { "code": null, "e": 4136, "s": 4082, "text": "Now I will create train, validation and test dataset." }, { "code": null, "e": 4470, "s": 4136, "text": "feat_train=features_train[:4434]target_train=target[:4434]y_train=features_train[4434:5330]y_val=target[4434:5330]test_data=features_train[5330:]test_label=lab['0'][5330:]print(\"Training\",feat_train.shape)print(target_train.shape)print(\"Validation\",y_train.shape)print(y_val.shape)print(\"Test\",test_data.shape)print(test_label.shape)" }, { "code": null, "e": 4503, "s": 4470, "text": "Next step is to build the model." }, { "code": null, "e": 4846, "s": 4503, "text": "model = Sequential()model.add(Dense(186, input_shape=(186,), activation = 'relu'))model.add(Dense(256, activation = 'relu'))model.add(Dropout(0.6))model.add(Dense(128, activation = 'relu'))model.add(Dropout(0.5))model.add(Dense(10, activation = 'softmax'))model.compile(loss='categorical_crossentropy', metrics=['accuracy'], optimizer='adam')" }, { "code": null, "e": 4903, "s": 4846, "text": "This is the final model which will be used for training." }, { "code": null, "e": 5029, "s": 4903, "text": "history = model.fit(feat_train, target_train, batch_size=64, epochs=30, validation_data=(y_train, y_val))" }, { "code": null, "e": 5092, "s": 5029, "text": "The model will train for epoch =30 and has a batch size of 64." }, { "code": null, "e": 5158, "s": 5092, "text": "After training the model it gives the validation accuracy of 92%." }, { "code": null, "e": 5216, "s": 5158, "text": "Now let’s see how our model will perform on test dataset." }, { "code": null, "e": 5278, "s": 5216, "text": "predict = model.predict_classes(test_data) #To predict labels" }, { "code": null, "e": 5341, "s": 5278, "text": "This will get the values now to get the prediction as classes." }, { "code": null, "e": 5414, "s": 5341, "text": "prediction=[]for i in predict: j=label_columns[i] prediction.append(j)" }, { "code": null, "e": 5497, "s": 5414, "text": "Prediction has 104 test label, and now calculate how many are correctly predicted." }, { "code": null, "e": 5564, "s": 5497, "text": "k=0for i, j in zip(test_label,prediction): if i==j: k=k+1" }, { "code": null, "e": 5649, "s": 5564, "text": "Out of 104 labels, this model has correctly predicted 94 labels, which is very good." }, { "code": null, "e": 5813, "s": 5649, "text": "In this blog, we have discussed how to extract features from audio files using librosa library and then build a model to classify audio files in different classes." } ]
\hdashline - Tex Command
\hdashline - Used to draw horizontal dash line. { \hdashline } \hdashline command draws horizontal dash line. \begin{matrix} x_{11} & x_{12} \\ x_{21} & x_{22} \strut \\ \hdashline x_{31} & x_{32} \strut \end{matrix} x11x12x21x22x31x32 \begin{matrix} x_{11} & x_{12} \\ x_{21} & x_{22} \strut \\ \hdashline x_{31} & x_{32} \strut \end{matrix} x11x12x21x22x31x32 \begin{matrix} x_{11} & x_{12} \\ x_{21} & x_{22} \strut \\ \hdashline x_{31} & x_{32} \strut \end{matrix} 14 Lectures 52 mins Ashraf Said 11 Lectures 1 hours Ashraf Said 9 Lectures 1 hours Emenwa Global, Ejike IfeanyiChukwu 29 Lectures 2.5 hours Mohammad Nauman 14 Lectures 1 hours Daniel Stern 15 Lectures 47 mins Nishant Kumar Print Add Notes Bookmark this page
[ { "code": null, "e": 8034, "s": 7986, "text": "\\hdashline - Used to draw horizontal dash line." }, { "code": null, "e": 8049, "s": 8034, "text": "{ \\hdashline }" }, { "code": null, "e": 8096, "s": 8049, "text": "\\hdashline command draws horizontal dash line." }, { "code": null, "e": 8227, "s": 8096, "text": "\n\\begin{matrix}\nx_{11} & x_{12} \\\\\nx_{21} & x_{22} \\strut \\\\\n\\hdashline\nx_{31} & x_{32} \\strut\n\\end{matrix}\n\nx11x12x21x22x31x32\n\n\n" }, { "code": null, "e": 8356, "s": 8227, "text": "\\begin{matrix}\nx_{11} & x_{12} \\\\\nx_{21} & x_{22} \\strut \\\\\n\\hdashline\nx_{31} & x_{32} \\strut\n\\end{matrix}\n\nx11x12x21x22x31x32\n\n" }, { "code": null, "e": 8463, "s": 8356, "text": "\\begin{matrix}\nx_{11} & x_{12} \\\\\nx_{21} & x_{22} \\strut \\\\\n\\hdashline\nx_{31} & x_{32} \\strut\n\\end{matrix}" }, { "code": null, "e": 8495, "s": 8463, "text": "\n 14 Lectures \n 52 mins\n" }, { "code": null, "e": 8508, "s": 8495, "text": " Ashraf Said" }, { "code": null, "e": 8541, "s": 8508, "text": "\n 11 Lectures \n 1 hours \n" }, { "code": null, "e": 8554, "s": 8541, "text": " Ashraf Said" }, { "code": null, "e": 8586, "s": 8554, "text": "\n 9 Lectures \n 1 hours \n" }, { "code": null, "e": 8622, "s": 8586, "text": " Emenwa Global, Ejike IfeanyiChukwu" }, { "code": null, "e": 8657, "s": 8622, "text": "\n 29 Lectures \n 2.5 hours \n" }, { "code": null, "e": 8674, "s": 8657, "text": " Mohammad Nauman" }, { "code": null, "e": 8707, "s": 8674, "text": "\n 14 Lectures \n 1 hours \n" }, { "code": null, "e": 8721, "s": 8707, "text": " Daniel Stern" }, { "code": null, "e": 8753, "s": 8721, "text": "\n 15 Lectures \n 47 mins\n" }, { "code": null, "e": 8768, "s": 8753, "text": " Nishant Kumar" }, { "code": null, "e": 8775, "s": 8768, "text": " Print" }, { "code": null, "e": 8786, "s": 8775, "text": " Add Notes" } ]
Introduction to Topic Modeling using Scikit-Learn | by Ng Wai Foong | Towards Data Science
Building on top of my previous articles on natural language processing Extractive Text Summarization Using spaCy in Python Extract Keywords Using spaCy in Python Let’s explore how to perform topic extraction using another popular machine learning module called scikit-learn. In this tutorial, we will be learning about the following unsupervised learning algorithms: Non-negative matrix factorization (NMF) Latent dirichlet allocation (LDA) TruncatedSVD (also known as latent semantic analysis when used with count or tfidf matrices) As for the dataset, you can choose to use your own or download the publicly available 20 News Group Dataset. It consists of approximately 20k documents related to newsgroup. There are altogether 3 variations: 20news-19997.tar.gz — contains the original unmodified 20 Newsgroups data set 20news-bydate.tar.gz — dataset is sorted by date in addition to the removal of duplicates and some headers. Split into train and test folder. 20news-18828.tar.gz — duplicates are removed and headers contain only From and Subject. I am using 20news-18828 dataset for this tutorial. To keep things simple and short, I am going to use only 5 topics out of 20. rec.sport.hockey soc.religion.christian talk.politics.mideast comp.graphics sci.crypt scikit-learn’s Vectorizers expect a list as input argument with each item represent the content of a document in string. You can easily process the dataset and store it in a JSON file via the following code: It is a lot faster to read the data from a single file before fitting it to any Vectorizers. Please be noted that the new dataset that we have created contains unnecessary header such as From followed by email and name of a person. Such noises will impact the result of your final prediction. In an actual use case, you should remove them and retain only relevant information related to the documents. Let’s proceed to the next section and start installing the necessary modules It is highly recommended to create a virtual environment before you continue with the installation. You can easily install the latest version of scikit-learn by running the following command in your terminal: pip install -U scikit-learn Next, continue to install pandas which is a powerful data analysis and manipulation tool. pip install pandas At the time of this writing, the latest numpy version is 1.19.4. It has a serious bug which causes the following error in Windows operating system. The current Numpy installation fails to pass a sanity check due to a bug in the windows runtime The developers behind numpy have released “... a bugfix 1.19.3 to work around this issue. The bugfix broke something else on Linux, so we had to revert the fix in release 1.19.4, but you can still install the 1.19.3 via pip install numpy==1.19.3.” In other words, you should install the working version based on the operating system of your machine. Windows — 1.19.3 Linux — 1.19.4 Run the following command to install numpy. Modify the version accordingly. pip install numpy==1.19.3 You should have the following packages installed in your virtual environment. cycler 0.10.0joblib 1.0.0kiwisolver 1.3.1matplotlib 3.2.0numpy 1.19.3pandas 1.2.0Pillow 8.0.1pip 20.3.3pyparsing 2.4.7python-dateutil 2.8.1pytz 2020.5scikit-learn 0.24.0scipy 1.5.4setuptools 51.1.0six 1.15.0threadpoolctl 2.1.0 In this section, we are going to implement our topic modeling code using three different algorithms. Create a new Python file called test.py. Add the following import statement at the top of the file. import pandas as pdfrom sklearn.feature_extraction.text import TfidfVectorizer, CountVectorizerfrom sklearn.decomposition import NMF, LatentDirichletAllocation, TruncatedSVDimport numpy as npimport jsonimport random Next, we are going to load the dataset that we have created earlier. It is a good idea to shuffle all the items in the list before you fit it to a Vectorizer. corpus = []with open('data.json', 'r', encoding='utf8') as f: corpus = json.loads(f.read()) random.shuffle(corpus) Initialize the following variables which will be used later on. n_features = 1000n_components = 5n_top_words = 20 n_components represents the number of topics while n_top_words represents the number of top words to be extracted for a single topic. By default, there are no labels for the respective topic during predictions. You need to identify it on your own and label it manually after that. Define the following variables which serve as the label for each algorithm: nmf_topics = ['soc.religion.christian', 'sci.crypt', 'rec.sport.hockey', 'talk.politics.mideast', 'comp.graphics']lsa_topics = ['soc.religion.christian', 'sci.crypt', 'rec.sport.hockey', 'talk.politics.mideast', 'comp.graphics']lda_topics = ['talk.politics.mideast', 'rec.sport.hockey', 'soc.religion.christian', 'sci.crypt', 'comp.graphics'] Besides, the order and arrangement of the topics are not in order during each run especially for probabilistic model such as LDA. Hence, you should modify the arrangement after you ran the whole training and prediction pipeline. CountVectorizer converts a collection of text documents to a matrix which contains all the token counts. Sometimes, token count is referred to as term frequency. There are a quite useful input parameters that can be modified: max_df — ignore terms with frequency higher than given threshold. Accepts either a float (range from 0 to 1) or integer. Float represents the proportion of documents while integer refers to absolute counts. min_df — similar to max_df but ignore terms with frequency lower than given threshold max_features — will only consider the given features ordered by term frequency across the entire corpus stop_words — accepts a list of custom stopwords to be removed from the corpus. You can specify the string english which uses built-in stopwords for English. ngram_range — a tuple which represents the lower and upper boundary for n-gram extractions. Continue by adding the following code: tf_vectorizer = CountVectorizer(max_df=0.95, min_df=2, max_features=n_features, stop_words='english', ngram_range=(1, 2))tf = tf_vectorizer.fit_transform(corpus) It will remove words that occur in less than 2 documents or appear in at least 95% of the documents. Setting ngram_range to (1, 2) indicates that we are using uni-gram and bi-gram when vectorizing the dataset. Unlike CountVectorizer, TfidfVectorizer converts documents to a matrix of TF-IDF features. The end result is akin to processing via CountVectorizer followed by TfidfTransformer. The input parameters are more or less the same as CountVectorizer. You should this whenever possible with the only exception for algorithms that are based on word count and document count such as latent dirichlet allocation (LDA). Append the following code which initialize the TfidfVectorizer and vectorize the input list of documents. tfidf_vectorizer = TfidfVectorizer(max_df=0.95, min_df=2, max_features=n_features, stop_words='english', ngram_range=(1, 2))tfidf = tfidf_vectorizer.fit_transform(corpus) Input parameters are exactly the same that we used previously for CountVectorizer. As the name implies, this algorithm is used to find “... two non-negative matrices (W, H) whose product approximates the non- negative matrix X.” The results are extremely useful to reduce the dimension of features as well as source separation. Besides, it can also be used for topic extraction. There are a few input parameters that can be fine-tuned. For example, you can change the init parameter for initializing the procedure: random — non-negative random matrices nndsvd — nonnegative double singular value decomposition. It is the preferred choice for sparseness. nndsvda —nndsvd with zeros filled with the average of X. You should use when sparsity is not needed. nndsvdar —nndsvd with zeros filled with small random values. Faster but less accurate compared to nndsvda. By default, the value is random unless n_components < n_features. If that is the case, nndsvd will be used. You tune the numerical solver parameter with one of the following: cd — Coordinate Descent mu — Multiplicative Update NMF can be applied with three different objective functions (called beta_loss when calling the function in sklearn): frobenius kullback-leibler itakura-saito — it can only be used in mu solver and the input matrix X must not contain zeros. Objective function will be defaulted to frobenius during instantiation. The time complexity is polynomial when running NMF. Initialize a new instance which takes in the output matrix of TfidfVectorizer. nmf = NMF(n_components=n_components, random_state=1, alpha=.1, l1_ratio=.5, init='nndsvd').fit(tfidf) alpha and l1_ratio are related to regularization. Set alpha value to 0 if you prefer to have no regularization. LDA is a good generative probabilistic model for identifying abstract topics from discrete dataset such as text corpora. LDA in scikit-learn is based on online variational Bayes algorithm which supports the following learning_method: batch — use all training data in each update. online — use mini-batch of the training data for each update. Will be a lot faster than batch if the training data size is large. From version 0.20 onwards, the default learning_method is batch. You should use CountVectorizer when fitting LDA instead of TfidfVectorizer since LDA is based on term count and document count. Fitting LDA with TfidfVectorizer will result in rare words being dis-proportionally sampled. As a result, they will have greater impact and influence on the final topic distribution. Use the following code to create a new instance of LDA. lda = LatentDirichletAllocation(n_components=n_components, random_state=1).fit(tf) Since LDA is a probabilistic model, you will get some differences in the end result each time you run it. Hence, it is a good idea to set the random_state parameter to a fixed number and save the model locally using pickle to preserve how it infers the topics later on. In addition, scikit-learn also comes with a great and useful dimensionality reduction model called Truncated Singular Value Decomposition (TruncatedSVD). Unlike PCA, this model computes the singular value decomposition without centering the data. In the event where TruncatedSVD model is fitted with count or tfidf matrices, it is also known as Latent Semantic Analysis (LSA). Most articles tend to refer this as LSA instead of TruncatedSVD. For consistency, I will refer it as LSA as well in this tutorial. It supports two different algorithms: randomized — a fast randomized SVD solver arpack — based on SciPy’s ARPACK wrapper as eigensolver Create a new instance of TruncatedSVD which fits against tfidf’s matrix via the following code. lsa = TruncatedSVD(n_components=n_components, random_state=1, algorithm='arpack').fit(tfidf) Please be noted that you should fit instance of this class once with pre-defined random_state before performing transformations. This prevents sign indeterminnancy issue, as the output from transform depends on the algorithm as well as random_state. Once you are done with it, let’s create a generic function which returns topics from a model as DataFrame. Our implementation is based on the print_top_words function from the following tutorial but with a little twist to it. Feel free to modify it based on your use cases. We will need another function to do inference for any input text of our choice. Define a new function called get_inference and add the following code inside it. This is my own implementation which returns label of the topic with the highest confidence confidence value for all the topics labels of all the topics that exceed a certain threshold Please be noted that confidence value for a particular topic can be a negative number depending on the algorithm used. The last step is to run both of the functions that we have created earlier and print out the results. I am going to use the following input text in which should be mapped to comp.graphics. text = 'you should use either jpeg or png files for it' Continue by calling the functions on all of the models that we have. For NMF, I got the following output which illustrated the topics distribution and final inference of the input text: The result for LSA is a little less promising even though the final result is accurate. There are quite a few of words that are modeled wrongly based on the topics distribution. On the other hand, LDA returned the following result. The word edu was predicted as the top word for three topics. This is mainly because the dataset that I used has From headers which contains quite a number of email addresses ends with .edu. Please be noted that the order of topics and top words might be different on each run especially if you did not specify a random_state or uses online learning. Consider saving both the Vectorizer and model locally using pickle if you intend to preserve the same results on each execution. Let’s recap what we have learned today. We started off with exploring the 20 NewGroup dataset which categorized into three different variations. We also processed the data and used only 5 topics instead of the full dataset. Then, we moved on to install the necessary Python modules and loaded our dataset in a Python file. Furthermore, we created both the CountVectorizer and TfidfVectorizer which are used to vectorize the documents before fitting them to our models. We built three different models based on non-negative matrix factorization, latent dirichlet allocation and TruncatedSVD. Lastly, we created generic functions to get topics and perform inference from the models that we have built. Thanks for reading this piece. Hope to see you again in the next article! 20 News Group DatasetStackOverflow — Numpy runtime issueSkLearn — Topic Extraction 20 News Group Dataset StackOverflow — Numpy runtime issue SkLearn — Topic Extraction
[ { "code": null, "e": 243, "s": 172, "text": "Building on top of my previous articles on natural language processing" }, { "code": null, "e": 295, "s": 243, "text": "Extractive Text Summarization Using spaCy in Python" }, { "code": null, "e": 334, "s": 295, "text": "Extract Keywords Using spaCy in Python" }, { "code": null, "e": 539, "s": 334, "text": "Let’s explore how to perform topic extraction using another popular machine learning module called scikit-learn. In this tutorial, we will be learning about the following unsupervised learning algorithms:" }, { "code": null, "e": 579, "s": 539, "text": "Non-negative matrix factorization (NMF)" }, { "code": null, "e": 613, "s": 579, "text": "Latent dirichlet allocation (LDA)" }, { "code": null, "e": 706, "s": 613, "text": "TruncatedSVD (also known as latent semantic analysis when used with count or tfidf matrices)" }, { "code": null, "e": 915, "s": 706, "text": "As for the dataset, you can choose to use your own or download the publicly available 20 News Group Dataset. It consists of approximately 20k documents related to newsgroup. There are altogether 3 variations:" }, { "code": null, "e": 993, "s": 915, "text": "20news-19997.tar.gz — contains the original unmodified 20 Newsgroups data set" }, { "code": null, "e": 1135, "s": 993, "text": "20news-bydate.tar.gz — dataset is sorted by date in addition to the removal of duplicates and some headers. Split into train and test folder." }, { "code": null, "e": 1223, "s": 1135, "text": "20news-18828.tar.gz — duplicates are removed and headers contain only From and Subject." }, { "code": null, "e": 1350, "s": 1223, "text": "I am using 20news-18828 dataset for this tutorial. To keep things simple and short, I am going to use only 5 topics out of 20." }, { "code": null, "e": 1367, "s": 1350, "text": "rec.sport.hockey" }, { "code": null, "e": 1390, "s": 1367, "text": "soc.religion.christian" }, { "code": null, "e": 1412, "s": 1390, "text": "talk.politics.mideast" }, { "code": null, "e": 1426, "s": 1412, "text": "comp.graphics" }, { "code": null, "e": 1436, "s": 1426, "text": "sci.crypt" }, { "code": null, "e": 1644, "s": 1436, "text": "scikit-learn’s Vectorizers expect a list as input argument with each item represent the content of a document in string. You can easily process the dataset and store it in a JSON file via the following code:" }, { "code": null, "e": 1737, "s": 1644, "text": "It is a lot faster to read the data from a single file before fitting it to any Vectorizers." }, { "code": null, "e": 2046, "s": 1737, "text": "Please be noted that the new dataset that we have created contains unnecessary header such as From followed by email and name of a person. Such noises will impact the result of your final prediction. In an actual use case, you should remove them and retain only relevant information related to the documents." }, { "code": null, "e": 2123, "s": 2046, "text": "Let’s proceed to the next section and start installing the necessary modules" }, { "code": null, "e": 2223, "s": 2123, "text": "It is highly recommended to create a virtual environment before you continue with the installation." }, { "code": null, "e": 2332, "s": 2223, "text": "You can easily install the latest version of scikit-learn by running the following command in your terminal:" }, { "code": null, "e": 2360, "s": 2332, "text": "pip install -U scikit-learn" }, { "code": null, "e": 2450, "s": 2360, "text": "Next, continue to install pandas which is a powerful data analysis and manipulation tool." }, { "code": null, "e": 2469, "s": 2450, "text": "pip install pandas" }, { "code": null, "e": 2617, "s": 2469, "text": "At the time of this writing, the latest numpy version is 1.19.4. It has a serious bug which causes the following error in Windows operating system." }, { "code": null, "e": 2713, "s": 2617, "text": "The current Numpy installation fails to pass a sanity check due to a bug in the windows runtime" }, { "code": null, "e": 2755, "s": 2713, "text": "The developers behind numpy have released" }, { "code": null, "e": 2961, "s": 2755, "text": "“... a bugfix 1.19.3 to work around this issue. The bugfix broke something else on Linux, so we had to revert the fix in release 1.19.4, but you can still install the 1.19.3 via pip install numpy==1.19.3.”" }, { "code": null, "e": 3063, "s": 2961, "text": "In other words, you should install the working version based on the operating system of your machine." }, { "code": null, "e": 3080, "s": 3063, "text": "Windows — 1.19.3" }, { "code": null, "e": 3095, "s": 3080, "text": "Linux — 1.19.4" }, { "code": null, "e": 3171, "s": 3095, "text": "Run the following command to install numpy. Modify the version accordingly." }, { "code": null, "e": 3197, "s": 3171, "text": "pip install numpy==1.19.3" }, { "code": null, "e": 3275, "s": 3197, "text": "You should have the following packages installed in your virtual environment." }, { "code": null, "e": 3619, "s": 3275, "text": "cycler 0.10.0joblib 1.0.0kiwisolver 1.3.1matplotlib 3.2.0numpy 1.19.3pandas 1.2.0Pillow 8.0.1pip 20.3.3pyparsing 2.4.7python-dateutil 2.8.1pytz 2020.5scikit-learn 0.24.0scipy 1.5.4setuptools 51.1.0six 1.15.0threadpoolctl 2.1.0" }, { "code": null, "e": 3761, "s": 3619, "text": "In this section, we are going to implement our topic modeling code using three different algorithms. Create a new Python file called test.py." }, { "code": null, "e": 3820, "s": 3761, "text": "Add the following import statement at the top of the file." }, { "code": null, "e": 4036, "s": 3820, "text": "import pandas as pdfrom sklearn.feature_extraction.text import TfidfVectorizer, CountVectorizerfrom sklearn.decomposition import NMF, LatentDirichletAllocation, TruncatedSVDimport numpy as npimport jsonimport random" }, { "code": null, "e": 4195, "s": 4036, "text": "Next, we are going to load the dataset that we have created earlier. It is a good idea to shuffle all the items in the list before you fit it to a Vectorizer." }, { "code": null, "e": 4316, "s": 4195, "text": "corpus = []with open('data.json', 'r', encoding='utf8') as f: corpus = json.loads(f.read()) random.shuffle(corpus)" }, { "code": null, "e": 4380, "s": 4316, "text": "Initialize the following variables which will be used later on." }, { "code": null, "e": 4430, "s": 4380, "text": "n_features = 1000n_components = 5n_top_words = 20" }, { "code": null, "e": 4564, "s": 4430, "text": "n_components represents the number of topics while n_top_words represents the number of top words to be extracted for a single topic." }, { "code": null, "e": 4711, "s": 4564, "text": "By default, there are no labels for the respective topic during predictions. You need to identify it on your own and label it manually after that." }, { "code": null, "e": 4787, "s": 4711, "text": "Define the following variables which serve as the label for each algorithm:" }, { "code": null, "e": 5130, "s": 4787, "text": "nmf_topics = ['soc.religion.christian', 'sci.crypt', 'rec.sport.hockey', 'talk.politics.mideast', 'comp.graphics']lsa_topics = ['soc.religion.christian', 'sci.crypt', 'rec.sport.hockey', 'talk.politics.mideast', 'comp.graphics']lda_topics = ['talk.politics.mideast', 'rec.sport.hockey', 'soc.religion.christian', 'sci.crypt', 'comp.graphics']" }, { "code": null, "e": 5359, "s": 5130, "text": "Besides, the order and arrangement of the topics are not in order during each run especially for probabilistic model such as LDA. Hence, you should modify the arrangement after you ran the whole training and prediction pipeline." }, { "code": null, "e": 5521, "s": 5359, "text": "CountVectorizer converts a collection of text documents to a matrix which contains all the token counts. Sometimes, token count is referred to as term frequency." }, { "code": null, "e": 5585, "s": 5521, "text": "There are a quite useful input parameters that can be modified:" }, { "code": null, "e": 5792, "s": 5585, "text": "max_df — ignore terms with frequency higher than given threshold. Accepts either a float (range from 0 to 1) or integer. Float represents the proportion of documents while integer refers to absolute counts." }, { "code": null, "e": 5878, "s": 5792, "text": "min_df — similar to max_df but ignore terms with frequency lower than given threshold" }, { "code": null, "e": 5982, "s": 5878, "text": "max_features — will only consider the given features ordered by term frequency across the entire corpus" }, { "code": null, "e": 6139, "s": 5982, "text": "stop_words — accepts a list of custom stopwords to be removed from the corpus. You can specify the string english which uses built-in stopwords for English." }, { "code": null, "e": 6231, "s": 6139, "text": "ngram_range — a tuple which represents the lower and upper boundary for n-gram extractions." }, { "code": null, "e": 6270, "s": 6231, "text": "Continue by adding the following code:" }, { "code": null, "e": 6432, "s": 6270, "text": "tf_vectorizer = CountVectorizer(max_df=0.95, min_df=2, max_features=n_features, stop_words='english', ngram_range=(1, 2))tf = tf_vectorizer.fit_transform(corpus)" }, { "code": null, "e": 6642, "s": 6432, "text": "It will remove words that occur in less than 2 documents or appear in at least 95% of the documents. Setting ngram_range to (1, 2) indicates that we are using uni-gram and bi-gram when vectorizing the dataset." }, { "code": null, "e": 6820, "s": 6642, "text": "Unlike CountVectorizer, TfidfVectorizer converts documents to a matrix of TF-IDF features. The end result is akin to processing via CountVectorizer followed by TfidfTransformer." }, { "code": null, "e": 7051, "s": 6820, "text": "The input parameters are more or less the same as CountVectorizer. You should this whenever possible with the only exception for algorithms that are based on word count and document count such as latent dirichlet allocation (LDA)." }, { "code": null, "e": 7157, "s": 7051, "text": "Append the following code which initialize the TfidfVectorizer and vectorize the input list of documents." }, { "code": null, "e": 7328, "s": 7157, "text": "tfidf_vectorizer = TfidfVectorizer(max_df=0.95, min_df=2, max_features=n_features, stop_words='english', ngram_range=(1, 2))tfidf = tfidf_vectorizer.fit_transform(corpus)" }, { "code": null, "e": 7411, "s": 7328, "text": "Input parameters are exactly the same that we used previously for CountVectorizer." }, { "code": null, "e": 7463, "s": 7411, "text": "As the name implies, this algorithm is used to find" }, { "code": null, "e": 7557, "s": 7463, "text": "“... two non-negative matrices (W, H) whose product approximates the non- negative matrix X.”" }, { "code": null, "e": 7707, "s": 7557, "text": "The results are extremely useful to reduce the dimension of features as well as source separation. Besides, it can also be used for topic extraction." }, { "code": null, "e": 7843, "s": 7707, "text": "There are a few input parameters that can be fine-tuned. For example, you can change the init parameter for initializing the procedure:" }, { "code": null, "e": 7881, "s": 7843, "text": "random — non-negative random matrices" }, { "code": null, "e": 7982, "s": 7881, "text": "nndsvd — nonnegative double singular value decomposition. It is the preferred choice for sparseness." }, { "code": null, "e": 8083, "s": 7982, "text": "nndsvda —nndsvd with zeros filled with the average of X. You should use when sparsity is not needed." }, { "code": null, "e": 8190, "s": 8083, "text": "nndsvdar —nndsvd with zeros filled with small random values. Faster but less accurate compared to nndsvda." }, { "code": null, "e": 8298, "s": 8190, "text": "By default, the value is random unless n_components < n_features. If that is the case, nndsvd will be used." }, { "code": null, "e": 8365, "s": 8298, "text": "You tune the numerical solver parameter with one of the following:" }, { "code": null, "e": 8389, "s": 8365, "text": "cd — Coordinate Descent" }, { "code": null, "e": 8416, "s": 8389, "text": "mu — Multiplicative Update" }, { "code": null, "e": 8533, "s": 8416, "text": "NMF can be applied with three different objective functions (called beta_loss when calling the function in sklearn):" }, { "code": null, "e": 8543, "s": 8533, "text": "frobenius" }, { "code": null, "e": 8560, "s": 8543, "text": "kullback-leibler" }, { "code": null, "e": 8656, "s": 8560, "text": "itakura-saito — it can only be used in mu solver and the input matrix X must not contain zeros." }, { "code": null, "e": 8780, "s": 8656, "text": "Objective function will be defaulted to frobenius during instantiation. The time complexity is polynomial when running NMF." }, { "code": null, "e": 8859, "s": 8780, "text": "Initialize a new instance which takes in the output matrix of TfidfVectorizer." }, { "code": null, "e": 8961, "s": 8859, "text": "nmf = NMF(n_components=n_components, random_state=1, alpha=.1, l1_ratio=.5, init='nndsvd').fit(tfidf)" }, { "code": null, "e": 9073, "s": 8961, "text": "alpha and l1_ratio are related to regularization. Set alpha value to 0 if you prefer to have no regularization." }, { "code": null, "e": 9194, "s": 9073, "text": "LDA is a good generative probabilistic model for identifying abstract topics from discrete dataset such as text corpora." }, { "code": null, "e": 9307, "s": 9194, "text": "LDA in scikit-learn is based on online variational Bayes algorithm which supports the following learning_method:" }, { "code": null, "e": 9353, "s": 9307, "text": "batch — use all training data in each update." }, { "code": null, "e": 9483, "s": 9353, "text": "online — use mini-batch of the training data for each update. Will be a lot faster than batch if the training data size is large." }, { "code": null, "e": 9548, "s": 9483, "text": "From version 0.20 onwards, the default learning_method is batch." }, { "code": null, "e": 9859, "s": 9548, "text": "You should use CountVectorizer when fitting LDA instead of TfidfVectorizer since LDA is based on term count and document count. Fitting LDA with TfidfVectorizer will result in rare words being dis-proportionally sampled. As a result, they will have greater impact and influence on the final topic distribution." }, { "code": null, "e": 9915, "s": 9859, "text": "Use the following code to create a new instance of LDA." }, { "code": null, "e": 9998, "s": 9915, "text": "lda = LatentDirichletAllocation(n_components=n_components, random_state=1).fit(tf)" }, { "code": null, "e": 10268, "s": 9998, "text": "Since LDA is a probabilistic model, you will get some differences in the end result each time you run it. Hence, it is a good idea to set the random_state parameter to a fixed number and save the model locally using pickle to preserve how it infers the topics later on." }, { "code": null, "e": 10515, "s": 10268, "text": "In addition, scikit-learn also comes with a great and useful dimensionality reduction model called Truncated Singular Value Decomposition (TruncatedSVD). Unlike PCA, this model computes the singular value decomposition without centering the data." }, { "code": null, "e": 10776, "s": 10515, "text": "In the event where TruncatedSVD model is fitted with count or tfidf matrices, it is also known as Latent Semantic Analysis (LSA). Most articles tend to refer this as LSA instead of TruncatedSVD. For consistency, I will refer it as LSA as well in this tutorial." }, { "code": null, "e": 10814, "s": 10776, "text": "It supports two different algorithms:" }, { "code": null, "e": 10856, "s": 10814, "text": "randomized — a fast randomized SVD solver" }, { "code": null, "e": 10912, "s": 10856, "text": "arpack — based on SciPy’s ARPACK wrapper as eigensolver" }, { "code": null, "e": 11008, "s": 10912, "text": "Create a new instance of TruncatedSVD which fits against tfidf’s matrix via the following code." }, { "code": null, "e": 11101, "s": 11008, "text": "lsa = TruncatedSVD(n_components=n_components, random_state=1, algorithm='arpack').fit(tfidf)" }, { "code": null, "e": 11351, "s": 11101, "text": "Please be noted that you should fit instance of this class once with pre-defined random_state before performing transformations. This prevents sign indeterminnancy issue, as the output from transform depends on the algorithm as well as random_state." }, { "code": null, "e": 11625, "s": 11351, "text": "Once you are done with it, let’s create a generic function which returns topics from a model as DataFrame. Our implementation is based on the print_top_words function from the following tutorial but with a little twist to it. Feel free to modify it based on your use cases." }, { "code": null, "e": 11786, "s": 11625, "text": "We will need another function to do inference for any input text of our choice. Define a new function called get_inference and add the following code inside it." }, { "code": null, "e": 11830, "s": 11786, "text": "This is my own implementation which returns" }, { "code": null, "e": 11877, "s": 11830, "text": "label of the topic with the highest confidence" }, { "code": null, "e": 11913, "s": 11877, "text": "confidence value for all the topics" }, { "code": null, "e": 11970, "s": 11913, "text": "labels of all the topics that exceed a certain threshold" }, { "code": null, "e": 12089, "s": 11970, "text": "Please be noted that confidence value for a particular topic can be a negative number depending on the algorithm used." }, { "code": null, "e": 12278, "s": 12089, "text": "The last step is to run both of the functions that we have created earlier and print out the results. I am going to use the following input text in which should be mapped to comp.graphics." }, { "code": null, "e": 12334, "s": 12278, "text": "text = 'you should use either jpeg or png files for it'" }, { "code": null, "e": 12403, "s": 12334, "text": "Continue by calling the functions on all of the models that we have." }, { "code": null, "e": 12520, "s": 12403, "text": "For NMF, I got the following output which illustrated the topics distribution and final inference of the input text:" }, { "code": null, "e": 12698, "s": 12520, "text": "The result for LSA is a little less promising even though the final result is accurate. There are quite a few of words that are modeled wrongly based on the topics distribution." }, { "code": null, "e": 12942, "s": 12698, "text": "On the other hand, LDA returned the following result. The word edu was predicted as the top word for three topics. This is mainly because the dataset that I used has From headers which contains quite a number of email addresses ends with .edu." }, { "code": null, "e": 13102, "s": 12942, "text": "Please be noted that the order of topics and top words might be different on each run especially if you did not specify a random_state or uses online learning." }, { "code": null, "e": 13231, "s": 13102, "text": "Consider saving both the Vectorizer and model locally using pickle if you intend to preserve the same results on each execution." }, { "code": null, "e": 13271, "s": 13231, "text": "Let’s recap what we have learned today." }, { "code": null, "e": 13455, "s": 13271, "text": "We started off with exploring the 20 NewGroup dataset which categorized into three different variations. We also processed the data and used only 5 topics instead of the full dataset." }, { "code": null, "e": 13554, "s": 13455, "text": "Then, we moved on to install the necessary Python modules and loaded our dataset in a Python file." }, { "code": null, "e": 13700, "s": 13554, "text": "Furthermore, we created both the CountVectorizer and TfidfVectorizer which are used to vectorize the documents before fitting them to our models." }, { "code": null, "e": 13822, "s": 13700, "text": "We built three different models based on non-negative matrix factorization, latent dirichlet allocation and TruncatedSVD." }, { "code": null, "e": 13931, "s": 13822, "text": "Lastly, we created generic functions to get topics and perform inference from the models that we have built." }, { "code": null, "e": 14005, "s": 13931, "text": "Thanks for reading this piece. Hope to see you again in the next article!" }, { "code": null, "e": 14088, "s": 14005, "text": "20 News Group DatasetStackOverflow — Numpy runtime issueSkLearn — Topic Extraction" }, { "code": null, "e": 14110, "s": 14088, "text": "20 News Group Dataset" }, { "code": null, "e": 14146, "s": 14110, "text": "StackOverflow — Numpy runtime issue" } ]
Use error bars in a Matplotlib scatter plot
17 Dec, 2020 Prerequisites: Matplotlib In this article, we will create a scatter plot with error bars using Matplotlib. Error bar charts are a great way to represent the variability in your data. It can be applied to graphs to provide an additional layer of detailed information on the presented data. Import required python library. Create data. Pass required values to errorbar() function Plot graph. Syntax: matplotlib.pyplot.errorbar(x, y, yerr=None, xerr=None, fmt=”, ecolor=None, elinewidth=None, capsize=None, barsabove=False, lolims=False, uplims=False, xlolims=False, xuplims=False, errorevery=1, capthick=None, \*, data=None, \*\*kwargs) Parameters: This method accept the following parameters that are described below: x, y: These parameters are the horizontal and vertical coordinates of the data points. fmt: This parameter is an optional parameter and it contains the string value. capsize: This parameter is also an optional parameter. And it is the length of the error bar caps in points with default value NONE. Implementation of the concept discussed above is given below: Example 1: Adding Some error in a ‘y’ value. Python3 import matplotlib.pyplot as plt a = [1, 3, 5, 7]b = [11, -2, 4, 19]plt.scatter(a, b) c = [1, 3, 2, 1] plt.errorbar(a, b, yerr=c, fmt="o")plt.show() Output: Example 2: Adding Some errors in the ‘x’ value. Python3 import matplotlib.pyplot as plt a = [1, 3, 5, 7]b = [11, -2, 4, 19]plt.scatter(a, b) c = [1, 3, 2, 1] plt.errorbar(a, b, xerr=c, fmt="o")plt.show() Output: Example 3: Adding error in x & y Python3 import matplotlib.pyplot as plt a = [1, 3, 5, 7]b = [11, -2, 4, 19]plt.scatter(a, b) c = [1, 3, 2, 1]d = [1, 3, 2, 1] # you can use color ="r" for red or skip to default as blueplt.errorbar(a, b, xerr=c, yerr=d, fmt="o", color="r") plt.show() Output: Example 4: Adding variable error in x and y. Python3 # importing matplotlibimport matplotlib.pyplot as plt # making a simple plotx = [1, 2, 3, 4, 5]y = [1, 2, 1, 2, 1] # creating errory_errormin = [0.1, 0.5, 0.9, 0.1, 0.9]y_errormax = [0.2, 0.4, 0.6, 0.4, 0.2] x_error = 0.5y_error = [y_errormin, y_errormax] # ploting graph# plt.plot(x, y)plt.errorbar(x, y, yerr=y_error, xerr=x_error, fmt='o') plt.show() 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 Create a directory in Python
[ { "code": null, "e": 53, "s": 25, "text": "\n17 Dec, 2020" }, { "code": null, "e": 79, "s": 53, "text": "Prerequisites: Matplotlib" }, { "code": null, "e": 343, "s": 79, "text": "In this article, we will create a scatter plot with error bars using Matplotlib. Error bar charts are a great way to represent the variability in your data. It can be applied to graphs to provide an additional layer of detailed information on the presented data. " }, { "code": null, "e": 375, "s": 343, "text": "Import required python library." }, { "code": null, "e": 388, "s": 375, "text": "Create data." }, { "code": null, "e": 432, "s": 388, "text": "Pass required values to errorbar() function" }, { "code": null, "e": 444, "s": 432, "text": "Plot graph." }, { "code": null, "e": 689, "s": 444, "text": "Syntax: matplotlib.pyplot.errorbar(x, y, yerr=None, xerr=None, fmt=”, ecolor=None, elinewidth=None, capsize=None, barsabove=False, lolims=False, uplims=False, xlolims=False, xuplims=False, errorevery=1, capthick=None, \\*, data=None, \\*\\*kwargs)" }, { "code": null, "e": 771, "s": 689, "text": "Parameters: This method accept the following parameters that are described below:" }, { "code": null, "e": 858, "s": 771, "text": "x, y: These parameters are the horizontal and vertical coordinates of the data points." }, { "code": null, "e": 937, "s": 858, "text": "fmt: This parameter is an optional parameter and it contains the string value." }, { "code": null, "e": 1070, "s": 937, "text": "capsize: This parameter is also an optional parameter. And it is the length of the error bar caps in points with default value NONE." }, { "code": null, "e": 1132, "s": 1070, "text": "Implementation of the concept discussed above is given below:" }, { "code": null, "e": 1177, "s": 1132, "text": "Example 1: Adding Some error in a ‘y’ value." }, { "code": null, "e": 1185, "s": 1177, "text": "Python3" }, { "code": "import matplotlib.pyplot as plt a = [1, 3, 5, 7]b = [11, -2, 4, 19]plt.scatter(a, b) c = [1, 3, 2, 1] plt.errorbar(a, b, yerr=c, fmt=\"o\")plt.show()", "e": 1336, "s": 1185, "text": null }, { "code": null, "e": 1344, "s": 1336, "text": "Output:" }, { "code": null, "e": 1392, "s": 1344, "text": "Example 2: Adding Some errors in the ‘x’ value." }, { "code": null, "e": 1400, "s": 1392, "text": "Python3" }, { "code": "import matplotlib.pyplot as plt a = [1, 3, 5, 7]b = [11, -2, 4, 19]plt.scatter(a, b) c = [1, 3, 2, 1] plt.errorbar(a, b, xerr=c, fmt=\"o\")plt.show()", "e": 1551, "s": 1400, "text": null }, { "code": null, "e": 1559, "s": 1551, "text": "Output:" }, { "code": null, "e": 1592, "s": 1559, "text": "Example 3: Adding error in x & y" }, { "code": null, "e": 1600, "s": 1592, "text": "Python3" }, { "code": "import matplotlib.pyplot as plt a = [1, 3, 5, 7]b = [11, -2, 4, 19]plt.scatter(a, b) c = [1, 3, 2, 1]d = [1, 3, 2, 1] # you can use color =\"r\" for red or skip to default as blueplt.errorbar(a, b, xerr=c, yerr=d, fmt=\"o\", color=\"r\") plt.show()", "e": 1849, "s": 1600, "text": null }, { "code": null, "e": 1857, "s": 1849, "text": "Output:" }, { "code": null, "e": 1902, "s": 1857, "text": "Example 4: Adding variable error in x and y." }, { "code": null, "e": 1910, "s": 1902, "text": "Python3" }, { "code": "# importing matplotlibimport matplotlib.pyplot as plt # making a simple plotx = [1, 2, 3, 4, 5]y = [1, 2, 1, 2, 1] # creating errory_errormin = [0.1, 0.5, 0.9, 0.1, 0.9]y_errormax = [0.2, 0.4, 0.6, 0.4, 0.2] x_error = 0.5y_error = [y_errormin, y_errormax] # ploting graph# plt.plot(x, y)plt.errorbar(x, y, yerr=y_error, xerr=x_error, fmt='o') plt.show()", "e": 2333, "s": 1910, "text": null }, { "code": null, "e": 2341, "s": 2333, "text": "Output:" }, { "code": null, "e": 2348, "s": 2341, "text": "Picked" }, { "code": null, "e": 2366, "s": 2348, "text": "Python-matplotlib" }, { "code": null, "e": 2373, "s": 2366, "text": "Python" }, { "code": null, "e": 2471, "s": 2373, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2503, "s": 2471, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 2530, "s": 2503, "text": "Python Classes and Objects" }, { "code": null, "e": 2551, "s": 2530, "text": "Python OOPs Concepts" }, { "code": null, "e": 2574, "s": 2551, "text": "Introduction To PYTHON" }, { "code": null, "e": 2605, "s": 2574, "text": "Python | os.path.join() method" }, { "code": null, "e": 2661, "s": 2605, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 2703, "s": 2661, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 2745, "s": 2703, "text": "Check if element exists in list in Python" }, { "code": null, "e": 2784, "s": 2745, "text": "Python | Get unique values from a list" } ]
UpdateView – Class Based Views Django
20 Jul, 2020 UpdateView refers to a view (logic) to update a particular instance of a table from the database with some extra details. It is used to update entries in the database, for example, updating an article at geeksforgeeks. We have already discussed basics of Update View in Update View – Function based Views Django. Class-based views provide an alternative way to implement views as Python objects instead of functions. They do not replace function-based views, but have certain differences and advantages when compared to function-based views: Organization of code related to specific HTTP methods (GET, POST, etc.) can be addressed by separate methods instead of conditional branching. Object oriented techniques such as mixins (multiple inheritance) can be used to factor code into reusable components. Class based views are simpler and efficient to manage than function-based views. A function based view with tons of lines of code can be converted into a class based views with few lines only. This is where Object Oriented Programming comes into impact. Illustration of How to create and use UpdateView 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 ? After you have a project and an app, let’s create a model of which we will be creating instances through our view. In geeks/models.py, # import the standard Django Model# from built-in libraryfrom django.db import models # declare a new model with a name "GeeksModel"class GeeksModel(models.Model): # fields of the model title = models.CharField(max_length = 200) description = models.TextField() # renames the instances of the model # with their title name def __str__(self): return self.title 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 Now let’s create some instances of this model using shell, run form bash, Python manage.py shell Enter following commands >>> from geeks.models import GeeksModel >>> GeeksModel.objects.create( title="title1", description="description1").save() >>> GeeksModel.objects.create( title="title2", description="description2").save() >>> GeeksModel.objects.create( title="title2", description="description2").save() Now we have everything ready for back end. Verify that instances have been created from http://localhost:8000/admin/geeks/geeksmodel/ Class Based Views automatically setup everything from A to Z. One just needs to specify which model to create UpdateView for, then Class based UpdateView will automatically try to find a template in app_name/modelname_form.html. In our case it is geeks/templates/geeks/geeksmodel_form.html. Let’s create our class based view. In geeks/views.py, # import generic UpdateViewfrom django.views.generic.edit import UpdateView # Relative import of GeeksModelfrom .models import GeeksModel class GeeksUpdateView(UpdateView): # specify the model you want to use model = GeeksModel # specify the fields fields = [ "title", "description" ] # can specify success url # url to redirect after successfully # updating details success_url ="/" Now create a url path to map the view. In geeks/urls.py, from django.urls import path # importing views from views..py from .views import GeeksUpdateView urlpatterns = [ # <pk> is identification for id field, # <slug> can also be used path('<pk>/update', GeeksUpdateView.as_view()), ] Create a template in templates/geeks/geeksmodel_form.html, <form method="post"> {% csrf_token %} {{ form.as_p }} <input type="submit" value="Save"> </form> Let’s check what is there on http://localhost:8000/1/update/ nidhi_biet Django-views Python Django Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n20 Jul, 2020" }, { "code": null, "e": 594, "s": 52, "text": "UpdateView refers to a view (logic) to update a particular instance of a table from the database with some extra details. It is used to update entries in the database, for example, updating an article at geeksforgeeks. We have already discussed basics of Update View in Update View – Function based Views Django. Class-based views provide an alternative way to implement views as Python objects instead of functions. They do not replace function-based views, but have certain differences and advantages when compared to function-based views:" }, { "code": null, "e": 737, "s": 594, "text": "Organization of code related to specific HTTP methods (GET, POST, etc.) can be addressed by separate methods instead of conditional branching." }, { "code": null, "e": 855, "s": 737, "text": "Object oriented techniques such as mixins (multiple inheritance) can be used to factor code into reusable components." }, { "code": null, "e": 1109, "s": 855, "text": "Class based views are simpler and efficient to manage than function-based views. A function based view with tons of lines of code can be converted into a class based views with few lines only. This is where Object Oriented Programming comes into impact." }, { "code": null, "e": 1242, "s": 1109, "text": "Illustration of How to create and use UpdateView using an Example. Consider a project named geeksforgeeks having an app named geeks." }, { "code": null, "e": 1329, "s": 1242, "text": "Refer to the following articles to check how to create a project and an app in Django." }, { "code": null, "e": 1380, "s": 1329, "text": "How to Create a Basic Project using MVT in Django?" }, { "code": null, "e": 1413, "s": 1380, "text": "How to Create an App in Django ?" }, { "code": null, "e": 1548, "s": 1413, "text": "After you have a project and an app, let’s create a model of which we will be creating instances through our view. In geeks/models.py," }, { "code": "# import the standard Django Model# from built-in libraryfrom django.db import models # declare a new model with a name \"GeeksModel\"class GeeksModel(models.Model): # fields of the model title = models.CharField(max_length = 200) description = models.TextField() # renames the instances of the model # with their title name def __str__(self): return self.title", "e": 1939, "s": 1548, "text": null }, { "code": null, "e": 2036, "s": 1939, "text": "After creating this model, we need to run two commands in order to create Database for the same." }, { "code": null, "e": 2094, "s": 2036, "text": "Python manage.py makemigrations\nPython manage.py migrate\n" }, { "code": null, "e": 2168, "s": 2094, "text": "Now let’s create some instances of this model using shell, run form bash," }, { "code": null, "e": 2191, "s": 2168, "text": "Python manage.py shell" }, { "code": null, "e": 2216, "s": 2191, "text": "Enter following commands" }, { "code": null, "e": 2641, "s": 2216, "text": ">>> from geeks.models import GeeksModel\n>>> GeeksModel.objects.create(\n title=\"title1\",\n description=\"description1\").save()\n>>> GeeksModel.objects.create(\n title=\"title2\",\n description=\"description2\").save()\n>>> GeeksModel.objects.create(\n title=\"title2\",\n description=\"description2\").save()\n" }, { "code": null, "e": 2775, "s": 2641, "text": "Now we have everything ready for back end. Verify that instances have been created from http://localhost:8000/admin/geeks/geeksmodel/" }, { "code": null, "e": 3120, "s": 2775, "text": "Class Based Views automatically setup everything from A to Z. One just needs to specify which model to create UpdateView for, then Class based UpdateView will automatically try to find a template in app_name/modelname_form.html. In our case it is geeks/templates/geeks/geeksmodel_form.html. Let’s create our class based view. In geeks/views.py," }, { "code": "# import generic UpdateViewfrom django.views.generic.edit import UpdateView # Relative import of GeeksModelfrom .models import GeeksModel class GeeksUpdateView(UpdateView): # specify the model you want to use model = GeeksModel # specify the fields fields = [ \"title\", \"description\" ] # can specify success url # url to redirect after successfully # updating details success_url =\"/\"", "e": 3551, "s": 3120, "text": null }, { "code": null, "e": 3608, "s": 3551, "text": "Now create a url path to map the view. In geeks/urls.py," }, { "code": "from django.urls import path # importing views from views..py from .views import GeeksUpdateView urlpatterns = [ # <pk> is identification for id field, # <slug> can also be used path('<pk>/update', GeeksUpdateView.as_view()), ] ", "e": 3853, "s": 3608, "text": null }, { "code": null, "e": 3912, "s": 3853, "text": "Create a template in templates/geeks/geeksmodel_form.html," }, { "code": "<form method=\"post\"> {% csrf_token %} {{ form.as_p }} <input type=\"submit\" value=\"Save\"> </form> ", "e": 4022, "s": 3912, "text": null }, { "code": null, "e": 4083, "s": 4022, "text": "Let’s check what is there on http://localhost:8000/1/update/" }, { "code": null, "e": 4094, "s": 4083, "text": "nidhi_biet" }, { "code": null, "e": 4107, "s": 4094, "text": "Django-views" }, { "code": null, "e": 4121, "s": 4107, "text": "Python Django" }, { "code": null, "e": 4128, "s": 4121, "text": "Python" } ]
What are the 4 steps to convert C program to Machine code?
A program contains a set of instructions which was written in a programming language. A program contains a set of instructions which was written in a programming language. The programmer’s job is to write and test the program. The programmer’s job is to write and test the program. The 4 steps to convert a ‘C’ program into machine language are &miuns;Writing and editing the programCompiling the programLinking the programExecuting the program The 4 steps to convert a ‘C’ program into machine language are &miuns; Writing and editing the program Compiling the program Linking the program Executing the program ‘Text editors’ are used to write programs. ‘Text editors’ are used to write programs. With the help of text editors, users can enter, change and store character data. With the help of text editors, users can enter, change and store character data. All special text editors are often included with a compiler. All special text editors are often included with a compiler. After writing the program, the file is saved to disk. After writing the program, the file is saved to disk. It is known as ‘source file’. It is known as ‘source file’. This file is input to the compiler. This file is input to the compiler. “Compiler” is a software that translates the source program into machine language. “Compiler” is a software that translates the source program into machine language. The ‘C’ compiler is divided into two separate programs.PreprocessorTranslator The ‘C’ compiler is divided into two separate programs. Preprocessor Translator Let us first see about Preprocessor − Preprocessor reads the source code and then prepares it for translator. Preprocessor reads the source code and then prepares it for translator. Preprocessor commands start with ‘#’ symbol. Preprocessor commands start with ‘#’ symbol. They tell the preprocessor to look for special code libraries and make substitutions. They tell the preprocessor to look for special code libraries and make substitutions. The result of preprocessing is known as ‘translation’ unit. The result of preprocessing is known as ‘translation’ unit. Translator’s work is to convert the program into machine language. Translator’s work is to convert the program into machine language. It reads the translation unit and results in ‘object module’. It reads the translation unit and results in ‘object module’. But it is not completely executable file because it does not have the ‘C’ and other functions included. But it is not completely executable file because it does not have the ‘C’ and other functions included. ‘Linker’ assembles I/O functions, some library functions and the functions that are part of source program into final executable program. ‘Linker’ assembles I/O functions, some library functions and the functions that are part of source program into final executable program. ‘Loader’ is the software that is ready for program execution into the memory. ‘Loader’ is the software that is ready for program execution into the memory. In the process of execution, the program reads the data from the user, processes the data and prepares the output. In the process of execution, the program reads the data from the user, processes the data and prepares the output. Following example is to find the average of 3 numbers − Live Demo #include<stdio.h> int main(){ int a,b,c,d; //declaring 4 variables float e; printf("Enter values of a,b,c:"); scanf("%d,%d,%d",&a,&b,&c); //read 3 input values from keyboard d=a+b+c; e=d/3; printf("Average=%f",e); // printing the result return 0; } Enter values of a,b,c :2,4,5 Average=3.000000 The following is to compute circumference of a circle − Live Demo #include <stdio.h> #define PI 3.1415 // defining PI value main (){ float c,r; printf("Enter radius of circle r="); scanf("%f",&r); c=2*PI*r; printf("Circumference of circle c=%f", c); } Enter radius of circle r=5.6 Circumference of circle c=35.184799
[ { "code": null, "e": 1273, "s": 1187, "text": "A program contains a set of instructions which was written in a programming language." }, { "code": null, "e": 1359, "s": 1273, "text": "A program contains a set of instructions which was written in a programming language." }, { "code": null, "e": 1414, "s": 1359, "text": "The programmer’s job is to write and test the program." }, { "code": null, "e": 1469, "s": 1414, "text": "The programmer’s job is to write and test the program." }, { "code": null, "e": 1632, "s": 1469, "text": "The 4 steps to convert a ‘C’ program into machine language are &miuns;Writing and editing the programCompiling the programLinking the programExecuting the program" }, { "code": null, "e": 1703, "s": 1632, "text": "The 4 steps to convert a ‘C’ program into machine language are &miuns;" }, { "code": null, "e": 1735, "s": 1703, "text": "Writing and editing the program" }, { "code": null, "e": 1757, "s": 1735, "text": "Compiling the program" }, { "code": null, "e": 1777, "s": 1757, "text": "Linking the program" }, { "code": null, "e": 1799, "s": 1777, "text": "Executing the program" }, { "code": null, "e": 1842, "s": 1799, "text": "‘Text editors’ are used to write programs." }, { "code": null, "e": 1885, "s": 1842, "text": "‘Text editors’ are used to write programs." }, { "code": null, "e": 1966, "s": 1885, "text": "With the help of text editors, users can enter, change and store character data." }, { "code": null, "e": 2047, "s": 1966, "text": "With the help of text editors, users can enter, change and store character data." }, { "code": null, "e": 2108, "s": 2047, "text": "All special text editors are often included with a compiler." }, { "code": null, "e": 2169, "s": 2108, "text": "All special text editors are often included with a compiler." }, { "code": null, "e": 2223, "s": 2169, "text": "After writing the program, the file is saved to disk." }, { "code": null, "e": 2277, "s": 2223, "text": "After writing the program, the file is saved to disk." }, { "code": null, "e": 2307, "s": 2277, "text": "It is known as ‘source file’." }, { "code": null, "e": 2337, "s": 2307, "text": "It is known as ‘source file’." }, { "code": null, "e": 2373, "s": 2337, "text": "This file is input to the compiler." }, { "code": null, "e": 2409, "s": 2373, "text": "This file is input to the compiler." }, { "code": null, "e": 2492, "s": 2409, "text": "“Compiler” is a software that translates the source program into machine language." }, { "code": null, "e": 2575, "s": 2492, "text": "“Compiler” is a software that translates the source program into machine language." }, { "code": null, "e": 2653, "s": 2575, "text": "The ‘C’ compiler is divided into two separate programs.PreprocessorTranslator" }, { "code": null, "e": 2709, "s": 2653, "text": "The ‘C’ compiler is divided into two separate programs." }, { "code": null, "e": 2722, "s": 2709, "text": "Preprocessor" }, { "code": null, "e": 2733, "s": 2722, "text": "Translator" }, { "code": null, "e": 2771, "s": 2733, "text": "Let us first see about Preprocessor −" }, { "code": null, "e": 2843, "s": 2771, "text": "Preprocessor reads the source code and then prepares it for translator." }, { "code": null, "e": 2915, "s": 2843, "text": "Preprocessor reads the source code and then prepares it for translator." }, { "code": null, "e": 2960, "s": 2915, "text": "Preprocessor commands start with ‘#’ symbol." }, { "code": null, "e": 3005, "s": 2960, "text": "Preprocessor commands start with ‘#’ symbol." }, { "code": null, "e": 3091, "s": 3005, "text": "They tell the preprocessor to look for special code libraries and make substitutions." }, { "code": null, "e": 3177, "s": 3091, "text": "They tell the preprocessor to look for special code libraries and make substitutions." }, { "code": null, "e": 3237, "s": 3177, "text": "The result of preprocessing is known as ‘translation’ unit." }, { "code": null, "e": 3297, "s": 3237, "text": "The result of preprocessing is known as ‘translation’ unit." }, { "code": null, "e": 3364, "s": 3297, "text": "Translator’s work is to convert the program into machine language." }, { "code": null, "e": 3431, "s": 3364, "text": "Translator’s work is to convert the program into machine language." }, { "code": null, "e": 3493, "s": 3431, "text": "It reads the translation unit and results in ‘object module’." }, { "code": null, "e": 3555, "s": 3493, "text": "It reads the translation unit and results in ‘object module’." }, { "code": null, "e": 3659, "s": 3555, "text": "But it is not completely executable file because it does not have the ‘C’ and other functions included." }, { "code": null, "e": 3763, "s": 3659, "text": "But it is not completely executable file because it does not have the ‘C’ and other functions included." }, { "code": null, "e": 3901, "s": 3763, "text": "‘Linker’ assembles I/O functions, some library functions and the functions that are part of source program into final executable program." }, { "code": null, "e": 4039, "s": 3901, "text": "‘Linker’ assembles I/O functions, some library functions and the functions that are part of source program into final executable program." }, { "code": null, "e": 4117, "s": 4039, "text": "‘Loader’ is the software that is ready for program execution into the memory." }, { "code": null, "e": 4195, "s": 4117, "text": "‘Loader’ is the software that is ready for program execution into the memory." }, { "code": null, "e": 4310, "s": 4195, "text": "In the process of execution, the program reads the data from the user, processes the data and prepares the output." }, { "code": null, "e": 4425, "s": 4310, "text": "In the process of execution, the program reads the data from the user, processes the data and prepares the output." }, { "code": null, "e": 4481, "s": 4425, "text": "Following example is to find the average of 3 numbers −" }, { "code": null, "e": 4492, "s": 4481, "text": " Live Demo" }, { "code": null, "e": 4765, "s": 4492, "text": "#include<stdio.h>\nint main(){\n int a,b,c,d; //declaring 4 variables\n float e;\n printf(\"Enter values of a,b,c:\");\n scanf(\"%d,%d,%d\",&a,&b,&c); //read 3 input values from keyboard\n d=a+b+c;\n e=d/3;\n printf(\"Average=%f\",e); // printing the result\n return 0;\n}" }, { "code": null, "e": 4811, "s": 4765, "text": "Enter values of a,b,c :2,4,5\nAverage=3.000000" }, { "code": null, "e": 4867, "s": 4811, "text": "The following is to compute circumference of a circle −" }, { "code": null, "e": 4878, "s": 4867, "text": " Live Demo" }, { "code": null, "e": 5079, "s": 4878, "text": "#include <stdio.h>\n#define PI 3.1415 // defining PI value\nmain (){\n float c,r;\n printf(\"Enter radius of circle r=\");\n scanf(\"%f\",&r);\n c=2*PI*r;\n printf(\"Circumference of circle c=%f\", c);\n}" }, { "code": null, "e": 5144, "s": 5079, "text": "Enter radius of circle r=5.6\nCircumference of circle c=35.184799" } ]
Map containsKey() method in Java with Examples
31 Dec, 2018 The java.util.Map.containsKey() method is used to check whether a particular key is being mapped into the Map or not. It takes the key element as a parameter and returns True if that element is mapped in the map. Syntax: boolean containsKey(key_element) Parameters: The method takes just one parameter key_element that refers to the key whose mapping is supposed to be checked inside a map. Return Value: The method returns boolean true if the presence of the key is detected else false . Below programs are used to illustrate the working of java.util.Map.containsKey() Method: Program 1: Mapping String Values to Integer Keys. // Java code to illustrate the containsKey() methodimport java.util.*; public class Map_Demo { public static void main(String[] args) { // Creating an empty Map Map<Integer, String> map = new HashMap<Integer, String>(); // Mapping string values to int keys map.put(10, "Geeks"); map.put(15, "4"); map.put(20, "Geeks"); map.put(25, "Welcomes"); map.put(30, "You"); // Displaying the Map System.out.println("Initial Mappings are: " + map); // Checking for the key_element '20' System.out.println("Is the key '20' present? " + map.containsKey(20)); // Checking for the key_element '5' System.out.println("Is the key '5' present? " + map.containsKey(5)); }} Initial Mappings are: {20=Geeks, 25=Welcomes, 10=Geeks, 30=You, 15=4} Is the key '20' present? true Is the key '5' present? false Program 2: Mapping Integer Values to String Keys. // Java code to illustrate the containsKey() method import java.util.*; public class Map_Demo { public static void main(String[] args) { // Creating an empty Map Map<String, Integer> map = new HashMap<String, Integer>(); // Mapping int values to string keys map.put("Geeks", 10); map.put("4", 15); map.put("Geeks", 20); map.put("Welcomes", 25); map.put("You", 30); // Displaying the Map System.out.println("Initial Mappings are: " + map); // Checking for the key_element 'Welcomes' System.out.println("Is the key 'Welcomes' present? " + map.containsKey("Welcomes")); // Checking for the key_element 'World' System.out.println("Is the key 'World' present? " + map.containsKey("World")); }} Initial Mappings are: {4=15, Geeks=20, You=30, Welcomes=25} Is the key 'Welcomes' present? true Is the key 'World' present? false Note: The same operation can be performed with any type of Mappings with variation and combination of different data types. Reference: https://docs.oracle.com/javase/7/docs/api/java/util/Map.html#containsKey(java.lang.Object) Java-Collections Java-Functions java-map Java Java Java-Collections Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Stream In Java Introduction to Java Constructors in Java Exceptions in Java Generics in Java Functional Interfaces in Java Java Programming Examples Strings in Java Differences between JDK, JRE and JVM Abstraction in Java
[ { "code": null, "e": 28, "s": 0, "text": "\n31 Dec, 2018" }, { "code": null, "e": 241, "s": 28, "text": "The java.util.Map.containsKey() method is used to check whether a particular key is being mapped into the Map or not. It takes the key element as a parameter and returns True if that element is mapped in the map." }, { "code": null, "e": 249, "s": 241, "text": "Syntax:" }, { "code": null, "e": 282, "s": 249, "text": "boolean containsKey(key_element)" }, { "code": null, "e": 419, "s": 282, "text": "Parameters: The method takes just one parameter key_element that refers to the key whose mapping is supposed to be checked inside a map." }, { "code": null, "e": 517, "s": 419, "text": "Return Value: The method returns boolean true if the presence of the key is detected else false ." }, { "code": null, "e": 606, "s": 517, "text": "Below programs are used to illustrate the working of java.util.Map.containsKey() Method:" }, { "code": null, "e": 656, "s": 606, "text": "Program 1: Mapping String Values to Integer Keys." }, { "code": "// Java code to illustrate the containsKey() methodimport java.util.*; public class Map_Demo { public static void main(String[] args) { // Creating an empty Map Map<Integer, String> map = new HashMap<Integer, String>(); // Mapping string values to int keys map.put(10, \"Geeks\"); map.put(15, \"4\"); map.put(20, \"Geeks\"); map.put(25, \"Welcomes\"); map.put(30, \"You\"); // Displaying the Map System.out.println(\"Initial Mappings are: \" + map); // Checking for the key_element '20' System.out.println(\"Is the key '20' present? \" + map.containsKey(20)); // Checking for the key_element '5' System.out.println(\"Is the key '5' present? \" + map.containsKey(5)); }}", "e": 1480, "s": 656, "text": null }, { "code": null, "e": 1611, "s": 1480, "text": "Initial Mappings are: {20=Geeks, 25=Welcomes, 10=Geeks, 30=You, 15=4}\nIs the key '20' present? true\nIs the key '5' present? false\n" }, { "code": null, "e": 1661, "s": 1611, "text": "Program 2: Mapping Integer Values to String Keys." }, { "code": "// Java code to illustrate the containsKey() method import java.util.*; public class Map_Demo { public static void main(String[] args) { // Creating an empty Map Map<String, Integer> map = new HashMap<String, Integer>(); // Mapping int values to string keys map.put(\"Geeks\", 10); map.put(\"4\", 15); map.put(\"Geeks\", 20); map.put(\"Welcomes\", 25); map.put(\"You\", 30); // Displaying the Map System.out.println(\"Initial Mappings are: \" + map); // Checking for the key_element 'Welcomes' System.out.println(\"Is the key 'Welcomes' present? \" + map.containsKey(\"Welcomes\")); // Checking for the key_element 'World' System.out.println(\"Is the key 'World' present? \" + map.containsKey(\"World\")); }}", "e": 2519, "s": 1661, "text": null }, { "code": null, "e": 2650, "s": 2519, "text": "Initial Mappings are: {4=15, Geeks=20, You=30, Welcomes=25}\nIs the key 'Welcomes' present? true\nIs the key 'World' present? false\n" }, { "code": null, "e": 2774, "s": 2650, "text": "Note: The same operation can be performed with any type of Mappings with variation and combination of different data types." }, { "code": null, "e": 2876, "s": 2774, "text": "Reference: https://docs.oracle.com/javase/7/docs/api/java/util/Map.html#containsKey(java.lang.Object)" }, { "code": null, "e": 2893, "s": 2876, "text": "Java-Collections" }, { "code": null, "e": 2908, "s": 2893, "text": "Java-Functions" }, { "code": null, "e": 2917, "s": 2908, "text": "java-map" }, { "code": null, "e": 2922, "s": 2917, "text": "Java" }, { "code": null, "e": 2927, "s": 2922, "text": "Java" }, { "code": null, "e": 2944, "s": 2927, "text": "Java-Collections" }, { "code": null, "e": 3042, "s": 2944, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3057, "s": 3042, "text": "Stream In Java" }, { "code": null, "e": 3078, "s": 3057, "text": "Introduction to Java" }, { "code": null, "e": 3099, "s": 3078, "text": "Constructors in Java" }, { "code": null, "e": 3118, "s": 3099, "text": "Exceptions in Java" }, { "code": null, "e": 3135, "s": 3118, "text": "Generics in Java" }, { "code": null, "e": 3165, "s": 3135, "text": "Functional Interfaces in Java" }, { "code": null, "e": 3191, "s": 3165, "text": "Java Programming Examples" }, { "code": null, "e": 3207, "s": 3191, "text": "Strings in Java" }, { "code": null, "e": 3244, "s": 3207, "text": "Differences between JDK, JRE and JVM" } ]
Insertion and Deletion in Heaps
14 Jun, 2022 Deletion in Heap Given a Binary Heap and an element present in the given Heap. The task is to delete an element from this Heap. The standard deletion operation on Heap is to delete the element present at the root node of the Heap. That is if it is a Max Heap, the standard deletion operation will delete the maximum element and if it is a Min heap, it will delete the minimum element. Process of Deletion: Since deleting an element at any intermediary position in the heap can be costly, so we can simply replace the element to be deleted by the last element and delete the last element of the Heap. Replace the root or element to be deleted by the last element. Delete the last element from the Heap. Since, the last element is now placed at the position of the root node. So, it may not follow the heap property. Therefore, heapify the last node placed at the position of root. Illustration: Suppose the Heap is a Max-Heap as: 10 / \ 5 3 / \ 2 4 The element to be deleted is root, i.e. 10. Process: The last element is 4. Step 1: Replace the last element with root, and delete it. 4 / \ 5 3 / 2 Step 2: Heapify root. Final Heap: 5 / \ 4 3 / 2 Implementation: C++ Java Python3 C# Javascript // C++ program for implement deletion in Heaps #include <iostream> using namespace std; // To heapify a subtree rooted with node i which is// an index of arr[] and n is the size of heapvoid heapify(int arr[], int n, int i){ int largest = i; // Initialize largest as root int l = 2 * i + 1; // left = 2*i + 1 int r = 2 * i + 2; // right = 2*i + 2 // If left child is larger than root if (l < n && arr[l] > arr[largest]) largest = l; // If right child is larger than largest so far if (r < n && arr[r] > arr[largest]) largest = r; // If largest is not root if (largest != i) { swap(arr[i], arr[largest]); // Recursively heapify the affected sub-tree heapify(arr, n, largest); }} // Function to delete the root from Heapvoid deleteRoot(int arr[], int& n){ // Get the last element int lastElement = arr[n - 1]; // Replace root with last element arr[0] = lastElement; // Decrease size of heap by 1 n = n - 1; // heapify the root node heapify(arr, n, 0);} /* A utility function to print array of size n */void printArray(int arr[], int n){ for (int i = 0; i < n; ++i) cout << arr[i] << " "; cout << "\n";} // Driver Codeint main(){ // Array representation of Max-Heap // 10 // / \ // 5 3 // / \ // 2 4 int arr[] = { 10, 5, 3, 2, 4 }; int n = sizeof(arr) / sizeof(arr[0]); deleteRoot(arr, n); printArray(arr, n); return 0;} // Java program for implement deletion in Heapspublic class deletionHeap { // To heapify a subtree rooted with node i which is // an index in arr[].Nn is size of heap static void heapify(int arr[], int n, int i) { int largest = i; // Initialize largest as root int l = 2 * i + 1; // left = 2*i + 1 int r = 2 * i + 2; // right = 2*i + 2 // If left child is larger than root if (l < n && arr[l] > arr[largest]) largest = l; // If right child is larger than largest so far if (r < n && arr[r] > arr[largest]) largest = r; // If largest is not root if (largest != i) { int swap = arr[i]; arr[i] = arr[largest]; arr[largest] = swap; // Recursively heapify the affected sub-tree heapify(arr, n, largest); } } // Function to delete the root from Heap static int deleteRoot(int arr[], int n) { // Get the last element int lastElement = arr[n - 1]; // Replace root with first element arr[0] = lastElement; // Decrease size of heap by 1 n = n - 1; // heapify the root node heapify(arr, n, 0); // return new size of Heap return n; } /* A utility function to print array of size N */ static void printArray(int arr[], int n) { for (int i = 0; i < n; ++i) System.out.print(arr[i] + " "); System.out.println(); } // Driver Code public static void main(String args[]) { // Array representation of Max-Heap // 10 // / \ // 5 3 // / \ // 2 4 int arr[] = { 10, 5, 3, 2, 4 }; int n = arr.length; n = deleteRoot(arr, n); printArray(arr, n); }} # Python 3 program for implement deletion in Heaps # To heapify a subtree rooted with node i which is# an index of arr[] and n is the size of heapdef heapify(arr, n, i): largest = i #Initialize largest as root l = 2 * i + 1 # left = 2*i + 1 r = 2 * i + 2 # right = 2*i + 2 #If left child is larger than root if (l < n and arr[l] > arr[largest]): largest = l #If right child is larger than largest so far if (r < n and arr[r] > arr[largest]): largest = r # If largest is not root if (largest != i): arr[i],arr[largest]=arr[largest],arr[i] #Recursively heapify the affected sub-tree heapify(arr, n, largest) #Function to delete the root from Heapdef deleteRoot(arr): global n # Get the last element lastElement = arr[n - 1] # Replace root with last element arr[0] = lastElement # Decrease size of heap by 1 n = n - 1 # heapify the root node heapify(arr, n, 0) # A utility function to print array of size ndef printArray(arr, n): for i in range(n): print(arr[i],end=" ") print() # Driver Codeif __name__ == '__main__': # Array representation of Max-Heap # 10 # / \ # 5 3 # / \ # 2 4 arr = [ 10, 5, 3, 2, 4 ] n = len(arr) deleteRoot(arr) printArray(arr, n) # This code is contributed by Rajat Kumar. // C# program for implement deletion in Heapsusing System; public class deletionHeap{ // To heapify a subtree rooted with node i which is // an index in arr[].Nn is size of heap static void heapify(int []arr, int n, int i) { int largest = i; // Initialize largest as root int l = 2 * i + 1; // left = 2*i + 1 int r = 2 * i + 2; // right = 2*i + 2 // If left child is larger than root if (l < n && arr[l] > arr[largest]) largest = l; // If right child is larger than largest so far if (r < n && arr[r] > arr[largest]) largest = r; // If largest is not root if (largest != i) { int swap = arr[i]; arr[i] = arr[largest]; arr[largest] = swap; // Recursively heapify the affected sub-tree heapify(arr, n, largest); } } // Function to delete the root from Heap static int deleteRoot(int []arr, int n) { // Get the last element int lastElement = arr[n - 1]; // Replace root with first element arr[0] = lastElement; // Decrease size of heap by 1 n = n - 1; // heapify the root node heapify(arr, n, 0); // return new size of Heap return n; } /* A utility function to print array of size N */ static void printArray(int []arr, int n) { for (int i = 0; i < n; ++i) Console.Write(arr[i] + " "); Console.WriteLine(); } // Driver Code public static void Main() { // Array representation of Max-Heap // 10 // / \ // 5 3 // / \ // 2 4 int []arr = { 10, 5, 3, 2, 4 }; int n = arr.Length; n = deleteRoot(arr, n); printArray(arr, n); }} // This code is contributed by Ryuga <script> // Javascript program for implement deletion in Heaps // To heapify a subtree rooted with node i which is // an index in arr[].Nn is size of heap function heapify(arr, n, i) { let largest = i; // Initialize largest as root let l = 2 * i + 1; // left = 2*i + 1 let r = 2 * i + 2; // right = 2*i + 2 // If left child is larger than root if (l < n && arr[l] > arr[largest]) largest = l; // If right child is larger than largest so far if (r < n && arr[r] > arr[largest]) largest = r; // If largest is not root if (largest != i) { let swap = arr[i]; arr[i] = arr[largest]; arr[largest] = swap; // Recursively heapify the affected sub-tree heapify(arr, n, largest); } } // Function to delete the root from Heap function deleteRoot(arr, n) { // Get the last element let lastElement = arr[n - 1]; // Replace root with first element arr[0] = lastElement; // Decrease size of heap by 1 n = n - 1; // heapify the root node heapify(arr, n, 0); // return new size of Heap return n; } /* A utility function to print array of size N */ function printArray(arr, n) { for (let i = 0; i < n; ++i) document.write(arr[i] + " "); document.write("</br>"); } let arr = [ 10, 5, 3, 2, 4 ]; let n = arr.length; n = deleteRoot(arr, n); printArray(arr, n); // This code is contributed by divyeshrabdiya07.</script> 5 4 3 2 Time complexity: O(logn) where n is no of elements in the heap Auxiliary Space: O(n) Insertion in Heaps The insertion operation is also similar to that of the deletion process. Given a Binary Heap and a new element to be added to this Heap. The task is to insert the new element to the Heap maintaining the properties of Heap. Process of Insertion: Elements can be inserted to the heap following a similar approach as discussed above for deletion. The idea is to: First increase the heap size by 1, so that it can store the new element. Insert the new element at the end of the Heap. This newly inserted element may distort the properties of Heap for its parents. So, in order to keep the properties of Heap, heapify this newly inserted element following a bottom-up approach. Illustration: Suppose the Heap is a Max-Heap as: 10 / \ 5 3 / \ 2 4 The new element to be inserted is 15. Process: Step 1: Insert the new element at the end. 10 / \ 5 3 / \ / 2 4 15 Step 2: Heapify the new element following bottom-up approach. -> 15 is more than its parent 3, swap them. 10 / \ 5 15 / \ / 2 4 3 -> 15 is again more than its parent 10, swap them. 15 / \ 5 10 / \ / 2 4 3 Therefore, the final heap after insertion is: 15 / \ 5 10 / \ / 2 4 3 Implementation: C++ Java Python3 // C++ program to insert new element to Heap #include <iostream>using namespace std; #define MAX 1000 // Max size of Heap // Function to heapify ith node in a Heap// of size n following a Bottom-up approachvoid heapify(int arr[], int n, int i){ // Find parent int parent = (i - 1) / 2; if (arr[parent] > 0) { // For Max-Heap // If current node is greater than its parent // Swap both of them and call heapify again // for the parent if (arr[i] > arr[parent]) { swap(arr[i], arr[parent]); // Recursively heapify the parent node heapify(arr, n, parent); } }} // Function to insert a new node to the Heapvoid insertNode(int arr[], int& n, int Key){ // Increase the size of Heap by 1 n = n + 1; // Insert the element at end of Heap arr[n - 1] = Key; // Heapify the new node following a // Bottom-up approach heapify(arr, n, n - 1);} // A utility function to print array of size nvoid printArray(int arr[], int n){ for (int i = 0; i < n; ++i) cout << arr[i] << " "; cout << "\n";} // Driver Codeint main(){ // Array representation of Max-Heap // 10 // / \ // 5 3 // / \ // 2 4 int arr[MAX] = { 10, 5, 3, 2, 4 }; int n = 5; int key = 15; insertNode(arr, n, key); printArray(arr, n); // Final Heap will be: // 15 // / \ // 5 10 // / \ / // 2 4 3 return 0;} // Java program for implementing insertion in Heapspublic class insertionHeap { // Function to heapify ith node in a Heap // of size n following a Bottom-up approach static void heapify(int[] arr, int n, int i) { // Find parent int parent = (i - 1) / 2; if (arr[parent] > 0) { // For Max-Heap // If current node is greater than its parent // Swap both of them and call heapify again // for the parent if (arr[i] > arr[parent]) { // swap arr[i] and arr[parent] int temp = arr[i]; arr[i] = arr[parent]; arr[parent] = temp; // Recursively heapify the parent node heapify(arr, n, parent); } } } // Function to insert a new node to the heap. static int insertNode(int[] arr, int n, int Key) { // Increase the size of Heap by 1 n = n + 1; // Insert the element at end of Heap arr[n - 1] = Key; // Heapify the new node following a // Bottom-up approach heapify(arr, n, n - 1); // return new size of Heap return n; } /* A utility function to print array of size n */ static void printArray(int[] arr, int n) { for (int i = 0; i < n; ++i) System.out.println(arr[i] + " "); System.out.println(); } // Driver Code public static void main(String args[]) { // Array representation of Max-Heap // 10 // / \ // 5 3 // / \ // 2 4 // maximum size of the array int MAX = 1000; int[] arr = new int[MAX]; // initializing some values arr[0] = 10; arr[1] = 5; arr[2] = 3; arr[3] = 2; arr[4] = 4; // Current size of the array int n = 5; // the element to be inserted int Key = 15; // The function inserts the new element to the heap and // returns the new size of the array n = insertNode(arr, n, Key); printArray(arr, n); // Final Heap will be: // 15 // / \ // 5 10 // / \ / // 2 4 3 }} // The code is contributed by Gautam goel # program to insert new element to Heap # Function to heapify ith node in a Heap# of size n following a Bottom-up approach def heapify(arr, n, i): parent = int(((i-1)/2)) # For Max-Heap # If current node is greater than its parent # Swap both of them and call heapify again # for the parent if arr[parent] > 0: if arr[i] > arr[parent]: arr[i], arr[parent] = arr[parent], arr[i] # Recursively heapify the parent node heapify(arr, n, parent)# Function to insert a new node to the Heap def insertNode(arr, key): global n # Increase the size of Heap by 1 n += 1 # Insert the element at end of Heap arr.append(key) # Heapify the new node following a # Bottom-up approach heapify(arr, n, n-1)# A utility function to print array of size n def printArr(arr, n): for i in range(n): print(arr[i], end=" ") # Driver Code# Array representation of Max-Heap''' 10 / \ 5 3 / \ 2 4'''arr = [10, 5, 3, 2, 4, 1, 7]n = 7key = 15insertNode(arr, key)printArr(arr, n)# Final Heap will be:''' 15 / \ 5 10 / \ /2 4 3 Code is written by Rajat Kumar....''' 15 5 10 2 4 3 Time Complexity: O(n) Auxiliary Space: O(n) ankthon YashJain25 ultrainstinct divyeshrabadiya07 dsc13103 amartyaghoshgfg rajatkumargla19 gautamgoel962 polymatir3j Data Structures Heap Data Structures Heap Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. DSA Sheet by Love Babbar SDE SHEET - A Complete Guide for SDE Preparation Introduction to Data Structures What is Hashing | A Complete Tutorial Introduction to Tree Data Structure K'th Smallest/Largest Element in Unsorted Array | Set 1 Introduction to Data Structures Huffman Coding | Greedy Algo-3 Sliding Window Maximum (Maximum of all subarrays of size k) k largest(or smallest) elements in an array
[ { "code": null, "e": 52, "s": 24, "text": "\n14 Jun, 2022" }, { "code": null, "e": 69, "s": 52, "text": "Deletion in Heap" }, { "code": null, "e": 182, "s": 69, "text": "Given a Binary Heap and an element present in the given Heap. The task is to delete an element from this Heap. " }, { "code": null, "e": 439, "s": 182, "text": "The standard deletion operation on Heap is to delete the element present at the root node of the Heap. That is if it is a Max Heap, the standard deletion operation will delete the maximum element and if it is a Min heap, it will delete the minimum element." }, { "code": null, "e": 655, "s": 439, "text": "Process of Deletion: Since deleting an element at any intermediary position in the heap can be costly, so we can simply replace the element to be deleted by the last element and delete the last element of the Heap. " }, { "code": null, "e": 718, "s": 655, "text": "Replace the root or element to be deleted by the last element." }, { "code": null, "e": 757, "s": 718, "text": "Delete the last element from the Heap." }, { "code": null, "e": 935, "s": 757, "text": "Since, the last element is now placed at the position of the root node. So, it may not follow the heap property. Therefore, heapify the last node placed at the position of root." }, { "code": null, "e": 951, "s": 935, "text": "Illustration: " }, { "code": null, "e": 1288, "s": 951, "text": "Suppose the Heap is a Max-Heap as:\n 10\n / \\\n 5 3\n / \\\n 2 4\n\nThe element to be deleted is root, i.e. 10.\n\nProcess:\nThe last element is 4.\n\nStep 1: Replace the last element with root, and delete it.\n 4\n / \\\n 5 3\n / \n 2 \n\nStep 2: Heapify root.\nFinal Heap:\n 5\n / \\\n 4 3\n / \n 2 " }, { "code": null, "e": 1306, "s": 1288, "text": "Implementation: " }, { "code": null, "e": 1310, "s": 1306, "text": "C++" }, { "code": null, "e": 1315, "s": 1310, "text": "Java" }, { "code": null, "e": 1323, "s": 1315, "text": "Python3" }, { "code": null, "e": 1326, "s": 1323, "text": "C#" }, { "code": null, "e": 1337, "s": 1326, "text": "Javascript" }, { "code": "// C++ program for implement deletion in Heaps #include <iostream> using namespace std; // To heapify a subtree rooted with node i which is// an index of arr[] and n is the size of heapvoid heapify(int arr[], int n, int i){ int largest = i; // Initialize largest as root int l = 2 * i + 1; // left = 2*i + 1 int r = 2 * i + 2; // right = 2*i + 2 // If left child is larger than root if (l < n && arr[l] > arr[largest]) largest = l; // If right child is larger than largest so far if (r < n && arr[r] > arr[largest]) largest = r; // If largest is not root if (largest != i) { swap(arr[i], arr[largest]); // Recursively heapify the affected sub-tree heapify(arr, n, largest); }} // Function to delete the root from Heapvoid deleteRoot(int arr[], int& n){ // Get the last element int lastElement = arr[n - 1]; // Replace root with last element arr[0] = lastElement; // Decrease size of heap by 1 n = n - 1; // heapify the root node heapify(arr, n, 0);} /* A utility function to print array of size n */void printArray(int arr[], int n){ for (int i = 0; i < n; ++i) cout << arr[i] << \" \"; cout << \"\\n\";} // Driver Codeint main(){ // Array representation of Max-Heap // 10 // / \\ // 5 3 // / \\ // 2 4 int arr[] = { 10, 5, 3, 2, 4 }; int n = sizeof(arr) / sizeof(arr[0]); deleteRoot(arr, n); printArray(arr, n); return 0;}", "e": 2816, "s": 1337, "text": null }, { "code": "// Java program for implement deletion in Heapspublic class deletionHeap { // To heapify a subtree rooted with node i which is // an index in arr[].Nn is size of heap static void heapify(int arr[], int n, int i) { int largest = i; // Initialize largest as root int l = 2 * i + 1; // left = 2*i + 1 int r = 2 * i + 2; // right = 2*i + 2 // If left child is larger than root if (l < n && arr[l] > arr[largest]) largest = l; // If right child is larger than largest so far if (r < n && arr[r] > arr[largest]) largest = r; // If largest is not root if (largest != i) { int swap = arr[i]; arr[i] = arr[largest]; arr[largest] = swap; // Recursively heapify the affected sub-tree heapify(arr, n, largest); } } // Function to delete the root from Heap static int deleteRoot(int arr[], int n) { // Get the last element int lastElement = arr[n - 1]; // Replace root with first element arr[0] = lastElement; // Decrease size of heap by 1 n = n - 1; // heapify the root node heapify(arr, n, 0); // return new size of Heap return n; } /* A utility function to print array of size N */ static void printArray(int arr[], int n) { for (int i = 0; i < n; ++i) System.out.print(arr[i] + \" \"); System.out.println(); } // Driver Code public static void main(String args[]) { // Array representation of Max-Heap // 10 // / \\ // 5 3 // / \\ // 2 4 int arr[] = { 10, 5, 3, 2, 4 }; int n = arr.length; n = deleteRoot(arr, n); printArray(arr, n); }}", "e": 4629, "s": 2816, "text": null }, { "code": "# Python 3 program for implement deletion in Heaps # To heapify a subtree rooted with node i which is# an index of arr[] and n is the size of heapdef heapify(arr, n, i): largest = i #Initialize largest as root l = 2 * i + 1 # left = 2*i + 1 r = 2 * i + 2 # right = 2*i + 2 #If left child is larger than root if (l < n and arr[l] > arr[largest]): largest = l #If right child is larger than largest so far if (r < n and arr[r] > arr[largest]): largest = r # If largest is not root if (largest != i): arr[i],arr[largest]=arr[largest],arr[i] #Recursively heapify the affected sub-tree heapify(arr, n, largest) #Function to delete the root from Heapdef deleteRoot(arr): global n # Get the last element lastElement = arr[n - 1] # Replace root with last element arr[0] = lastElement # Decrease size of heap by 1 n = n - 1 # heapify the root node heapify(arr, n, 0) # A utility function to print array of size ndef printArray(arr, n): for i in range(n): print(arr[i],end=\" \") print() # Driver Codeif __name__ == '__main__': # Array representation of Max-Heap # 10 # / \\ # 5 3 # / \\ # 2 4 arr = [ 10, 5, 3, 2, 4 ] n = len(arr) deleteRoot(arr) printArray(arr, n) # This code is contributed by Rajat Kumar.", "e": 6000, "s": 4629, "text": null }, { "code": "// C# program for implement deletion in Heapsusing System; public class deletionHeap{ // To heapify a subtree rooted with node i which is // an index in arr[].Nn is size of heap static void heapify(int []arr, int n, int i) { int largest = i; // Initialize largest as root int l = 2 * i + 1; // left = 2*i + 1 int r = 2 * i + 2; // right = 2*i + 2 // If left child is larger than root if (l < n && arr[l] > arr[largest]) largest = l; // If right child is larger than largest so far if (r < n && arr[r] > arr[largest]) largest = r; // If largest is not root if (largest != i) { int swap = arr[i]; arr[i] = arr[largest]; arr[largest] = swap; // Recursively heapify the affected sub-tree heapify(arr, n, largest); } } // Function to delete the root from Heap static int deleteRoot(int []arr, int n) { // Get the last element int lastElement = arr[n - 1]; // Replace root with first element arr[0] = lastElement; // Decrease size of heap by 1 n = n - 1; // heapify the root node heapify(arr, n, 0); // return new size of Heap return n; } /* A utility function to print array of size N */ static void printArray(int []arr, int n) { for (int i = 0; i < n; ++i) Console.Write(arr[i] + \" \"); Console.WriteLine(); } // Driver Code public static void Main() { // Array representation of Max-Heap // 10 // / \\ // 5 3 // / \\ // 2 4 int []arr = { 10, 5, 3, 2, 4 }; int n = arr.Length; n = deleteRoot(arr, n); printArray(arr, n); }} // This code is contributed by Ryuga", "e": 7838, "s": 6000, "text": null }, { "code": "<script> // Javascript program for implement deletion in Heaps // To heapify a subtree rooted with node i which is // an index in arr[].Nn is size of heap function heapify(arr, n, i) { let largest = i; // Initialize largest as root let l = 2 * i + 1; // left = 2*i + 1 let r = 2 * i + 2; // right = 2*i + 2 // If left child is larger than root if (l < n && arr[l] > arr[largest]) largest = l; // If right child is larger than largest so far if (r < n && arr[r] > arr[largest]) largest = r; // If largest is not root if (largest != i) { let swap = arr[i]; arr[i] = arr[largest]; arr[largest] = swap; // Recursively heapify the affected sub-tree heapify(arr, n, largest); } } // Function to delete the root from Heap function deleteRoot(arr, n) { // Get the last element let lastElement = arr[n - 1]; // Replace root with first element arr[0] = lastElement; // Decrease size of heap by 1 n = n - 1; // heapify the root node heapify(arr, n, 0); // return new size of Heap return n; } /* A utility function to print array of size N */ function printArray(arr, n) { for (let i = 0; i < n; ++i) document.write(arr[i] + \" \"); document.write(\"</br>\"); } let arr = [ 10, 5, 3, 2, 4 ]; let n = arr.length; n = deleteRoot(arr, n); printArray(arr, n); // This code is contributed by divyeshrabdiya07.</script>", "e": 9482, "s": 7838, "text": null }, { "code": null, "e": 9490, "s": 9482, "text": "5 4 3 2" }, { "code": null, "e": 9555, "s": 9492, "text": "Time complexity: O(logn) where n is no of elements in the heap" }, { "code": null, "e": 9577, "s": 9555, "text": "Auxiliary Space: O(n)" }, { "code": null, "e": 9596, "s": 9577, "text": "Insertion in Heaps" }, { "code": null, "e": 9670, "s": 9596, "text": "The insertion operation is also similar to that of the deletion process. " }, { "code": null, "e": 9822, "s": 9670, "text": "Given a Binary Heap and a new element to be added to this Heap. The task is to insert the new element to the Heap maintaining the properties of Heap. " }, { "code": null, "e": 9960, "s": 9822, "text": "Process of Insertion: Elements can be inserted to the heap following a similar approach as discussed above for deletion. The idea is to: " }, { "code": null, "e": 10033, "s": 9960, "text": "First increase the heap size by 1, so that it can store the new element." }, { "code": null, "e": 10080, "s": 10033, "text": "Insert the new element at the end of the Heap." }, { "code": null, "e": 10273, "s": 10080, "text": "This newly inserted element may distort the properties of Heap for its parents. So, in order to keep the properties of Heap, heapify this newly inserted element following a bottom-up approach." }, { "code": null, "e": 10289, "s": 10273, "text": "Illustration: " }, { "code": null, "e": 10895, "s": 10289, "text": "Suppose the Heap is a Max-Heap as:\n 10\n / \\\n 5 3\n / \\\n 2 4\n\nThe new element to be inserted is 15.\n\nProcess:\nStep 1: Insert the new element at the end.\n 10\n / \\\n 5 3\n / \\ /\n 2 4 15\n\nStep 2: Heapify the new element following bottom-up \n approach.\n-> 15 is more than its parent 3, swap them.\n 10\n / \\\n 5 15\n / \\ /\n 2 4 3\n\n-> 15 is again more than its parent 10, swap them.\n 15\n / \\\n 5 10\n / \\ /\n 2 4 3\n\nTherefore, the final heap after insertion is:\n 15\n / \\\n 5 10\n / \\ /\n 2 4 3" }, { "code": null, "e": 10912, "s": 10895, "text": "Implementation: " }, { "code": null, "e": 10916, "s": 10912, "text": "C++" }, { "code": null, "e": 10921, "s": 10916, "text": "Java" }, { "code": null, "e": 10929, "s": 10921, "text": "Python3" }, { "code": "// C++ program to insert new element to Heap #include <iostream>using namespace std; #define MAX 1000 // Max size of Heap // Function to heapify ith node in a Heap// of size n following a Bottom-up approachvoid heapify(int arr[], int n, int i){ // Find parent int parent = (i - 1) / 2; if (arr[parent] > 0) { // For Max-Heap // If current node is greater than its parent // Swap both of them and call heapify again // for the parent if (arr[i] > arr[parent]) { swap(arr[i], arr[parent]); // Recursively heapify the parent node heapify(arr, n, parent); } }} // Function to insert a new node to the Heapvoid insertNode(int arr[], int& n, int Key){ // Increase the size of Heap by 1 n = n + 1; // Insert the element at end of Heap arr[n - 1] = Key; // Heapify the new node following a // Bottom-up approach heapify(arr, n, n - 1);} // A utility function to print array of size nvoid printArray(int arr[], int n){ for (int i = 0; i < n; ++i) cout << arr[i] << \" \"; cout << \"\\n\";} // Driver Codeint main(){ // Array representation of Max-Heap // 10 // / \\ // 5 3 // / \\ // 2 4 int arr[MAX] = { 10, 5, 3, 2, 4 }; int n = 5; int key = 15; insertNode(arr, n, key); printArray(arr, n); // Final Heap will be: // 15 // / \\ // 5 10 // / \\ / // 2 4 3 return 0;}", "e": 12387, "s": 10929, "text": null }, { "code": "// Java program for implementing insertion in Heapspublic class insertionHeap { // Function to heapify ith node in a Heap // of size n following a Bottom-up approach static void heapify(int[] arr, int n, int i) { // Find parent int parent = (i - 1) / 2; if (arr[parent] > 0) { // For Max-Heap // If current node is greater than its parent // Swap both of them and call heapify again // for the parent if (arr[i] > arr[parent]) { // swap arr[i] and arr[parent] int temp = arr[i]; arr[i] = arr[parent]; arr[parent] = temp; // Recursively heapify the parent node heapify(arr, n, parent); } } } // Function to insert a new node to the heap. static int insertNode(int[] arr, int n, int Key) { // Increase the size of Heap by 1 n = n + 1; // Insert the element at end of Heap arr[n - 1] = Key; // Heapify the new node following a // Bottom-up approach heapify(arr, n, n - 1); // return new size of Heap return n; } /* A utility function to print array of size n */ static void printArray(int[] arr, int n) { for (int i = 0; i < n; ++i) System.out.println(arr[i] + \" \"); System.out.println(); } // Driver Code public static void main(String args[]) { // Array representation of Max-Heap // 10 // / \\ // 5 3 // / \\ // 2 4 // maximum size of the array int MAX = 1000; int[] arr = new int[MAX]; // initializing some values arr[0] = 10; arr[1] = 5; arr[2] = 3; arr[3] = 2; arr[4] = 4; // Current size of the array int n = 5; // the element to be inserted int Key = 15; // The function inserts the new element to the heap and // returns the new size of the array n = insertNode(arr, n, Key); printArray(arr, n); // Final Heap will be: // 15 // / \\ // 5 10 // / \\ / // 2 4 3 }} // The code is contributed by Gautam goel", "e": 14745, "s": 12387, "text": null }, { "code": "# program to insert new element to Heap # Function to heapify ith node in a Heap# of size n following a Bottom-up approach def heapify(arr, n, i): parent = int(((i-1)/2)) # For Max-Heap # If current node is greater than its parent # Swap both of them and call heapify again # for the parent if arr[parent] > 0: if arr[i] > arr[parent]: arr[i], arr[parent] = arr[parent], arr[i] # Recursively heapify the parent node heapify(arr, n, parent)# Function to insert a new node to the Heap def insertNode(arr, key): global n # Increase the size of Heap by 1 n += 1 # Insert the element at end of Heap arr.append(key) # Heapify the new node following a # Bottom-up approach heapify(arr, n, n-1)# A utility function to print array of size n def printArr(arr, n): for i in range(n): print(arr[i], end=\" \") # Driver Code# Array representation of Max-Heap''' 10 / \\ 5 3 / \\ 2 4'''arr = [10, 5, 3, 2, 4, 1, 7]n = 7key = 15insertNode(arr, key)printArr(arr, n)# Final Heap will be:''' 15 / \\ 5 10 / \\ /2 4 3 Code is written by Rajat Kumar....'''", "e": 15928, "s": 14745, "text": null }, { "code": null, "e": 15942, "s": 15928, "text": "15 5 10 2 4 3" }, { "code": null, "e": 15966, "s": 15944, "text": "Time Complexity: O(n)" }, { "code": null, "e": 15988, "s": 15966, "text": "Auxiliary Space: O(n)" }, { "code": null, "e": 15996, "s": 15988, "text": "ankthon" }, { "code": null, "e": 16007, "s": 15996, "text": "YashJain25" }, { "code": null, "e": 16021, "s": 16007, "text": "ultrainstinct" }, { "code": null, "e": 16039, "s": 16021, "text": "divyeshrabadiya07" }, { "code": null, "e": 16048, "s": 16039, "text": "dsc13103" }, { "code": null, "e": 16064, "s": 16048, "text": "amartyaghoshgfg" }, { "code": null, "e": 16080, "s": 16064, "text": "rajatkumargla19" }, { "code": null, "e": 16094, "s": 16080, "text": "gautamgoel962" }, { "code": null, "e": 16106, "s": 16094, "text": "polymatir3j" }, { "code": null, "e": 16122, "s": 16106, "text": "Data Structures" }, { "code": null, "e": 16127, "s": 16122, "text": "Heap" }, { "code": null, "e": 16143, "s": 16127, "text": "Data Structures" }, { "code": null, "e": 16148, "s": 16143, "text": "Heap" }, { "code": null, "e": 16246, "s": 16148, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 16271, "s": 16246, "text": "DSA Sheet by Love Babbar" }, { "code": null, "e": 16320, "s": 16271, "text": "SDE SHEET - A Complete Guide for SDE Preparation" }, { "code": null, "e": 16352, "s": 16320, "text": "Introduction to Data Structures" }, { "code": null, "e": 16390, "s": 16352, "text": "What is Hashing | A Complete Tutorial" }, { "code": null, "e": 16426, "s": 16390, "text": "Introduction to Tree Data Structure" }, { "code": null, "e": 16482, "s": 16426, "text": "K'th Smallest/Largest Element in Unsorted Array | Set 1" }, { "code": null, "e": 16514, "s": 16482, "text": "Introduction to Data Structures" }, { "code": null, "e": 16545, "s": 16514, "text": "Huffman Coding | Greedy Algo-3" }, { "code": null, "e": 16605, "s": 16545, "text": "Sliding Window Maximum (Maximum of all subarrays of size k)" } ]
Java Swing | JDialog with examples
16 Apr, 2021 JDialog is a part Java swing package. The main purpose of the dialog is to add components to it. JDialog can be customized according to user need .Constructor of the class are: JDialog() : creates an empty dialog without any title or any specified ownerJDialog(Frame o) :creates an empty dialog with a specified frame as its ownerJDialog(Frame o, String s) : creates an empty dialog with a specified frame as its owner and a specified titleJDialog(Window o) : creates an empty dialog with a specified window as its ownerJDialog(Window o, String t) : creates an empty dialog with a specified window as its owner and specified title.JDialog(Dialog o) :creates an empty dialog with a specified dialog as its ownerJDialog(Dialog o, String s) : creates an empty dialog with a specified dialog as its owner and specified title. JDialog() : creates an empty dialog without any title or any specified owner JDialog(Frame o) :creates an empty dialog with a specified frame as its owner JDialog(Frame o, String s) : creates an empty dialog with a specified frame as its owner and a specified title JDialog(Window o) : creates an empty dialog with a specified window as its owner JDialog(Window o, String t) : creates an empty dialog with a specified window as its owner and specified title. JDialog(Dialog o) :creates an empty dialog with a specified dialog as its owner JDialog(Dialog o, String s) : creates an empty dialog with a specified dialog as its owner and specified title. Commonly used methods setLayout(LayoutManager m) : sets the layout of the dialog to specified layout managersetJMenuBar(JMenuBar m) : sets the menubar of the dialog to specified menubaradd(Component c): adds component to the dialogisVisible(boolean b): sets the visibility of the dialog, if value of the boolean is true then visible else invisibleupdate(Graphics g) : calls the paint(g) functionremove(Component c) : removes the component cgetGraphics() : returns the graphics context of the component.getLayeredPane() : returns the layered pane for the dialogsetContentPane(Container c) :sets the content pane for the dialogsetLayeredPane(JLayeredPane l) : set the layered pane for the dialogsetRootPane(JRootPane r) : sets the rootPane for the dialoggetJMenuBar() : returns the menubar of the componentsetTransferHandler(TransferHandler n) : Sets the transferHandler property, which is a mechanism to support transfer of data into this component.setRootPaneCheckingEnabled(boolean enabled) : Sets whether calls to add and setLayout are forwarded to the contentPane.setRootPane(JRootPane root) :Sets the rootPane property of the dialog.setGlassPane(Component glass) : Sets the glassPane property of the dialog.repaint(long time, int x, int y, int width, int height): Repaints the specified rectangle of this component within time milliseconds.remove(Component c): Removes the specified component from the dialog.isRootPaneCheckingEnabled() : Returns whether calls to add and setLayout are forwarded to the contentPane or not .getTransferHandler() : returns the transferHandler property.getRootPane() : Returns the rootPane object for this dialog.getGlassPane() : Returns the glassPane object for this dialog.createRootPane() : Called by the constructor methods to create the default rootPane.addImpl(Component co, Object c, int i) : Adds the specified child Component to the dialog. setLayout(LayoutManager m) : sets the layout of the dialog to specified layout manager setJMenuBar(JMenuBar m) : sets the menubar of the dialog to specified menubar add(Component c): adds component to the dialog isVisible(boolean b): sets the visibility of the dialog, if value of the boolean is true then visible else invisible update(Graphics g) : calls the paint(g) function remove(Component c) : removes the component c getGraphics() : returns the graphics context of the component. getLayeredPane() : returns the layered pane for the dialog setContentPane(Container c) :sets the content pane for the dialog setLayeredPane(JLayeredPane l) : set the layered pane for the dialog setRootPane(JRootPane r) : sets the rootPane for the dialog getJMenuBar() : returns the menubar of the component setTransferHandler(TransferHandler n) : Sets the transferHandler property, which is a mechanism to support transfer of data into this component. setRootPaneCheckingEnabled(boolean enabled) : Sets whether calls to add and setLayout are forwarded to the contentPane. setRootPane(JRootPane root) :Sets the rootPane property of the dialog. setGlassPane(Component glass) : Sets the glassPane property of the dialog. repaint(long time, int x, int y, int width, int height): Repaints the specified rectangle of this component within time milliseconds. remove(Component c): Removes the specified component from the dialog. isRootPaneCheckingEnabled() : Returns whether calls to add and setLayout are forwarded to the contentPane or not . getTransferHandler() : returns the transferHandler property. getRootPane() : Returns the rootPane object for this dialog. getGlassPane() : Returns the glassPane object for this dialog. createRootPane() : Called by the constructor methods to create the default rootPane. addImpl(Component co, Object c, int i) : Adds the specified child Component to the dialog. The following programs will illustrate the use of JDialog 1 .Program to create a simple JDialog Java // java Program to create a simple JDialogimport java.awt.event.*;import java.awt.*;import javax.swing.*;class solve extends JFrame implements ActionListener { // frame static JFrame f; // main class public static void main(String[] args) { // create a new frame f = new JFrame("frame"); // create a object solve s = new solve(); // create a panel JPanel p = new JPanel(); JButton b = new JButton("click"); // add actionlistener to button b.addActionListener(s); // add button to panel p.add(b); f.add(p); // set the size of frame f.setSize(400, 400); f.show(); } public void actionPerformed(ActionEvent e) { String s = e.getActionCommand(); if (s.equals("click")) { // create a dialog Box JDialog d = new JDialog(f, "dialog Box"); // create a label JLabel l = new JLabel("this is a dialog box"); d.add(l); // setsize of dialog d.setSize(100, 100); // set visibility of dialog d.setVisible(true); } }} Output: 2. Program to create a dialog within a dialog Java // java Program to create a dialog within a dialogimport java.awt.event.*;import java.awt.*;import javax.swing.*;class solve extends JFrame implements ActionListener { // frame static JFrame f; // dialog static JDialog d, d1; // main class public static void main(String[] args) { // create a new frame f = new JFrame("frame"); // create a object solve s = new solve(); // create a panel JPanel p = new JPanel(); JButton b = new JButton("click"); // add actionlistener to button b.addActionListener(s); // add button to panel p.add(b); f.add(p); // set the size of frame f.setSize(400, 400); f.show(); } public void actionPerformed(ActionEvent e) { String s = e.getActionCommand(); if (s.equals("click")) { // create a dialog Box d = new JDialog(f, "dialog Box"); // create a label JLabel l = new JLabel("this is first dialog box"); // create a button JButton b = new JButton("click me"); // add Action Listener b.addActionListener(this); // create a panel JPanel p = new JPanel(); p.add(b); p.add(l); // add panel to dialog d.add(p); // setsize of dialog d.setSize(200, 200); // set visibility of dialog d.setVisible(true); } else { // create a dialog Box d1 = new JDialog(d, "dialog Box"); // create a label JLabel l = new JLabel("this is second dialog box"); d1.add(l); // setsize of dialog d1.setSize(200, 200); // set location of dialog d1.setLocation(200, 200); // set visibility of dialog d1.setVisible(true); } }} Output : Note : The above programs might not run in an online compiler please use an offline IDE sweetyty java-swing Java Programming Language Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Object Oriented Programming (OOPs) Concept in Java How to iterate any Map in Java Interfaces in Java HashMap in Java with Examples ArrayList in Java Differences between Procedural and Object Oriented Programming Arrow operator -> in C/C++ with Examples Modulo Operator (%) in C/C++ with Examples Structures in C++ Decorators with parameters in Python
[ { "code": null, "e": 52, "s": 24, "text": "\n16 Apr, 2021" }, { "code": null, "e": 231, "s": 52, "text": "JDialog is a part Java swing package. The main purpose of the dialog is to add components to it. JDialog can be customized according to user need .Constructor of the class are: " }, { "code": null, "e": 876, "s": 231, "text": "JDialog() : creates an empty dialog without any title or any specified ownerJDialog(Frame o) :creates an empty dialog with a specified frame as its ownerJDialog(Frame o, String s) : creates an empty dialog with a specified frame as its owner and a specified titleJDialog(Window o) : creates an empty dialog with a specified window as its ownerJDialog(Window o, String t) : creates an empty dialog with a specified window as its owner and specified title.JDialog(Dialog o) :creates an empty dialog with a specified dialog as its ownerJDialog(Dialog o, String s) : creates an empty dialog with a specified dialog as its owner and specified title." }, { "code": null, "e": 953, "s": 876, "text": "JDialog() : creates an empty dialog without any title or any specified owner" }, { "code": null, "e": 1031, "s": 953, "text": "JDialog(Frame o) :creates an empty dialog with a specified frame as its owner" }, { "code": null, "e": 1142, "s": 1031, "text": "JDialog(Frame o, String s) : creates an empty dialog with a specified frame as its owner and a specified title" }, { "code": null, "e": 1223, "s": 1142, "text": "JDialog(Window o) : creates an empty dialog with a specified window as its owner" }, { "code": null, "e": 1335, "s": 1223, "text": "JDialog(Window o, String t) : creates an empty dialog with a specified window as its owner and specified title." }, { "code": null, "e": 1415, "s": 1335, "text": "JDialog(Dialog o) :creates an empty dialog with a specified dialog as its owner" }, { "code": null, "e": 1527, "s": 1415, "text": "JDialog(Dialog o, String s) : creates an empty dialog with a specified dialog as its owner and specified title." }, { "code": null, "e": 1551, "s": 1527, "text": "Commonly used methods " }, { "code": null, "e": 3413, "s": 1551, "text": "setLayout(LayoutManager m) : sets the layout of the dialog to specified layout managersetJMenuBar(JMenuBar m) : sets the menubar of the dialog to specified menubaradd(Component c): adds component to the dialogisVisible(boolean b): sets the visibility of the dialog, if value of the boolean is true then visible else invisibleupdate(Graphics g) : calls the paint(g) functionremove(Component c) : removes the component cgetGraphics() : returns the graphics context of the component.getLayeredPane() : returns the layered pane for the dialogsetContentPane(Container c) :sets the content pane for the dialogsetLayeredPane(JLayeredPane l) : set the layered pane for the dialogsetRootPane(JRootPane r) : sets the rootPane for the dialoggetJMenuBar() : returns the menubar of the componentsetTransferHandler(TransferHandler n) : Sets the transferHandler property, which is a mechanism to support transfer of data into this component.setRootPaneCheckingEnabled(boolean enabled) : Sets whether calls to add and setLayout are forwarded to the contentPane.setRootPane(JRootPane root) :Sets the rootPane property of the dialog.setGlassPane(Component glass) : Sets the glassPane property of the dialog.repaint(long time, int x, int y, int width, int height): Repaints the specified rectangle of this component within time milliseconds.remove(Component c): Removes the specified component from the dialog.isRootPaneCheckingEnabled() : Returns whether calls to add and setLayout are forwarded to the contentPane or not .getTransferHandler() : returns the transferHandler property.getRootPane() : Returns the rootPane object for this dialog.getGlassPane() : Returns the glassPane object for this dialog.createRootPane() : Called by the constructor methods to create the default rootPane.addImpl(Component co, Object c, int i) : Adds the specified child Component to the dialog." }, { "code": null, "e": 3500, "s": 3413, "text": "setLayout(LayoutManager m) : sets the layout of the dialog to specified layout manager" }, { "code": null, "e": 3578, "s": 3500, "text": "setJMenuBar(JMenuBar m) : sets the menubar of the dialog to specified menubar" }, { "code": null, "e": 3625, "s": 3578, "text": "add(Component c): adds component to the dialog" }, { "code": null, "e": 3742, "s": 3625, "text": "isVisible(boolean b): sets the visibility of the dialog, if value of the boolean is true then visible else invisible" }, { "code": null, "e": 3791, "s": 3742, "text": "update(Graphics g) : calls the paint(g) function" }, { "code": null, "e": 3837, "s": 3791, "text": "remove(Component c) : removes the component c" }, { "code": null, "e": 3900, "s": 3837, "text": "getGraphics() : returns the graphics context of the component." }, { "code": null, "e": 3959, "s": 3900, "text": "getLayeredPane() : returns the layered pane for the dialog" }, { "code": null, "e": 4025, "s": 3959, "text": "setContentPane(Container c) :sets the content pane for the dialog" }, { "code": null, "e": 4094, "s": 4025, "text": "setLayeredPane(JLayeredPane l) : set the layered pane for the dialog" }, { "code": null, "e": 4154, "s": 4094, "text": "setRootPane(JRootPane r) : sets the rootPane for the dialog" }, { "code": null, "e": 4207, "s": 4154, "text": "getJMenuBar() : returns the menubar of the component" }, { "code": null, "e": 4352, "s": 4207, "text": "setTransferHandler(TransferHandler n) : Sets the transferHandler property, which is a mechanism to support transfer of data into this component." }, { "code": null, "e": 4472, "s": 4352, "text": "setRootPaneCheckingEnabled(boolean enabled) : Sets whether calls to add and setLayout are forwarded to the contentPane." }, { "code": null, "e": 4543, "s": 4472, "text": "setRootPane(JRootPane root) :Sets the rootPane property of the dialog." }, { "code": null, "e": 4618, "s": 4543, "text": "setGlassPane(Component glass) : Sets the glassPane property of the dialog." }, { "code": null, "e": 4752, "s": 4618, "text": "repaint(long time, int x, int y, int width, int height): Repaints the specified rectangle of this component within time milliseconds." }, { "code": null, "e": 4822, "s": 4752, "text": "remove(Component c): Removes the specified component from the dialog." }, { "code": null, "e": 4937, "s": 4822, "text": "isRootPaneCheckingEnabled() : Returns whether calls to add and setLayout are forwarded to the contentPane or not ." }, { "code": null, "e": 4998, "s": 4937, "text": "getTransferHandler() : returns the transferHandler property." }, { "code": null, "e": 5059, "s": 4998, "text": "getRootPane() : Returns the rootPane object for this dialog." }, { "code": null, "e": 5122, "s": 5059, "text": "getGlassPane() : Returns the glassPane object for this dialog." }, { "code": null, "e": 5207, "s": 5122, "text": "createRootPane() : Called by the constructor methods to create the default rootPane." }, { "code": null, "e": 5298, "s": 5207, "text": "addImpl(Component co, Object c, int i) : Adds the specified child Component to the dialog." }, { "code": null, "e": 5396, "s": 5298, "text": "The following programs will illustrate the use of JDialog 1 .Program to create a simple JDialog " }, { "code": null, "e": 5401, "s": 5396, "text": "Java" }, { "code": "// java Program to create a simple JDialogimport java.awt.event.*;import java.awt.*;import javax.swing.*;class solve extends JFrame implements ActionListener { // frame static JFrame f; // main class public static void main(String[] args) { // create a new frame f = new JFrame(\"frame\"); // create a object solve s = new solve(); // create a panel JPanel p = new JPanel(); JButton b = new JButton(\"click\"); // add actionlistener to button b.addActionListener(s); // add button to panel p.add(b); f.add(p); // set the size of frame f.setSize(400, 400); f.show(); } public void actionPerformed(ActionEvent e) { String s = e.getActionCommand(); if (s.equals(\"click\")) { // create a dialog Box JDialog d = new JDialog(f, \"dialog Box\"); // create a label JLabel l = new JLabel(\"this is a dialog box\"); d.add(l); // setsize of dialog d.setSize(100, 100); // set visibility of dialog d.setVisible(true); } }}", "e": 6569, "s": 5401, "text": null }, { "code": null, "e": 6579, "s": 6569, "text": "Output: " }, { "code": null, "e": 6626, "s": 6579, "text": "2. Program to create a dialog within a dialog " }, { "code": null, "e": 6631, "s": 6626, "text": "Java" }, { "code": "// java Program to create a dialog within a dialogimport java.awt.event.*;import java.awt.*;import javax.swing.*;class solve extends JFrame implements ActionListener { // frame static JFrame f; // dialog static JDialog d, d1; // main class public static void main(String[] args) { // create a new frame f = new JFrame(\"frame\"); // create a object solve s = new solve(); // create a panel JPanel p = new JPanel(); JButton b = new JButton(\"click\"); // add actionlistener to button b.addActionListener(s); // add button to panel p.add(b); f.add(p); // set the size of frame f.setSize(400, 400); f.show(); } public void actionPerformed(ActionEvent e) { String s = e.getActionCommand(); if (s.equals(\"click\")) { // create a dialog Box d = new JDialog(f, \"dialog Box\"); // create a label JLabel l = new JLabel(\"this is first dialog box\"); // create a button JButton b = new JButton(\"click me\"); // add Action Listener b.addActionListener(this); // create a panel JPanel p = new JPanel(); p.add(b); p.add(l); // add panel to dialog d.add(p); // setsize of dialog d.setSize(200, 200); // set visibility of dialog d.setVisible(true); } else { // create a dialog Box d1 = new JDialog(d, \"dialog Box\"); // create a label JLabel l = new JLabel(\"this is second dialog box\"); d1.add(l); // setsize of dialog d1.setSize(200, 200); // set location of dialog d1.setLocation(200, 200); // set visibility of dialog d1.setVisible(true); } }}", "e": 8558, "s": 6631, "text": null }, { "code": null, "e": 8569, "s": 8558, "text": "Output : " }, { "code": null, "e": 8658, "s": 8569, "text": "Note : The above programs might not run in an online compiler please use an offline IDE " }, { "code": null, "e": 8667, "s": 8658, "text": "sweetyty" }, { "code": null, "e": 8678, "s": 8667, "text": "java-swing" }, { "code": null, "e": 8683, "s": 8678, "text": "Java" }, { "code": null, "e": 8704, "s": 8683, "text": "Programming Language" }, { "code": null, "e": 8709, "s": 8704, "text": "Java" }, { "code": null, "e": 8807, "s": 8709, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 8858, "s": 8807, "text": "Object Oriented Programming (OOPs) Concept in Java" }, { "code": null, "e": 8889, "s": 8858, "text": "How to iterate any Map in Java" }, { "code": null, "e": 8908, "s": 8889, "text": "Interfaces in Java" }, { "code": null, "e": 8938, "s": 8908, "text": "HashMap in Java with Examples" }, { "code": null, "e": 8956, "s": 8938, "text": "ArrayList in Java" }, { "code": null, "e": 9019, "s": 8956, "text": "Differences between Procedural and Object Oriented Programming" }, { "code": null, "e": 9060, "s": 9019, "text": "Arrow operator -> in C/C++ with Examples" }, { "code": null, "e": 9103, "s": 9060, "text": "Modulo Operator (%) in C/C++ with Examples" }, { "code": null, "e": 9121, "s": 9103, "text": "Structures in C++" } ]
Getting the minimum value from a list in Julia – min() Method
21 Apr, 2020 The min() is an inbuilt function in julia which is used to return the minimum value of the parameters. Syntax: min(x, y, ...) Parameters: x: Specified 1st value. y: Specified 2nd value and so on. Returns: It returns the minimum value of the parameters. Example 1: # Julia program to illustrate # the use of min() method # Getting the minimum value of the parameters.println(min(1, 2, 3, 4))println(min(1, 3, 5))println(min(2, 4, 6)) Output: 1 1 2 Example 2: # Julia program to illustrate # the use of min() method # Getting the minimum value of the parameters.println(min(0.6, 0.7, 0.2))println(min(2.5, 3.5, 0.3, 1.7)) Output: 0.2 0.3 Julia Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Vectors in Julia Getting rounded value of a number in Julia - round() Method Manipulating matrices in Julia Reshaping array dimensions in Julia | Array reshape() Method Exception handling in Julia Formatting of Strings in Julia Get number of elements of array in Julia - length() Method Storing Output on a File in Julia Get array dimensions and size of a dimension in Julia - size() Method Tuples in Julia
[ { "code": null, "e": 28, "s": 0, "text": "\n21 Apr, 2020" }, { "code": null, "e": 131, "s": 28, "text": "The min() is an inbuilt function in julia which is used to return the minimum value of the parameters." }, { "code": null, "e": 154, "s": 131, "text": "Syntax: min(x, y, ...)" }, { "code": null, "e": 166, "s": 154, "text": "Parameters:" }, { "code": null, "e": 190, "s": 166, "text": "x: Specified 1st value." }, { "code": null, "e": 224, "s": 190, "text": "y: Specified 2nd value and so on." }, { "code": null, "e": 281, "s": 224, "text": "Returns: It returns the minimum value of the parameters." }, { "code": null, "e": 292, "s": 281, "text": "Example 1:" }, { "code": "# Julia program to illustrate # the use of min() method # Getting the minimum value of the parameters.println(min(1, 2, 3, 4))println(min(1, 3, 5))println(min(2, 4, 6))", "e": 462, "s": 292, "text": null }, { "code": null, "e": 470, "s": 462, "text": "Output:" }, { "code": null, "e": 477, "s": 470, "text": "1\n1\n2\n" }, { "code": null, "e": 488, "s": 477, "text": "Example 2:" }, { "code": "# Julia program to illustrate # the use of min() method # Getting the minimum value of the parameters.println(min(0.6, 0.7, 0.2))println(min(2.5, 3.5, 0.3, 1.7))", "e": 651, "s": 488, "text": null }, { "code": null, "e": 659, "s": 651, "text": "Output:" }, { "code": null, "e": 668, "s": 659, "text": "0.2\n0.3\n" }, { "code": null, "e": 674, "s": 668, "text": "Julia" }, { "code": null, "e": 772, "s": 674, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 789, "s": 772, "text": "Vectors in Julia" }, { "code": null, "e": 849, "s": 789, "text": "Getting rounded value of a number in Julia - round() Method" }, { "code": null, "e": 880, "s": 849, "text": "Manipulating matrices in Julia" }, { "code": null, "e": 941, "s": 880, "text": "Reshaping array dimensions in Julia | Array reshape() Method" }, { "code": null, "e": 969, "s": 941, "text": "Exception handling in Julia" }, { "code": null, "e": 1000, "s": 969, "text": "Formatting of Strings in Julia" }, { "code": null, "e": 1059, "s": 1000, "text": "Get number of elements of array in Julia - length() Method" }, { "code": null, "e": 1093, "s": 1059, "text": "Storing Output on a File in Julia" }, { "code": null, "e": 1163, "s": 1093, "text": "Get array dimensions and size of a dimension in Julia - size() Method" } ]
The Knight’s tour problem
In chess, we know that the knight can jump in a special manner. It can move either two squares horizontally and one square vertically or two squares vertically and one square horizontally in each direction, So the complete movement looks like English letter ‘L’. In this problem, there is an empty chess board, and a knight starting from any location in the board, our task is to check whether the knight can visit all of the squares in the board or not. When It can visit all of the squares, then place the number of jumps needed to reach that location from the starting point. This problem can have multiple solutions, but we will try to find one possible solution. Input: The size of a chess board. Generally, it is 8. as (8 x 8 is the size of a normal chess board.) Output: The knight’s moves. Each cell holds a number, that indicates where to start and the knight will reach a cell at which move. 0 59 38 33 30 17 8 63 37 34 31 60 9 62 29 16 58 1 36 39 32 27 18 7 35 48 41 26 61 10 15 28 42 57 2 49 40 23 6 19 47 50 45 54 25 20 11 14 56 43 52 3 22 13 24 5 51 46 55 44 53 4 21 12 isValid(x, y, solution) Input − Place x and y and the solution matrix. Output − Check whether the (x,y) is in place and not assigned yet. Begin if 0 ≤ x ≤ Board Size and 0 ≤ y ≤ Board Size, and (x, y) is empty, then return true End knightTour(x, y, move, sol, xMove, yMove) Input − (x, y) place, number of moves, solution matrix, and possible x and y movement lists. Output − The updated solution matrix if it exists. Begin if move = Board Size * Board Size, then //when all squares are visited return true for k := 0 to number of possible xMovement or yMovement, do xNext := x + xMove[k] yNext := y + yMove[k] if isValid(xNext, yNext, sol) is true, then sol[xNext, yMext] := move if knightTour(xNext, yNext, move+1, sol, xMove, yMove), then return true else remove move from the sol[xNext, yNext] to backtrack done return false End #include <iostream> #include <iomanip> #define N 8 using namespace std; int sol[N][N]; bool isValid(int x, int y, int sol[N][N]) { //check place is in range and not assigned yet return ( x >= 0 && x < N && y >= 0 && y < N && sol[x][y] == -1); } void displaySolution() { for (int x = 0; x < N; x++) { for (int y = 0; y < N; y++) cout << setw(3) << sol[x][y] << " "; cout << endl; } } int knightTour(int x, int y, int move, int sol[N][N], int xMove[N], int yMove[N]) { int xNext, yNext; if (move == N*N) //when the total board is covered return true; for (int k = 0; k < 8; k++) { xNext = x + xMove[k]; yNext = y + yMove[k]; if (isValid(xNext, yNext, sol)) { //check room is preoccupied or not sol[xNext][yNext] = move; if (knightTour(xNext, yNext, move+1, sol, xMove, yMove) == true) return true; else sol[xNext][yNext] = -1;// backtracking } } return false; } bool findKnightTourSol() { for (int x = 0; x < N; x++) //initially set all values to -1 of solution matrix for (int y = 0; y < N; y++) sol[x][y] = -1; //all possible moves for knight int xMove[8] = { 2, 1, -1, -2, -2, -1, 1, 2 }; int yMove[8] = { 1, 2, 2, 1, -1, -2, -2, -1 }; sol[0][0] = 0; //starting from room (0, 0) if (knightTour(0, 0, 1, sol, xMove, yMove) == false) { cout << "Solution does not exist"; return false; } else displaySolution(); return true; } int main() { findKnightTourSol(); } 0 59 38 33 30 17 8 63 37 34 31 60 9 62 29 16 58 1 36 39 32 27 18 7 35 48 41 26 61 10 15 28 42 57 2 49 40 23 6 19 47 50 45 54 25 20 11 14 56 43 52 3 22 13 24 5 51 46 55 44 53 4 21 12
[ { "code": null, "e": 1450, "s": 1187, "text": "In chess, we know that the knight can jump in a special manner. It can move either two squares horizontally and one square vertically or two squares vertically and one square horizontally in each direction, So the complete movement looks like English letter ‘L’." }, { "code": null, "e": 1766, "s": 1450, "text": "In this problem, there is an empty chess board, and a knight starting from any location in the board, our task is to check whether the knight can visit all of the squares in the board or not. When It can visit all of the squares, then place the number of jumps needed to reach that location from the starting point." }, { "code": null, "e": 1855, "s": 1766, "text": "This problem can have multiple solutions, but we will try to find one possible solution." }, { "code": null, "e": 2348, "s": 1855, "text": "Input: \nThe size of a chess board. Generally, it is 8. as (8 x 8 is the size of a normal chess board.)\nOutput:\nThe knight’s moves. Each cell holds a number, that indicates where to start and the knight will reach a cell at which move.\n\n 0 59 38 33 30 17 8 63\n 37 34 31 60 9 62 29 16\n 58 1 36 39 32 27 18 7\n 35 48 41 26 61 10 15 28\n 42 57 2 49 40 23 6 19\n 47 50 45 54 25 20 11 14\n 56 43 52 3 22 13 24 5\n 51 46 55 44 53 4 21 12" }, { "code": null, "e": 2372, "s": 2348, "text": "isValid(x, y, solution)" }, { "code": null, "e": 2419, "s": 2372, "text": "Input − Place x and y and the solution matrix." }, { "code": null, "e": 2486, "s": 2419, "text": "Output − Check whether the (x,y) is in place and not assigned yet." }, { "code": null, "e": 2589, "s": 2486, "text": "Begin\n if 0 ≤ x ≤ Board Size and 0 ≤ y ≤ Board Size, and (x, y) is empty, then\n return true\nEnd" }, { "code": null, "e": 2631, "s": 2589, "text": "knightTour(x, y, move, sol, xMove, yMove)" }, { "code": null, "e": 2724, "s": 2631, "text": "Input − (x, y) place, number of moves, solution matrix, and possible x and y movement lists." }, { "code": null, "e": 2775, "s": 2724, "text": "Output − The updated solution matrix if it exists." }, { "code": null, "e": 3277, "s": 2775, "text": "Begin\n if move = Board Size * Board Size, then //when all squares are visited\n return true\n for k := 0 to number of possible xMovement or yMovement, do\n xNext := x + xMove[k]\n yNext := y + yMove[k]\n if isValid(xNext, yNext, sol) is true, then\n sol[xNext, yMext] := move\n if knightTour(xNext, yNext, move+1, sol, xMove, yMove), then\n return true\n else\n remove move from the sol[xNext, yNext] to backtrack\n done\n return false\nEnd" }, { "code": null, "e": 4859, "s": 3277, "text": "#include <iostream>\n#include <iomanip>\n#define N 8\n\nusing namespace std;\nint sol[N][N];\n\nbool isValid(int x, int y, int sol[N][N]) { //check place is in range and not assigned yet\n return ( x >= 0 && x < N && y >= 0 && y < N && sol[x][y] == -1);\n}\n\nvoid displaySolution() {\n for (int x = 0; x < N; x++) {\n for (int y = 0; y < N; y++)\n cout << setw(3) << sol[x][y] << \" \";\n cout << endl;\n }\n}\n\nint knightTour(int x, int y, int move, int sol[N][N], int xMove[N], int yMove[N]) {\n int xNext, yNext;\n if (move == N*N) //when the total board is covered\n return true;\n\n for (int k = 0; k < 8; k++) {\n xNext = x + xMove[k];\n yNext = y + yMove[k];\n if (isValid(xNext, yNext, sol)) { //check room is preoccupied or not\n sol[xNext][yNext] = move;\n if (knightTour(xNext, yNext, move+1, sol, xMove, yMove) == true)\n return true;\n else\n sol[xNext][yNext] = -1;// backtracking\n }\n }\n return false;\n}\n\nbool findKnightTourSol() {\n for (int x = 0; x < N; x++) //initially set all values to -1 of solution matrix\n for (int y = 0; y < N; y++)\n sol[x][y] = -1;\n //all possible moves for knight\n int xMove[8] = { 2, 1, -1, -2, -2, -1, 1, 2 };\n int yMove[8] = { 1, 2, 2, 1, -1, -2, -2, -1 };\n sol[0][0] = 0; //starting from room (0, 0)\n\n if (knightTour(0, 0, 1, sol, xMove, yMove) == false) {\n cout << \"Solution does not exist\";\n return false;\n } else\n displaySolution();\n return true;\n}\n\nint main() {\n findKnightTourSol();\n}" }, { "code": null, "e": 5107, "s": 4859, "text": " 0 59 38 33 30 17 8 63\n37 34 31 60 9 62 29 16\n58 1 36 39 32 27 18 7\n35 48 41 26 61 10 15 28\n42 57 2 49 40 23 6 19\n47 50 45 54 25 20 11 14\n56 43 52 3 22 13 24 5\n51 46 55 44 53 4 21 12" } ]
Python sympy | Matrix.nullspace() method
13 Aug, 2019 With the help of sympy.Matrix().nullspace() method, we can find the Nullspace of a Matrix. Matrix().nullspace() returns a list of column vectors that span the nullspace of the matrix. Syntax: Matrix().nullspace() Returns: Returns a list of column vectors that span the nullspace of the matrix. Example #1: # import sympy from sympy import * M = Matrix([[1, 0, 1, 3], [2, 3, 4, 7], [-1, -3, -3, -4]])print("Matrix : {} ".format(M)) # Use sympy.nullspace() method M_nullspace = M.nullspace() print("Nullspace of a matrix : {}".format(M_nullspace)) Output: Matrix : Matrix([[1, 0, 1, 3], [2, 3, 4, 7], [-1, -3, -3, -4]]) Nullspace of a matrix : [Matrix([ [ -1], [-2/3], [ 1], [ 0]]), Matrix([ [ -3], [-1/3], [ 0], [ 1]])] Example #2: # import sympy from sympy import * M = Matrix([[14, 0, 11, 3], [22, 23, 4, 7], [-12, -34, -3, -4]])print("Matrix : {} ".format(M)) # Use sympy.nullspace() method M_nullspace = M.nullspace() print("Nullspace of a matrix : {}".format(M_nullspace)) Output: Matrix : Matrix([[14, 0, 11, 3], [22, 23, 4, 7], [-12, -34, -3, -4]]) Nullspace of a matrix : [Matrix([ [-1405/4254], [ -10/709], [ 314/2127], [ 1]])] SymPy 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 Python Classes and Objects Iterate over a list in Python Python OOPs Concepts
[ { "code": null, "e": 28, "s": 0, "text": "\n13 Aug, 2019" }, { "code": null, "e": 212, "s": 28, "text": "With the help of sympy.Matrix().nullspace() method, we can find the Nullspace of a Matrix. Matrix().nullspace() returns a list of column vectors that span the nullspace of the matrix." }, { "code": null, "e": 241, "s": 212, "text": "Syntax: Matrix().nullspace()" }, { "code": null, "e": 322, "s": 241, "text": "Returns: Returns a list of column vectors that span the nullspace of the matrix." }, { "code": null, "e": 334, "s": 322, "text": "Example #1:" }, { "code": "# import sympy from sympy import * M = Matrix([[1, 0, 1, 3], [2, 3, 4, 7], [-1, -3, -3, -4]])print(\"Matrix : {} \".format(M)) # Use sympy.nullspace() method M_nullspace = M.nullspace() print(\"Nullspace of a matrix : {}\".format(M_nullspace)) ", "e": 587, "s": 334, "text": null }, { "code": null, "e": 595, "s": 587, "text": "Output:" }, { "code": null, "e": 772, "s": 595, "text": "Matrix : Matrix([[1, 0, 1, 3], [2, 3, 4, 7], [-1, -3, -3, -4]]) \nNullspace of a matrix : [Matrix([\n[ -1],\n[-2/3],\n[ 1],\n[ 0]]), Matrix([\n[ -3],\n[-1/3],\n[ 0],\n[ 1]])]\n" }, { "code": null, "e": 784, "s": 772, "text": "Example #2:" }, { "code": "# import sympy from sympy import * M = Matrix([[14, 0, 11, 3], [22, 23, 4, 7], [-12, -34, -3, -4]])print(\"Matrix : {} \".format(M)) # Use sympy.nullspace() method M_nullspace = M.nullspace() print(\"Nullspace of a matrix : {}\".format(M_nullspace)) ", "e": 1042, "s": 784, "text": null }, { "code": null, "e": 1050, "s": 1042, "text": "Output:" }, { "code": null, "e": 1214, "s": 1050, "text": "Matrix : Matrix([[14, 0, 11, 3], [22, 23, 4, 7], [-12, -34, -3, -4]]) \nNullspace of a matrix : [Matrix([\n[-1405/4254],\n[ -10/709],\n[ 314/2127],\n[ 1]])]\n" }, { "code": null, "e": 1220, "s": 1214, "text": "SymPy" }, { "code": null, "e": 1227, "s": 1220, "text": "Python" }, { "code": null, "e": 1325, "s": 1227, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1343, "s": 1325, "text": "Python Dictionary" }, { "code": null, "e": 1385, "s": 1343, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 1407, "s": 1385, "text": "Enumerate() in Python" }, { "code": null, "e": 1442, "s": 1407, "text": "Read a file line by line in Python" }, { "code": null, "e": 1468, "s": 1442, "text": "Python String | replace()" }, { "code": null, "e": 1500, "s": 1468, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 1529, "s": 1500, "text": "*args and **kwargs in Python" }, { "code": null, "e": 1556, "s": 1529, "text": "Python Classes and Objects" }, { "code": null, "e": 1586, "s": 1556, "text": "Iterate over a list in Python" } ]
ML – Decision Function
18 May, 2022 Decision function is a method present in classifier{ SVC, Logistic Regression } class of sklearn machine learning framework. This method basically returns a Numpy array, In which each element represents whether a predicted sample for x_test by the classifier lies to the right or left side of the Hyperplane and also how far from the HyperPlane. It also tells us that how confidently each value predicted for x_test by the classifier is Positive ( large-magnitude Positive value ) or Negative ( large-magnitude Negative value). Math behind the Decision Function method: Let’s consider the SVM for linearly-separable binary class classification problem: Cost Function:Hypothesis for this Linearly Separable Binary class classification: The optimization Algorithm minimizes the cost function to find the best value of the model parameter for the hypothesis such that:What Actually happens when we pass a data instance to Decision Function method ? This data sample is substituted in this hypothesis whose model parameters have been found by minimizing the cost function and returns the value outputted by this hypothesis which would be >1 if actual output is 1 or <-1 if the actual output is 0. This returned value indeed represents on which side of the hyperplane and also how far from it the given data sample lie. Code: create our own data set and plot the input. python3 # This code may not run on GFG IDE# As required modules are not available. # Create a simple data set# Binary-Class Classification. # Import Required Modules.import matplotlib.pyplot as pltimport numpy as np # Input Feature X.x = np.array([[2, 1.5], [-2, -1], [-1, -1], [2, 1], [1, 5], [0.5, 0.5], [-2, 0.5]]) # Input Feature Y.y = np.array([0, 0, 1, 1, 1, 1, 0]) # Training set Feature x_train.x_train = np.array([[2, 1.5], [-2, -1], [-1, -1], [2, 1]]) # Training set Target Variable y_train.y_train = np.array([0, 0, 1, 1]) # Test set Feature x_test.x_test = np.array([[1, 5], [0.5, 0.5], [-2, 0.5]]) # Test set Target Variable y_testy_test = np.array([1, 1, 0]) # Plot the obtained dataplt.scatter(x[:, 0], x[:, 1], c = y)plt.xlabel('Feature 1 --->')plt.ylabel('Feature 2 --->')plt.title('Created Data') Output: Code: train our model python3 # This code may not run on GFG IDE# As required modules are not available. # Import SVM Class from sklearn.from sklearn.svm import SVCclf = SVC() # Train the model on the training set.clf.fit(x_train, y_train) # Predict on Test setpredict = clf.predict(x_test)print('Predicted Values from Classifier:', predict)print('Actual Output is:', y_test)print('Accuracy of the model is:', clf.score(x_test, y_test)) Output: Predicted Values from Classifier: [0 1 0] Actual Output is: [1 1 0] Accuracy of the model is: 0.6666666666666666 Code: decision function method python3 # This code may not run on GFG IDE# As required modules are not available. # Using Decision Function Method Present in svc classDecision_Function = clf.decision_function(x_test)print('Output of Decision Function is:', Decision_Function)print('Prediction for x_test from classifier is:', predict) Output: Output of Decision Function is: [-0.04274893 0.29143233 -0.13001369] Prediction for x_test from classifier is: [0 1 0] From the above output, we can conclude that the decision function output represents whether a predicted sample for x_test by the classifier lies to the right side or left side of hyperplane and also how far from it. It also tells us how confidently each value predicted for x_test by the classifier is Positive ( large-magnitude Positive value ) or Negative ( large-magnitude Negative value) Code: Decision Boundary python3 # This code may not run on GFG IDE# As required modules are not available. # To Plot the Decision Boundary.arr1 = np.arange(x[:, 0].min()-1, x[:, 0].max()+1, 0.01)arr2 = np.arange(x[:, 1].min()-1, x[:, 1].max()+1, 0.01) xx, yy = np.meshgrid(arr1, arr2)input_array = np.array([xx.ravel(), yy.ravel()]).Tlabels = clf.predict(input_array) plt.figure(figsize =(10, 7))plt.contourf(xx, yy, labels.reshape(xx.shape), alpha = 0.1)plt.scatter(x_test[:, 0], x_test[:, 1], c = y_test.ravel(), alpha = 1)plt.xlabel('Feature 1')plt.ylabel('Feature 2')plt.title('Decision Boundary') Let’s Visualize the above conclusion. The advantage of Decision Function output is to set DECISION THRESHOLD and predict a new output for x_test, such that we get desired precision or recall value If our project is precision-oriented or recall-oriented respectively. sumitgumber28 Machine Learning Python Machine Learning Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. ML | Linear Regression Search Algorithms in AI Introduction to Recurrent Neural Network ML | Monte Carlo Tree Search (MCTS) Markov Decision Process Read JSON file using Python Adding new column to existing DataFrame in Pandas Python map() function Python Dictionary How to get column names in Pandas dataframe
[ { "code": null, "e": 54, "s": 26, "text": "\n18 May, 2022" }, { "code": null, "e": 1420, "s": 54, "text": "Decision function is a method present in classifier{ SVC, Logistic Regression } class of sklearn machine learning framework. This method basically returns a Numpy array, In which each element represents whether a predicted sample for x_test by the classifier lies to the right or left side of the Hyperplane and also how far from the HyperPlane. It also tells us that how confidently each value predicted for x_test by the classifier is Positive ( large-magnitude Positive value ) or Negative ( large-magnitude Negative value). Math behind the Decision Function method: Let’s consider the SVM for linearly-separable binary class classification problem: Cost Function:Hypothesis for this Linearly Separable Binary class classification: The optimization Algorithm minimizes the cost function to find the best value of the model parameter for the hypothesis such that:What Actually happens when we pass a data instance to Decision Function method ? This data sample is substituted in this hypothesis whose model parameters have been found by minimizing the cost function and returns the value outputted by this hypothesis which would be >1 if actual output is 1 or <-1 if the actual output is 0. This returned value indeed represents on which side of the hyperplane and also how far from it the given data sample lie. Code: create our own data set and plot the input. " }, { "code": null, "e": 1428, "s": 1420, "text": "python3" }, { "code": "# This code may not run on GFG IDE# As required modules are not available. # Create a simple data set# Binary-Class Classification. # Import Required Modules.import matplotlib.pyplot as pltimport numpy as np # Input Feature X.x = np.array([[2, 1.5], [-2, -1], [-1, -1], [2, 1], [1, 5], [0.5, 0.5], [-2, 0.5]]) # Input Feature Y.y = np.array([0, 0, 1, 1, 1, 1, 0]) # Training set Feature x_train.x_train = np.array([[2, 1.5], [-2, -1], [-1, -1], [2, 1]]) # Training set Target Variable y_train.y_train = np.array([0, 0, 1, 1]) # Test set Feature x_test.x_test = np.array([[1, 5], [0.5, 0.5], [-2, 0.5]]) # Test set Target Variable y_testy_test = np.array([1, 1, 0]) # Plot the obtained dataplt.scatter(x[:, 0], x[:, 1], c = y)plt.xlabel('Feature 1 --->')plt.ylabel('Feature 2 --->')plt.title('Created Data')", "e": 2248, "s": 1428, "text": null }, { "code": null, "e": 2279, "s": 2248, "text": "Output: Code: train our model " }, { "code": null, "e": 2287, "s": 2279, "text": "python3" }, { "code": "# This code may not run on GFG IDE# As required modules are not available. # Import SVM Class from sklearn.from sklearn.svm import SVCclf = SVC() # Train the model on the training set.clf.fit(x_train, y_train) # Predict on Test setpredict = clf.predict(x_test)print('Predicted Values from Classifier:', predict)print('Actual Output is:', y_test)print('Accuracy of the model is:', clf.score(x_test, y_test))", "e": 2694, "s": 2287, "text": null }, { "code": null, "e": 2702, "s": 2694, "text": "Output:" }, { "code": null, "e": 2815, "s": 2702, "text": "Predicted Values from Classifier: [0 1 0]\nActual Output is: [1 1 0]\nAccuracy of the model is: 0.6666666666666666" }, { "code": null, "e": 2847, "s": 2815, "text": "Code: decision function method " }, { "code": null, "e": 2855, "s": 2847, "text": "python3" }, { "code": "# This code may not run on GFG IDE# As required modules are not available. # Using Decision Function Method Present in svc classDecision_Function = clf.decision_function(x_test)print('Output of Decision Function is:', Decision_Function)print('Prediction for x_test from classifier is:', predict)", "e": 3151, "s": 2855, "text": null }, { "code": null, "e": 3159, "s": 3151, "text": "Output:" }, { "code": null, "e": 3279, "s": 3159, "text": "Output of Decision Function is: [-0.04274893 0.29143233 -0.13001369]\nPrediction for x_test from classifier is: [0 1 0]" }, { "code": null, "e": 3696, "s": 3279, "text": "From the above output, we can conclude that the decision function output represents whether a predicted sample for x_test by the classifier lies to the right side or left side of hyperplane and also how far from it. It also tells us how confidently each value predicted for x_test by the classifier is Positive ( large-magnitude Positive value ) or Negative ( large-magnitude Negative value) Code: Decision Boundary " }, { "code": null, "e": 3704, "s": 3696, "text": "python3" }, { "code": "# This code may not run on GFG IDE# As required modules are not available. # To Plot the Decision Boundary.arr1 = np.arange(x[:, 0].min()-1, x[:, 0].max()+1, 0.01)arr2 = np.arange(x[:, 1].min()-1, x[:, 1].max()+1, 0.01) xx, yy = np.meshgrid(arr1, arr2)input_array = np.array([xx.ravel(), yy.ravel()]).Tlabels = clf.predict(input_array) plt.figure(figsize =(10, 7))plt.contourf(xx, yy, labels.reshape(xx.shape), alpha = 0.1)plt.scatter(x_test[:, 0], x_test[:, 1], c = y_test.ravel(), alpha = 1)plt.xlabel('Feature 1')plt.ylabel('Feature 2')plt.title('Decision Boundary')", "e": 4274, "s": 3704, "text": null }, { "code": null, "e": 4541, "s": 4274, "text": "Let’s Visualize the above conclusion. The advantage of Decision Function output is to set DECISION THRESHOLD and predict a new output for x_test, such that we get desired precision or recall value If our project is precision-oriented or recall-oriented respectively." }, { "code": null, "e": 4555, "s": 4541, "text": "sumitgumber28" }, { "code": null, "e": 4572, "s": 4555, "text": "Machine Learning" }, { "code": null, "e": 4579, "s": 4572, "text": "Python" }, { "code": null, "e": 4596, "s": 4579, "text": "Machine Learning" }, { "code": null, "e": 4694, "s": 4596, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 4717, "s": 4694, "text": "ML | Linear Regression" }, { "code": null, "e": 4741, "s": 4717, "text": "Search Algorithms in AI" }, { "code": null, "e": 4782, "s": 4741, "text": "Introduction to Recurrent Neural Network" }, { "code": null, "e": 4818, "s": 4782, "text": "ML | Monte Carlo Tree Search (MCTS)" }, { "code": null, "e": 4842, "s": 4818, "text": "Markov Decision Process" }, { "code": null, "e": 4870, "s": 4842, "text": "Read JSON file using Python" }, { "code": null, "e": 4920, "s": 4870, "text": "Adding new column to existing DataFrame in Pandas" }, { "code": null, "e": 4942, "s": 4920, "text": "Python map() function" }, { "code": null, "e": 4960, "s": 4942, "text": "Python Dictionary" } ]
CSS clamp() Method
15 Oct, 2020 The clamp() method is used to clamp the value between an upper and lower bound. It takes three parameters which are listed below: Minimum value Preferred value Maximum value The minimum value comes in handy when the preferred value is smaller than the minimum value similarly maximum value comes in handy when the preferred value is more than the maximum value. The preferred value becomes useful when it is between the minimum and maximum value. The clamp() function can be used with the various elements such as font-size, width etc. Lets built a simple layout to get a clear understanding of the clamp() function Syntax : clamp(value1, value2, value3) Parameters: Here value1 represents the minimum value, value2 represents the preferred value and value3 represents the maximum value. Example: <!DOCTYPE html><html> <head> <style> /* Setting clamp property of heading */ h1 { font-size: clamp(2rem, 4vw, 4rem); color: #eb4034; } /* Setting clamp property of box */ .box { width: clamp(150px, 50%, 400px); height: 8rem; background: #5f76e8; } </style></head> <body> <div class="container"> <h1>Welcome To GFG</h1> <div class="box"></div> </div></body> </html> Output: In the above-shown example, we see how easily the width and font-size are adjusted according to viewport with the help of the clamp function. The clamp() function is very useful for typography and for creating fluid layout. Supported Browsers: Chrome Opera Safari Firefox Edge CSS-Properties CSS Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to set space between the flexbox ? Design a Tribute Page using HTML & CSS Form validation using jQuery How to Change the Position of Scrollbar using CSS ? What is the difference between SCSS and SASS ? Installation of Node.js on Linux How to set the default value for an HTML <select> element ? How do you run JavaScript script through the Terminal? Node.js fs.readFileSync() Method How to set space between the flexbox ?
[ { "code": null, "e": 28, "s": 0, "text": "\n15 Oct, 2020" }, { "code": null, "e": 158, "s": 28, "text": "The clamp() method is used to clamp the value between an upper and lower bound. It takes three parameters which are listed below:" }, { "code": null, "e": 172, "s": 158, "text": "Minimum value" }, { "code": null, "e": 188, "s": 172, "text": "Preferred value" }, { "code": null, "e": 202, "s": 188, "text": "Maximum value" }, { "code": null, "e": 475, "s": 202, "text": "The minimum value comes in handy when the preferred value is smaller than the minimum value similarly maximum value comes in handy when the preferred value is more than the maximum value. The preferred value becomes useful when it is between the minimum and maximum value." }, { "code": null, "e": 644, "s": 475, "text": "The clamp() function can be used with the various elements such as font-size, width etc. Lets built a simple layout to get a clear understanding of the clamp() function" }, { "code": null, "e": 654, "s": 644, "text": "Syntax : " }, { "code": null, "e": 684, "s": 654, "text": "clamp(value1, value2, value3)" }, { "code": null, "e": 696, "s": 684, "text": "Parameters:" }, { "code": null, "e": 817, "s": 696, "text": "Here value1 represents the minimum value, value2 represents the preferred value and value3 represents the maximum value." }, { "code": null, "e": 826, "s": 817, "text": "Example:" }, { "code": "<!DOCTYPE html><html> <head> <style> /* Setting clamp property of heading */ h1 { font-size: clamp(2rem, 4vw, 4rem); color: #eb4034; } /* Setting clamp property of box */ .box { width: clamp(150px, 50%, 400px); height: 8rem; background: #5f76e8; } </style></head> <body> <div class=\"container\"> <h1>Welcome To GFG</h1> <div class=\"box\"></div> </div></body> </html>", "e": 1321, "s": 826, "text": null }, { "code": null, "e": 1329, "s": 1321, "text": "Output:" }, { "code": null, "e": 1553, "s": 1329, "text": "In the above-shown example, we see how easily the width and font-size are adjusted according to viewport with the help of the clamp function. The clamp() function is very useful for typography and for creating fluid layout." }, { "code": null, "e": 1573, "s": 1553, "text": "Supported Browsers:" }, { "code": null, "e": 1580, "s": 1573, "text": "Chrome" }, { "code": null, "e": 1586, "s": 1580, "text": "Opera" }, { "code": null, "e": 1593, "s": 1586, "text": "Safari" }, { "code": null, "e": 1601, "s": 1593, "text": "Firefox" }, { "code": null, "e": 1606, "s": 1601, "text": "Edge" }, { "code": null, "e": 1621, "s": 1606, "text": "CSS-Properties" }, { "code": null, "e": 1625, "s": 1621, "text": "CSS" }, { "code": null, "e": 1642, "s": 1625, "text": "Web Technologies" }, { "code": null, "e": 1740, "s": 1642, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1779, "s": 1740, "text": "How to set space between the flexbox ?" }, { "code": null, "e": 1818, "s": 1779, "text": "Design a Tribute Page using HTML & CSS" }, { "code": null, "e": 1847, "s": 1818, "text": "Form validation using jQuery" }, { "code": null, "e": 1899, "s": 1847, "text": "How to Change the Position of Scrollbar using CSS ?" }, { "code": null, "e": 1946, "s": 1899, "text": "What is the difference between SCSS and SASS ?" }, { "code": null, "e": 1979, "s": 1946, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 2039, "s": 1979, "text": "How to set the default value for an HTML <select> element ?" }, { "code": null, "e": 2094, "s": 2039, "text": "How do you run JavaScript script through the Terminal?" }, { "code": null, "e": 2127, "s": 2094, "text": "Node.js fs.readFileSync() Method" } ]
How to export default constructors ?
21 Jun, 2021 The export statement is used to bind one JavaScript module to others. In order to export the default constructor, we use an export statement and import module at the required place. On creating an instance of the class, the constructor of a respective class is invoked. Syntax: export default class ClassName{...} In the following example, we will use the JavaScript module in another module by exporting and importing it. However, Cross origin requests are only supported for HTTPS. Therefore, we need to run our HTML file on the local server. Approach: Create a file index.html. Create a User.js file that will export the module. Create another Profile.js file to import the constructor and check whether it’s invoked on creating an object. Add script-src in index.html (Note: Since we are exporting modules we need to add type=”module”) Project Directory: Our project directory will look like this. Project Directory Structure Example: The index.html file will contain src to Profile.js where the module is imported. The Profile.js file will import User.js and invoke a constructor of User.js by creating an object of class User. The User.js file will have a constructor which takes params and prints its value along with some dummy text. index.html <!DOCTYPE html> <head> <script type="module" src="./Profile.js"> </script></head> <body> <div style="color: green; font-size: 35px; margin-left: 100px;"> Geeks for Geeks </div> <p style="color: rgb(44, 46, 44); font-size: 20px; margin-left: 100px;"> Result will be displayed at console </p></body> </html> Profile.js // Importing Userimport User from './User.js'; // Creating new user objectvar user = new User({name:'Lorem Ipsum',lang:'Javascript'}); // Printing dataconsole.log(user); User.js export default class User{ constructor(params) { this.name=params.name; this.lang=params.lang; console.log('constructor of User class called: '); console.log(this.name+' is your name.'); console.log(this.lang+' is your language'); }} Steps to run HTML files on the local server If you have NodeJs and npm installed on your machine, install http-server by running this command on the terminal.npm install http-server -g npm install http-server -g Through terminal navigate to the directory where you have your all file saved and type.http-server http-server Output: You will see a list of the local server serving as shown below:List of Available ports serving List of Available ports serving Now click on any available local server, we will see the following output. Constructors JavaScript-Questions Picked JavaScript Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Difference between var, let and const keywords in JavaScript Remove elements from a JavaScript Array Difference Between PUT and PATCH Request Roadmap to Learn JavaScript For Beginners JavaScript | Promises Top 10 Projects For Beginners To Practice HTML and CSS Skills Installation of Node.js on Linux Difference between var, let and const keywords in JavaScript How to insert spaces/tabs in text using HTML/CSS? How to fetch data from an API in ReactJS ?
[ { "code": null, "e": 28, "s": 0, "text": "\n21 Jun, 2021" }, { "code": null, "e": 298, "s": 28, "text": "The export statement is used to bind one JavaScript module to others. In order to export the default constructor, we use an export statement and import module at the required place. On creating an instance of the class, the constructor of a respective class is invoked." }, { "code": null, "e": 306, "s": 298, "text": "Syntax:" }, { "code": null, "e": 342, "s": 306, "text": "export default class ClassName{...}" }, { "code": null, "e": 574, "s": 342, "text": "In the following example, we will use the JavaScript module in another module by exporting and importing it. However, Cross origin requests are only supported for HTTPS. Therefore, we need to run our HTML file on the local server. " }, { "code": null, "e": 584, "s": 574, "text": "Approach:" }, { "code": null, "e": 610, "s": 584, "text": "Create a file index.html." }, { "code": null, "e": 661, "s": 610, "text": "Create a User.js file that will export the module." }, { "code": null, "e": 772, "s": 661, "text": "Create another Profile.js file to import the constructor and check whether it’s invoked on creating an object." }, { "code": null, "e": 869, "s": 772, "text": "Add script-src in index.html (Note: Since we are exporting modules we need to add type=”module”)" }, { "code": null, "e": 933, "s": 871, "text": "Project Directory: Our project directory will look like this." }, { "code": null, "e": 961, "s": 933, "text": "Project Directory Structure" }, { "code": null, "e": 1273, "s": 961, "text": "Example: The index.html file will contain src to Profile.js where the module is imported. The Profile.js file will import User.js and invoke a constructor of User.js by creating an object of class User. The User.js file will have a constructor which takes params and prints its value along with some dummy text." }, { "code": null, "e": 1284, "s": 1273, "text": "index.html" }, { "code": "<!DOCTYPE html> <head> <script type=\"module\" src=\"./Profile.js\"> </script></head> <body> <div style=\"color: green; font-size: 35px; margin-left: 100px;\"> Geeks for Geeks </div> <p style=\"color: rgb(44, 46, 44); font-size: 20px; margin-left: 100px;\"> Result will be displayed at console </p></body> </html>", "e": 1697, "s": 1284, "text": null }, { "code": null, "e": 1708, "s": 1697, "text": "Profile.js" }, { "code": "// Importing Userimport User from './User.js'; // Creating new user objectvar user = new User({name:'Lorem Ipsum',lang:'Javascript'}); // Printing dataconsole.log(user);", "e": 1880, "s": 1708, "text": null }, { "code": null, "e": 1888, "s": 1880, "text": "User.js" }, { "code": "export default class User{ constructor(params) { this.name=params.name; this.lang=params.lang; console.log('constructor of User class called: '); console.log(this.name+' is your name.'); console.log(this.lang+' is your language'); }}", "e": 2166, "s": 1888, "text": null }, { "code": null, "e": 2210, "s": 2166, "text": "Steps to run HTML files on the local server" }, { "code": null, "e": 2351, "s": 2210, "text": "If you have NodeJs and npm installed on your machine, install http-server by running this command on the terminal.npm install http-server -g" }, { "code": null, "e": 2378, "s": 2351, "text": "npm install http-server -g" }, { "code": null, "e": 2477, "s": 2378, "text": "Through terminal navigate to the directory where you have your all file saved and type.http-server" }, { "code": null, "e": 2489, "s": 2477, "text": "http-server" }, { "code": null, "e": 2497, "s": 2489, "text": "Output:" }, { "code": null, "e": 2592, "s": 2497, "text": "You will see a list of the local server serving as shown below:List of Available ports serving" }, { "code": null, "e": 2624, "s": 2592, "text": "List of Available ports serving" }, { "code": null, "e": 2699, "s": 2624, "text": "Now click on any available local server, we will see the following output." }, { "code": null, "e": 2712, "s": 2699, "text": "Constructors" }, { "code": null, "e": 2733, "s": 2712, "text": "JavaScript-Questions" }, { "code": null, "e": 2740, "s": 2733, "text": "Picked" }, { "code": null, "e": 2751, "s": 2740, "text": "JavaScript" }, { "code": null, "e": 2768, "s": 2751, "text": "Web Technologies" }, { "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": 2927, "s": 2866, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 2967, "s": 2927, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 3008, "s": 2967, "text": "Difference Between PUT and PATCH Request" }, { "code": null, "e": 3050, "s": 3008, "text": "Roadmap to Learn JavaScript For Beginners" }, { "code": null, "e": 3072, "s": 3050, "text": "JavaScript | Promises" }, { "code": null, "e": 3134, "s": 3072, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 3167, "s": 3134, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 3228, "s": 3167, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 3278, "s": 3228, "text": "How to insert spaces/tabs in text using HTML/CSS?" } ]
p5.js | html() Function
20 Aug, 2019 The html() function is used to set the inner HTML of the element by replacing any existing html. If the value of the second parameter is true then html is appended instead of replacing the existing html element. If this function does not contain any parameters then it returns the inner HTML of the element. Note: This function requires the p5.dom library. So add the following line in the head section of the index.html file. <script language="javascript" type="text/javascript" src="path/to/p5.dom.js"></script> Syntax: html() or html( html, append ) Parameters: html: This parameter holds the HTML element in string format which needs to be placed inside the element. append: This parameter holds the Boolean value to append existing HTML element. Return Value: This function returns a string which contains the inner HTML of the element. Below examples illustrate the html() function in p5.js: Example 1: function setup() { // Create a canvas of given size createCanvas(400, 200); // Set background color background('green'); var div = createDiv(''); // Use html() function div.html('Welcome to GeeksforGeeks'); // Set the position of div element div.position(60, 80); // Set font-size of text div.style('font-size', '24px'); // Set font-color of text div.style('color', 'white'); } Output: Example 2: function setup() { // Create canvas of given size createCanvas(400, 200); // Set background color background('green'); var div = createDiv('').size(200, 70); // Use html() function div.html('Welcome to GeeksforGeeks', true); // Set the position of div element div.position(100, 60); // Set font-size of text div.style('font-size', '24px'); // Set font-color of text div.style('color', 'white'); div.style('border', '1px solid white'); div.style('text-align', 'center'); } Output: JavaScript-p5.js JavaScript Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Difference between var, let and const keywords in JavaScript Differences between Functional Components and Class Components in React Remove elements from a JavaScript Array Difference Between PUT and PATCH Request How to append HTML code to a div using JavaScript ? Installation of Node.js on Linux Top 10 Projects For Beginners To Practice HTML and CSS Skills Difference between var, let and const keywords in JavaScript How to insert spaces/tabs in text using HTML/CSS? How to fetch data from an API in ReactJS ?
[ { "code": null, "e": 28, "s": 0, "text": "\n20 Aug, 2019" }, { "code": null, "e": 336, "s": 28, "text": "The html() function is used to set the inner HTML of the element by replacing any existing html. If the value of the second parameter is true then html is appended instead of replacing the existing html element. If this function does not contain any parameters then it returns the inner HTML of the element." }, { "code": null, "e": 455, "s": 336, "text": "Note: This function requires the p5.dom library. So add the following line in the head section of the index.html file." }, { "code": "<script language=\"javascript\" type=\"text/javascript\" src=\"path/to/p5.dom.js\"></script>", "e": 546, "s": 455, "text": null }, { "code": null, "e": 554, "s": 546, "text": "Syntax:" }, { "code": null, "e": 561, "s": 554, "text": "html()" }, { "code": null, "e": 564, "s": 561, "text": "or" }, { "code": null, "e": 585, "s": 564, "text": "html( html, append )" }, { "code": null, "e": 597, "s": 585, "text": "Parameters:" }, { "code": null, "e": 703, "s": 597, "text": "html: This parameter holds the HTML element in string format which needs to be placed inside the element." }, { "code": null, "e": 783, "s": 703, "text": "append: This parameter holds the Boolean value to append existing HTML element." }, { "code": null, "e": 874, "s": 783, "text": "Return Value: This function returns a string which contains the inner HTML of the element." }, { "code": null, "e": 930, "s": 874, "text": "Below examples illustrate the html() function in p5.js:" }, { "code": null, "e": 941, "s": 930, "text": "Example 1:" }, { "code": "function setup() { // Create a canvas of given size createCanvas(400, 200); // Set background color background('green'); var div = createDiv(''); // Use html() function div.html('Welcome to GeeksforGeeks'); // Set the position of div element div.position(60, 80); // Set font-size of text div.style('font-size', '24px'); // Set font-color of text div.style('color', 'white'); } ", "e": 1400, "s": 941, "text": null }, { "code": null, "e": 1408, "s": 1400, "text": "Output:" }, { "code": null, "e": 1419, "s": 1408, "text": "Example 2:" }, { "code": "function setup() { // Create canvas of given size createCanvas(400, 200); // Set background color background('green'); var div = createDiv('').size(200, 70); // Use html() function div.html('Welcome to GeeksforGeeks', true); // Set the position of div element div.position(100, 60); // Set font-size of text div.style('font-size', '24px'); // Set font-color of text div.style('color', 'white'); div.style('border', '1px solid white'); div.style('text-align', 'center'); } ", "e": 1986, "s": 1419, "text": null }, { "code": null, "e": 1994, "s": 1986, "text": "Output:" }, { "code": null, "e": 2011, "s": 1994, "text": "JavaScript-p5.js" }, { "code": null, "e": 2022, "s": 2011, "text": "JavaScript" }, { "code": null, "e": 2039, "s": 2022, "text": "Web Technologies" }, { "code": null, "e": 2137, "s": 2039, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2198, "s": 2137, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 2270, "s": 2198, "text": "Differences between Functional Components and Class Components in React" }, { "code": null, "e": 2310, "s": 2270, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 2351, "s": 2310, "text": "Difference Between PUT and PATCH Request" }, { "code": null, "e": 2403, "s": 2351, "text": "How to append HTML code to a div using JavaScript ?" }, { "code": null, "e": 2436, "s": 2403, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 2498, "s": 2436, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 2559, "s": 2498, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 2609, "s": 2559, "text": "How to insert spaces/tabs in text using HTML/CSS?" } ]
exec family of functions in C
10 May, 2022 The exec family of functions replaces the current running process with a new process. It can be used to run a C program by using another C program. It comes under the header file unistd.h. There are many members in the exec family which are shown below with examples. execvp : Using this command, the created child process does not have to run the same program as the parent process does. The exec type system calls allow a process to run any program files, which include a binary executable or a shell script . Syntax: int execvp (const char *file, char *const argv[]); file: points to the file name associated with the file being executed. argv: is a null terminated array of character pointers.Let us see a small example to show how to use execvp() function in C. We will have two .C files , EXEC.c and execDemo.c and we will replace the execDemo.c with EXEC.c by calling execvp() function in execDemo.c . CPP //EXEC.c #include<stdio.h>#include<unistd.h> int main(){ int i; printf("I am EXEC.c called by execvp() "); printf("\n"); return 0;} Now,create an executable file of EXEC.c using command gcc EXEC.c -o EXEC CPP //execDemo.c #include<stdio.h>#include<stdlib.h>#include<unistd.h>int main(){ //A null terminated array of character //pointers char *args[]={"./EXEC",NULL}; execvp(args[0],args); /*All statements are ignored after execvp() call as this whole process(execDemo.c) is replaced by another process (EXEC.c) */ printf("Ending-----"); return 0;} Now, create an executable file of execDemo.c using command gcc execDemo.c -o execDemo After running the executable file of execDemo.cby using command ./excDemo, we get the following output: I AM EXEC.c called by execvp() When the file execDemo.c is compiled, as soon as the statement execvp(args[0],args) is executed, this very program is replaced by the program EXEC.c. “Ending—–” is not printed because as soon as the execvp() function is called, this program is replaced by the program EXEC.c. execv : This is very similar to execvp() function in terms of syntax as well. The syntax of execv() is as shown below: Syntax: int execv(const char *path, char *const argv[]); path: should point to the path of the file being executed. argv[]: is a null terminated array of character pointers.Let us see a small example to show how to use execv() function in C. This example is similar to the example shown above for execvp() . We will have two .C files , EXEC.c and execDemo.c and we will replace the execDemo.c with EXEC.c by calling execv() function in execDemo.c . CPP //EXEC.c #include<stdio.h>#include<unistd.h> int main(){ int i; printf("I am EXEC.c called by execv() "); printf("\n"); return 0;} Now,create an executable file of EXEC.c using command gcc EXEC.c -o EXEC CPP //execDemo.c #include<stdio.h>#include<stdlib.h>#include<unistd.h>int main(){ //A null terminated array of character //pointers char *args[]={"./EXEC",NULL}; execv(args[0],args); /*All statements are ignored after execvp() call as this whole process(execDemo.c) is replaced by another process (EXEC.c) */ printf("Ending-----"); return 0;} Now, create an executable file of execDemo.c using command gcc execDemo.c -o execDemo After running the executable file of execDemo.c by using command ./excDemo, we get the following output: I AM EXEC.c called by execv() execlp and execl : These two also serve the same purpose but the syntax of them are a bit different which is as shown below: Syntax: int execlp(const char *file, const char *arg,.../* (char *) NULL */); int execl(const char *path, const char *arg,.../* (char *) NULL */); file: file name associated with the file being executed const char *arg and ellipses : describe a list of one or more pointers to null-terminated strings that represent the argument list available to the executed program.The same C programs shown above can be executed with execlp() or execl() functions and they will perform the same task i.e. replacing the current process the with a new process. execvpe and execle : These two also serve the same purpose but the syntax of them are a bit different from all the above members of exec family. The syntaxes of both of them are shown below : Syntax: int execvpe(const char *file, char *const argv[],char *const envp[]); Syntax: int execle(const char *path, const char *arg, .../*, (char *) NULL, char * const envp[] */); The syntaxes above shown has one different argument from all the above exec members, i.e. char * const envp[]: allow the caller to specify the environment of the executed program via the argument envp. envp:This argument is an array of pointers to null-terminated strings and must be terminated by a null pointer. The other functions take the environment for the new process image from the external variable environ in the calling process. Reference: exec(3) man pageThis article is contributed by MAZHAR IMAM KHAN. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. AakashkumarGoryan ShubhamMaurya3 simmytarika5 surinderdawra388 C-Library C Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Substring in C++ Function Pointer in C Different Methods to Reverse a String in C++ std::string class in C++ Unordered Sets in C++ Standard Template Library Enumeration (or enum) in C Memory Layout of C Programs C Language Introduction Power Function in C/C++ Command line arguments in C/C++
[ { "code": null, "e": 52, "s": 24, "text": "\n10 May, 2022" }, { "code": null, "e": 321, "s": 52, "text": "The exec family of functions replaces the current running process with a new process. It can be used to run a C program by using another C program. It comes under the header file unistd.h. There are many members in the exec family which are shown below with examples. " }, { "code": null, "e": 566, "s": 321, "text": "execvp : Using this command, the created child process does not have to run the same program as the parent process does. The exec type system calls allow a process to run any program files, which include a binary executable or a shell script . " }, { "code": null, "e": 575, "s": 566, "text": "Syntax: " }, { "code": null, "e": 626, "s": 575, "text": "int execvp (const char *file, char *const argv[]);" }, { "code": null, "e": 965, "s": 626, "text": "file: points to the file name associated with the file being executed. argv: is a null terminated array of character pointers.Let us see a small example to show how to use execvp() function in C. We will have two .C files , EXEC.c and execDemo.c and we will replace the execDemo.c with EXEC.c by calling execvp() function in execDemo.c ." }, { "code": null, "e": 969, "s": 965, "text": "CPP" }, { "code": "//EXEC.c #include<stdio.h>#include<unistd.h> int main(){ int i; printf(\"I am EXEC.c called by execvp() \"); printf(\"\\n\"); return 0;}", "e": 1123, "s": 969, "text": null }, { "code": null, "e": 1178, "s": 1123, "text": "Now,create an executable file of EXEC.c using command " }, { "code": null, "e": 1197, "s": 1178, "text": "gcc EXEC.c -o EXEC" }, { "code": null, "e": 1201, "s": 1197, "text": "CPP" }, { "code": "//execDemo.c #include<stdio.h>#include<stdlib.h>#include<unistd.h>int main(){ //A null terminated array of character //pointers char *args[]={\"./EXEC\",NULL}; execvp(args[0],args); /*All statements are ignored after execvp() call as this whole process(execDemo.c) is replaced by another process (EXEC.c) */ printf(\"Ending-----\"); return 0;}", "e": 1610, "s": 1201, "text": null }, { "code": null, "e": 1670, "s": 1610, "text": "Now, create an executable file of execDemo.c using command " }, { "code": null, "e": 1697, "s": 1670, "text": "gcc execDemo.c -o execDemo" }, { "code": null, "e": 1802, "s": 1697, "text": "After running the executable file of execDemo.cby using command ./excDemo, we get the following output: " }, { "code": null, "e": 1833, "s": 1802, "text": "I AM EXEC.c called by execvp()" }, { "code": null, "e": 2109, "s": 1833, "text": "When the file execDemo.c is compiled, as soon as the statement execvp(args[0],args) is executed, this very program is replaced by the program EXEC.c. “Ending—–” is not printed because as soon as the execvp() function is called, this program is replaced by the program EXEC.c." }, { "code": null, "e": 2228, "s": 2109, "text": "execv : This is very similar to execvp() function in terms of syntax as well. The syntax of execv() is as shown below:" }, { "code": null, "e": 2237, "s": 2228, "text": "Syntax: " }, { "code": null, "e": 2286, "s": 2237, "text": "int execv(const char *path, char *const argv[]);" }, { "code": null, "e": 2679, "s": 2286, "text": "path: should point to the path of the file being executed. argv[]: is a null terminated array of character pointers.Let us see a small example to show how to use execv() function in C. This example is similar to the example shown above for execvp() . We will have two .C files , EXEC.c and execDemo.c and we will replace the execDemo.c with EXEC.c by calling execv() function in execDemo.c . " }, { "code": null, "e": 2683, "s": 2679, "text": "CPP" }, { "code": "//EXEC.c #include<stdio.h>#include<unistd.h> int main(){ int i; printf(\"I am EXEC.c called by execv() \"); printf(\"\\n\"); return 0;}", "e": 2831, "s": 2683, "text": null }, { "code": null, "e": 2886, "s": 2831, "text": "Now,create an executable file of EXEC.c using command " }, { "code": null, "e": 2905, "s": 2886, "text": "gcc EXEC.c -o EXEC" }, { "code": null, "e": 2909, "s": 2905, "text": "CPP" }, { "code": "//execDemo.c #include<stdio.h>#include<stdlib.h>#include<unistd.h>int main(){ //A null terminated array of character //pointers char *args[]={\"./EXEC\",NULL}; execv(args[0],args); /*All statements are ignored after execvp() call as this whole process(execDemo.c) is replaced by another process (EXEC.c) */ printf(\"Ending-----\"); return 0;}", "e": 3317, "s": 2909, "text": null }, { "code": null, "e": 3377, "s": 3317, "text": "Now, create an executable file of execDemo.c using command " }, { "code": null, "e": 3404, "s": 3377, "text": "gcc execDemo.c -o execDemo" }, { "code": null, "e": 3510, "s": 3404, "text": "After running the executable file of execDemo.c by using command ./excDemo, we get the following output: " }, { "code": null, "e": 3540, "s": 3510, "text": "I AM EXEC.c called by execv()" }, { "code": null, "e": 3665, "s": 3540, "text": "execlp and execl : These two also serve the same purpose but the syntax of them are a bit different which is as shown below:" }, { "code": null, "e": 3674, "s": 3665, "text": "Syntax: " }, { "code": null, "e": 3815, "s": 3674, "text": "int execlp(const char *file, const char *arg,.../* (char *) NULL */);\nint execl(const char *path, const char *arg,.../* (char *) NULL */);" }, { "code": null, "e": 4215, "s": 3815, "text": "file: file name associated with the file being executed const char *arg and ellipses : describe a list of one or more pointers to null-terminated strings that represent the argument list available to the executed program.The same C programs shown above can be executed with execlp() or execl() functions and they will perform the same task i.e. replacing the current process the with a new process." }, { "code": null, "e": 4416, "s": 4215, "text": "execvpe and execle : These two also serve the same purpose but the syntax of them are a bit different from all the above members of exec family. The syntaxes of both of them are shown below : Syntax: " }, { "code": null, "e": 4589, "s": 4416, "text": "int execvpe(const char *file, char *const argv[],char *const envp[]);\n\nSyntax:\nint execle(const char *path, const char *arg, .../*, (char *) NULL, \nchar * const envp[] */);" }, { "code": null, "e": 5029, "s": 4589, "text": "The syntaxes above shown has one different argument from all the above exec members, i.e. char * const envp[]: allow the caller to specify the environment of the executed program via the argument envp. envp:This argument is an array of pointers to null-terminated strings and must be terminated by a null pointer. The other functions take the environment for the new process image from the external variable environ in the calling process." }, { "code": null, "e": 5480, "s": 5029, "text": "Reference: exec(3) man pageThis article is contributed by MAZHAR IMAM KHAN. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 5498, "s": 5480, "text": "AakashkumarGoryan" }, { "code": null, "e": 5513, "s": 5498, "text": "ShubhamMaurya3" }, { "code": null, "e": 5526, "s": 5513, "text": "simmytarika5" }, { "code": null, "e": 5543, "s": 5526, "text": "surinderdawra388" }, { "code": null, "e": 5553, "s": 5543, "text": "C-Library" }, { "code": null, "e": 5564, "s": 5553, "text": "C Language" }, { "code": null, "e": 5662, "s": 5564, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 5679, "s": 5662, "text": "Substring in C++" }, { "code": null, "e": 5701, "s": 5679, "text": "Function Pointer in C" }, { "code": null, "e": 5746, "s": 5701, "text": "Different Methods to Reverse a String in C++" }, { "code": null, "e": 5771, "s": 5746, "text": "std::string class in C++" }, { "code": null, "e": 5819, "s": 5771, "text": "Unordered Sets in C++ Standard Template Library" }, { "code": null, "e": 5846, "s": 5819, "text": "Enumeration (or enum) in C" }, { "code": null, "e": 5874, "s": 5846, "text": "Memory Layout of C Programs" }, { "code": null, "e": 5898, "s": 5874, "text": "C Language Introduction" }, { "code": null, "e": 5922, "s": 5898, "text": "Power Function in C/C++" } ]
Filter data in Django Rest Framework
30 May, 2021 Django REST Framework’s generic list view, by default, returns the entire query sets for a model manager. For real-world applications, it is necessary to filter the queryset to retrieve the relevant results based on the need. So, let’s discuss how to create a RESTful Web Service that provides filtering capabilities. DjangoFilterBackend SearchFilter OrderingFilter Note: You can refer The Browsable API section for Models, Serializers, and Views of Project used in the article The DjangoFilterBackend class is used to filter the queryset based on a specified set of fields. This backend class automatically creates a FilterSet (django_filters.rest_framework.FilterSet) class for the given fields. We can also create our own FilterSet class with customized settings. To configure filter backend classes in our Django Web Service, we need to install the django-filter package in our virtual environment. Make sure you quit the Django development server (Ctrl + C) and activate the virtual environment. Let’s run the below command. pip install django-filter After installation, we need to define the django_filters application to INSTALLED_APPS in the settings.py file. Python3 INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', # Django REST framework 'rest_framework', 'robots.apps.RobotsConfig', # Django Filters 'django_filters',] As a next step, we need to set the DjangoFilterBackend class from django_filters as the default filter class. Let’s mention it to the REST_FRAMEWORK dictionary in the settings.py file. Python3 REST_FRAMEWORK = { 'DEFAULT_FILTER_BACKENDS' 'django_filters.rest_framework.DjangoFilterBackend', ),} Now our RESTful web service is configured to make use of the filtering feature provided by django_filters.rest_framework.DjangoFilterBackend class. Let’s filter the robot class that retrieves a list of robots. The RobotList class as follows: Python3 class RobotList(generics.ListCreateAPIView): queryset = Robot.objects.all() serializer_class = RobotSerializer name = 'robot-list' filter_fields = ( 'robot_category', 'manufacturer', ) Here, you can notice an attribute named filter_fileds where we specify the field name to filter against. Now, we can retrieve robots based on their category (robot_category) and/or manufacturer. Let’s filter the robots based on the robot category. The HTTPie command is http “:8000/robot/?robot_category=2” Output: Let’s try another HTTPie command that filters robots based on robot category and manufacturer. The HTTPie command is http “:8000/robot/?robot_category=2&manufacturer=1” Output: Now let’s check the functionality in Browsable API. You can browse the below URL http://127.0.0.1:8000/robot/ You can click the Filters button in the top right corner to make use of the filter feature. It will display as shown below On clicking the submit button you will get the result based on the populated filter fields as shown below. The SearchFilter class supports a single query parameter-based searching feature, and it is based on the Django admin’s search function. By default, SearchFilter class uses case-insensitive partial matches, and it may contain multiple search terms (should be whitespace and/or comma-separated). We can also restrict the search behavior by prepending various characters to the search_fields. ‘^’ Starts-with search. ‘=’ Exact matches. ‘@’ Full-text search. ( for Django’s PostgreSQL backend) ‘$’ Regex search By default, the search parameter is named search, and you can override it with the SEARCH_PARAM setting. Let’s make use of SearchFilter class by adding the rest_framework.filters.SearchFilter class to the REST_FRAMEWORK dictionary. Python3 REST_FRAMEWORK = { 'DEFAULT_FILTER_BACKENDS' 'django_filters.rest_framework.DjangoFilterBackend', 'rest_framework.filters.SearchFilter', ),} Our RobotList class looks as follows: Python3 class RobotList(generics.ListCreateAPIView): queryset = Robot.objects.all() serializer_class = RobotSerializer name = 'robot-list' search_fields = ( '^name', ) The search_fields attribute specifies a tuple of strings, which indicates the field names that we want to include in the search feature. Let’s search the robots, which starts with the name ‘IRB’. The HTTPie command is http “:8000/robot/?search=IRB” Output: The OrderingFilter class allows you to order the result based on the specified fields. By default, the query parameter is named ordering, and it can be overridden with the ORDERING_PARAM setting. The ordering_field attribute specifies a tuple of strings, which indicates the field names to sort the results. If you don’t specify an ordering_fields attribute on the view, the filter class allows the user to filter on any readable fields specified by the serializer_class attribute. This permits the user to order against sensitive information such as password hash fields and so on, which may lead to unexpected data leakage. You can also specify a default order by setting an ordering attribute on the view. It can be either a string or a list/tuple of strings. To make use of OrderingFilter class, we need to set the class as the default ordering filter class to the REST_FRAMEWORK dictionary. Python3 REST_FRAMEWORK = { 'DEFAULT_FILTER_BACKENDS' 'django_filters.rest_framework.DjangoFilterBackend', 'rest_framework.filters.OrderingFilter', ),} Let’s mention the ordering_fields attribute on the RobotList class. The code as follows: Python3 class RobotList(generics.ListCreateAPIView): queryset = Robot.objects.all() serializer_class = RobotSerializer name = 'robot-list' ordering_fields = ( 'price', ) Now, let’s retrieve robots based on the increase in price order. The HTTPie command is http “:8000/robot/?ordering=price” Output: Django-REST 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 How to drop one or multiple columns in Pandas Dataframe Python | os.path.join() method Check if element exists in list in Python How To Convert Python Dictionary To JSON? Python | Get unique values from a list Python | datetime.timedelta() function
[ { "code": null, "e": 28, "s": 0, "text": "\n30 May, 2021" }, { "code": null, "e": 348, "s": 28, "text": "Django REST Framework’s generic list view, by default, returns the entire query sets for a model manager. For real-world applications, it is necessary to filter the queryset to retrieve the relevant results based on the need. So, let’s discuss how to create a RESTful Web Service that provides filtering capabilities. " }, { "code": null, "e": 368, "s": 348, "text": "DjangoFilterBackend" }, { "code": null, "e": 381, "s": 368, "text": "SearchFilter" }, { "code": null, "e": 396, "s": 381, "text": "OrderingFilter" }, { "code": null, "e": 508, "s": 396, "text": "Note: You can refer The Browsable API section for Models, Serializers, and Views of Project used in the article" }, { "code": null, "e": 797, "s": 508, "text": "The DjangoFilterBackend class is used to filter the queryset based on a specified set of fields. This backend class automatically creates a FilterSet (django_filters.rest_framework.FilterSet) class for the given fields. We can also create our own FilterSet class with customized settings." }, { "code": null, "e": 1060, "s": 797, "text": "To configure filter backend classes in our Django Web Service, we need to install the django-filter package in our virtual environment. Make sure you quit the Django development server (Ctrl + C) and activate the virtual environment. Let’s run the below command." }, { "code": null, "e": 1086, "s": 1060, "text": "pip install django-filter" }, { "code": null, "e": 1198, "s": 1086, "text": "After installation, we need to define the django_filters application to INSTALLED_APPS in the settings.py file." }, { "code": null, "e": 1206, "s": 1198, "text": "Python3" }, { "code": "INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', # Django REST framework 'rest_framework', 'robots.apps.RobotsConfig', # Django Filters 'django_filters',]", "e": 1526, "s": 1206, "text": null }, { "code": null, "e": 1712, "s": 1526, "text": "As a next step, we need to set the DjangoFilterBackend class from django_filters as the default filter class. Let’s mention it to the REST_FRAMEWORK dictionary in the settings.py file. " }, { "code": null, "e": 1720, "s": 1712, "text": "Python3" }, { "code": "REST_FRAMEWORK = { 'DEFAULT_FILTER_BACKENDS' 'django_filters.rest_framework.DjangoFilterBackend', ),}", "e": 1835, "s": 1720, "text": null }, { "code": null, "e": 2077, "s": 1835, "text": "Now our RESTful web service is configured to make use of the filtering feature provided by django_filters.rest_framework.DjangoFilterBackend class. Let’s filter the robot class that retrieves a list of robots. The RobotList class as follows:" }, { "code": null, "e": 2085, "s": 2077, "text": "Python3" }, { "code": "class RobotList(generics.ListCreateAPIView): queryset = Robot.objects.all() serializer_class = RobotSerializer name = 'robot-list' filter_fields = ( 'robot_category', 'manufacturer', )", "e": 2305, "s": 2085, "text": null }, { "code": null, "e": 2501, "s": 2305, "text": "Here, you can notice an attribute named filter_fileds where we specify the field name to filter against. Now, we can retrieve robots based on their category (robot_category) and/or manufacturer. " }, { "code": null, "e": 2576, "s": 2501, "text": "Let’s filter the robots based on the robot category. The HTTPie command is" }, { "code": null, "e": 2613, "s": 2576, "text": "http “:8000/robot/?robot_category=2”" }, { "code": null, "e": 2621, "s": 2613, "text": "Output:" }, { "code": null, "e": 2738, "s": 2621, "text": "Let’s try another HTTPie command that filters robots based on robot category and manufacturer. The HTTPie command is" }, { "code": null, "e": 2790, "s": 2738, "text": "http “:8000/robot/?robot_category=2&manufacturer=1”" }, { "code": null, "e": 2798, "s": 2790, "text": "Output:" }, { "code": null, "e": 2879, "s": 2798, "text": "Now let’s check the functionality in Browsable API. You can browse the below URL" }, { "code": null, "e": 2908, "s": 2879, "text": "http://127.0.0.1:8000/robot/" }, { "code": null, "e": 3031, "s": 2908, "text": "You can click the Filters button in the top right corner to make use of the filter feature. It will display as shown below" }, { "code": null, "e": 3138, "s": 3031, "text": "On clicking the submit button you will get the result based on the populated filter fields as shown below." }, { "code": null, "e": 3275, "s": 3138, "text": "The SearchFilter class supports a single query parameter-based searching feature, and it is based on the Django admin’s search function." }, { "code": null, "e": 3530, "s": 3275, "text": "By default, SearchFilter class uses case-insensitive partial matches, and it may contain multiple search terms (should be whitespace and/or comma-separated). We can also restrict the search behavior by prepending various characters to the search_fields. " }, { "code": null, "e": 3554, "s": 3530, "text": "‘^’ Starts-with search." }, { "code": null, "e": 3573, "s": 3554, "text": "‘=’ Exact matches." }, { "code": null, "e": 3630, "s": 3573, "text": "‘@’ Full-text search. ( for Django’s PostgreSQL backend)" }, { "code": null, "e": 3647, "s": 3630, "text": "‘$’ Regex search" }, { "code": null, "e": 3880, "s": 3647, "text": "By default, the search parameter is named search, and you can override it with the SEARCH_PARAM setting. Let’s make use of SearchFilter class by adding the rest_framework.filters.SearchFilter class to the REST_FRAMEWORK dictionary. " }, { "code": null, "e": 3888, "s": 3880, "text": "Python3" }, { "code": "REST_FRAMEWORK = { 'DEFAULT_FILTER_BACKENDS' 'django_filters.rest_framework.DjangoFilterBackend', 'rest_framework.filters.SearchFilter', ),}", "e": 4049, "s": 3888, "text": null }, { "code": null, "e": 4087, "s": 4049, "text": "Our RobotList class looks as follows:" }, { "code": null, "e": 4095, "s": 4087, "text": "Python3" }, { "code": "class RobotList(generics.ListCreateAPIView): queryset = Robot.objects.all() serializer_class = RobotSerializer name = 'robot-list' search_fields = ( '^name', )", "e": 4283, "s": 4095, "text": null }, { "code": null, "e": 4421, "s": 4283, "text": "The search_fields attribute specifies a tuple of strings, which indicates the field names that we want to include in the search feature. " }, { "code": null, "e": 4502, "s": 4421, "text": "Let’s search the robots, which starts with the name ‘IRB’. The HTTPie command is" }, { "code": null, "e": 4533, "s": 4502, "text": "http “:8000/robot/?search=IRB”" }, { "code": null, "e": 4541, "s": 4533, "text": "Output:" }, { "code": null, "e": 4849, "s": 4541, "text": "The OrderingFilter class allows you to order the result based on the specified fields. By default, the query parameter is named ordering, and it can be overridden with the ORDERING_PARAM setting. The ordering_field attribute specifies a tuple of strings, which indicates the field names to sort the results." }, { "code": null, "e": 5304, "s": 4849, "text": "If you don’t specify an ordering_fields attribute on the view, the filter class allows the user to filter on any readable fields specified by the serializer_class attribute. This permits the user to order against sensitive information such as password hash fields and so on, which may lead to unexpected data leakage. You can also specify a default order by setting an ordering attribute on the view. It can be either a string or a list/tuple of strings." }, { "code": null, "e": 5438, "s": 5304, "text": "To make use of OrderingFilter class, we need to set the class as the default ordering filter class to the REST_FRAMEWORK dictionary." }, { "code": null, "e": 5446, "s": 5438, "text": "Python3" }, { "code": "REST_FRAMEWORK = { 'DEFAULT_FILTER_BACKENDS' 'django_filters.rest_framework.DjangoFilterBackend', 'rest_framework.filters.OrderingFilter', ),}", "e": 5609, "s": 5446, "text": null }, { "code": null, "e": 5698, "s": 5609, "text": "Let’s mention the ordering_fields attribute on the RobotList class. The code as follows:" }, { "code": null, "e": 5706, "s": 5698, "text": "Python3" }, { "code": "class RobotList(generics.ListCreateAPIView): queryset = Robot.objects.all() serializer_class = RobotSerializer name = 'robot-list' ordering_fields = ( 'price', )", "e": 5892, "s": 5706, "text": null }, { "code": null, "e": 5979, "s": 5892, "text": "Now, let’s retrieve robots based on the increase in price order. The HTTPie command is" }, { "code": null, "e": 6014, "s": 5979, "text": "http “:8000/robot/?ordering=price”" }, { "code": null, "e": 6022, "s": 6014, "text": "Output:" }, { "code": null, "e": 6034, "s": 6022, "text": "Django-REST" }, { "code": null, "e": 6048, "s": 6034, "text": "Python Django" }, { "code": null, "e": 6055, "s": 6048, "text": "Python" }, { "code": null, "e": 6153, "s": 6055, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 6185, "s": 6153, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 6212, "s": 6185, "text": "Python Classes and Objects" }, { "code": null, "e": 6233, "s": 6212, "text": "Python OOPs Concepts" }, { "code": null, "e": 6256, "s": 6233, "text": "Introduction To PYTHON" }, { "code": null, "e": 6312, "s": 6256, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 6343, "s": 6312, "text": "Python | os.path.join() method" }, { "code": null, "e": 6385, "s": 6343, "text": "Check if element exists in list in Python" }, { "code": null, "e": 6427, "s": 6385, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 6466, "s": 6427, "text": "Python | Get unique values from a list" } ]
How to Swap Two Elements in a LinkedList in Java?
15 Feb, 2022 Given a Linked List, the task is to swap two elements without disturbing their links. There are multiple ways to swap. Elements can be swapped using by swapping the elements inside the nodes, and by swapping the complete nodes. Example: Input :- 10->11->12->13->14->15 element1 = 11 element2 = 14 Output :- 10->14->12->13->11->15 Method 1: Using the in-built set method Swap the two elements in a Linked List using the Java.util.LinkedList.set() method. In order to achieve our desired output, first, make sure that both the elements provided to us are available in the Linked List. If either of the elements is absent, simply return. Use the set() method to set the element1’s position to element2’s and vice versa. Below is the code for the above approach: Java // Swapping two elements in a Linked List in Java import java.util.*; class GFG { public static void main(String[] args) { LinkedList<Integer> ll = new LinkedList<>(); // Adding elements to Linked List ll.add(10); ll.add(11); ll.add(12); ll.add(13); ll.add(14); ll.add(15); // Elements to swap int element1 = 11; int element2 = 14; System.out.println("Linked List Before Swapping :-"); for (int i : ll) { System.out.print(i + " "); } // Swapping the elements swap(ll, element1, element2); System.out.println(); System.out.println(); System.out.println("Linked List After Swapping :-"); for (int i : ll) { System.out.print(i + " "); } } // Swap Function public static void swap(LinkedList<Integer> list, int ele1, int ele2) { // Getting the positions of the elements int index1 = list.indexOf(ele1); int index2 = list.indexOf(ele2); // Returning if the element is not present in the // LinkedList if (index1 == -1 || index2 == -1) { return; } // Swapping the elements list.set(index1, ele2); list.set(index2, ele1); }} Linked List Before Swapping :- 10 11 12 13 14 15 Linked List After Swapping :- 10 14 12 13 11 15 Time Complexity: O(N), where N is the length of Linked List Method 2: Using our very own Linked List Given a linked list, provided with two values, and swap nodes for two given nodes. Below is the implementation of the above approach: Java // Java Program to Swap Two Elements in a LinkedListclass Node { int data; Node next; Node(int d) { data = d; next = null; }} class LinkedList { Node head; // head of list // Function to swap Nodes x and y in // linked list by changing links public void swapNodes(int x, int y) { // Nothing to do if x and y are same if (x == y) return; // Search for x (keep track of prevX and CurrX) Node prevX = null, currX = head; while (currX != null && currX.data != x) { prevX = currX; currX = currX.next; } // Search for y (keep track of prevY and currY) Node prevY = null, currY = head; while (currY != null && currY.data != y) { prevY = currY; currY = currY.next; } // If either x or y is not present, nothing to do if (currX == null || currY == null) return; // If x is not head of linked list if (prevX != null) prevX.next = currY; else // make y the new head head = currY; // If y is not head of linked list if (prevY != null) prevY.next = currX; else // make x the new head head = currX; // Swap next pointers Node temp = currX.next; currX.next = currY.next; currY.next = temp; } // Function to add Node at beginning of list. public void push(int new_data) { // 1. alloc the Node and put the data Node new_Node = new Node(new_data); // 2. Make next of new Node as head new_Node.next = head; // 3. Move the head to point to new Node head = new_Node; } // This function prints contents of linked // list starting from the given Node public void printList() { Node tNode = head; while (tNode != null) { System.out.print(tNode.data + " "); tNode = tNode.next; } System.out.println(); } // Driver program to test above function public static void main(String[] args) { LinkedList llist = new LinkedList(); // The constructed linked list is: // 1->2->3->4->5->6->7 llist.push(7); llist.push(6); llist.push(5); llist.push(4); llist.push(3); llist.push(2); llist.push(1); System.out.println("Linked List Before Swapping :-"); llist.printList(); llist.swapNodes(4, 3); System.out.println("Linked List After Swapping :-"); llist.printList(); }} Linked List Before Swapping :- 1 2 3 4 5 6 7 Linked List After Swapping :- 1 2 4 3 5 6 7 Time Complexity: O(N), where N is the length of Linked List saurabh1990aror java-LinkedList Picked Java Java Programs Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Stream In Java Introduction to Java Constructors in Java Exceptions in Java Generics in Java Java Programming Examples Convert Double to Integer in Java Implementing a Linked List in Java using Class Factory method design pattern in Java Java Program to Remove Duplicate Elements From the Array
[ { "code": null, "e": 53, "s": 25, "text": "\n15 Feb, 2022" }, { "code": null, "e": 282, "s": 53, "text": "Given a Linked List, the task is to swap two elements without disturbing their links. There are multiple ways to swap. Elements can be swapped using by swapping the elements inside the nodes, and by swapping the complete nodes. " }, { "code": null, "e": 291, "s": 282, "text": "Example:" }, { "code": null, "e": 412, "s": 291, "text": "Input :- 10->11->12->13->14->15\n element1 = 11\n element2 = 14\n \nOutput :- 10->14->12->13->11->15" }, { "code": null, "e": 452, "s": 412, "text": "Method 1: Using the in-built set method" }, { "code": null, "e": 799, "s": 452, "text": "Swap the two elements in a Linked List using the Java.util.LinkedList.set() method. In order to achieve our desired output, first, make sure that both the elements provided to us are available in the Linked List. If either of the elements is absent, simply return. Use the set() method to set the element1’s position to element2’s and vice versa." }, { "code": null, "e": 841, "s": 799, "text": "Below is the code for the above approach:" }, { "code": null, "e": 846, "s": 841, "text": "Java" }, { "code": "// Swapping two elements in a Linked List in Java import java.util.*; class GFG { public static void main(String[] args) { LinkedList<Integer> ll = new LinkedList<>(); // Adding elements to Linked List ll.add(10); ll.add(11); ll.add(12); ll.add(13); ll.add(14); ll.add(15); // Elements to swap int element1 = 11; int element2 = 14; System.out.println(\"Linked List Before Swapping :-\"); for (int i : ll) { System.out.print(i + \" \"); } // Swapping the elements swap(ll, element1, element2); System.out.println(); System.out.println(); System.out.println(\"Linked List After Swapping :-\"); for (int i : ll) { System.out.print(i + \" \"); } } // Swap Function public static void swap(LinkedList<Integer> list, int ele1, int ele2) { // Getting the positions of the elements int index1 = list.indexOf(ele1); int index2 = list.indexOf(ele2); // Returning if the element is not present in the // LinkedList if (index1 == -1 || index2 == -1) { return; } // Swapping the elements list.set(index1, ele2); list.set(index2, ele1); }}", "e": 2188, "s": 846, "text": null }, { "code": null, "e": 2287, "s": 2188, "text": "Linked List Before Swapping :-\n10 11 12 13 14 15 \n\nLinked List After Swapping :-\n10 14 12 13 11 15" }, { "code": null, "e": 2347, "s": 2287, "text": "Time Complexity: O(N), where N is the length of Linked List" }, { "code": null, "e": 2388, "s": 2347, "text": "Method 2: Using our very own Linked List" }, { "code": null, "e": 2471, "s": 2388, "text": "Given a linked list, provided with two values, and swap nodes for two given nodes." }, { "code": null, "e": 2522, "s": 2471, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 2527, "s": 2522, "text": "Java" }, { "code": "// Java Program to Swap Two Elements in a LinkedListclass Node { int data; Node next; Node(int d) { data = d; next = null; }} class LinkedList { Node head; // head of list // Function to swap Nodes x and y in // linked list by changing links public void swapNodes(int x, int y) { // Nothing to do if x and y are same if (x == y) return; // Search for x (keep track of prevX and CurrX) Node prevX = null, currX = head; while (currX != null && currX.data != x) { prevX = currX; currX = currX.next; } // Search for y (keep track of prevY and currY) Node prevY = null, currY = head; while (currY != null && currY.data != y) { prevY = currY; currY = currY.next; } // If either x or y is not present, nothing to do if (currX == null || currY == null) return; // If x is not head of linked list if (prevX != null) prevX.next = currY; else // make y the new head head = currY; // If y is not head of linked list if (prevY != null) prevY.next = currX; else // make x the new head head = currX; // Swap next pointers Node temp = currX.next; currX.next = currY.next; currY.next = temp; } // Function to add Node at beginning of list. public void push(int new_data) { // 1. alloc the Node and put the data Node new_Node = new Node(new_data); // 2. Make next of new Node as head new_Node.next = head; // 3. Move the head to point to new Node head = new_Node; } // This function prints contents of linked // list starting from the given Node public void printList() { Node tNode = head; while (tNode != null) { System.out.print(tNode.data + \" \"); tNode = tNode.next; } System.out.println(); } // Driver program to test above function public static void main(String[] args) { LinkedList llist = new LinkedList(); // The constructed linked list is: // 1->2->3->4->5->6->7 llist.push(7); llist.push(6); llist.push(5); llist.push(4); llist.push(3); llist.push(2); llist.push(1); System.out.println(\"Linked List Before Swapping :-\"); llist.printList(); llist.swapNodes(4, 3); System.out.println(\"Linked List After Swapping :-\"); llist.printList(); }}", "e": 5139, "s": 2527, "text": null }, { "code": null, "e": 5229, "s": 5139, "text": "Linked List Before Swapping :-\n1 2 3 4 5 6 7 \nLinked List After Swapping :-\n1 2 4 3 5 6 7" }, { "code": null, "e": 5289, "s": 5229, "text": "Time Complexity: O(N), where N is the length of Linked List" }, { "code": null, "e": 5305, "s": 5289, "text": "saurabh1990aror" }, { "code": null, "e": 5321, "s": 5305, "text": "java-LinkedList" }, { "code": null, "e": 5328, "s": 5321, "text": "Picked" }, { "code": null, "e": 5333, "s": 5328, "text": "Java" }, { "code": null, "e": 5347, "s": 5333, "text": "Java Programs" }, { "code": null, "e": 5352, "s": 5347, "text": "Java" }, { "code": null, "e": 5450, "s": 5352, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 5465, "s": 5450, "text": "Stream In Java" }, { "code": null, "e": 5486, "s": 5465, "text": "Introduction to Java" }, { "code": null, "e": 5507, "s": 5486, "text": "Constructors in Java" }, { "code": null, "e": 5526, "s": 5507, "text": "Exceptions in Java" }, { "code": null, "e": 5543, "s": 5526, "text": "Generics in Java" }, { "code": null, "e": 5569, "s": 5543, "text": "Java Programming Examples" }, { "code": null, "e": 5603, "s": 5569, "text": "Convert Double to Integer in Java" }, { "code": null, "e": 5650, "s": 5603, "text": "Implementing a Linked List in Java using Class" }, { "code": null, "e": 5688, "s": 5650, "text": "Factory method design pattern in Java" } ]
numpy.rollaxis() function | Python
22 Apr, 2020 numpy.rollaxis() function roll the specified axis backwards, until it lies in a given position. Syntax : numpy.rollaxis(arr, axis, start=0)Parameters :arr : [ndarray] Input array.axis : [int] The axis to roll backwards. The positions of the other axes do not change relative to one another.start : [int, optional] The axis is rolled until it lies before this position. The default, 0, results in a “complete” roll.Return : [ndarray] In earlier NumPy versions, arr is returned only if the order of the axes is changed, otherwise the input array is returned. For NumPy >= 1.10.0, a view of arr is always returned. Code #1 : # Python program explaining# numpy.rollaxis() function # importing numpy as geek import numpy as geek arr = geek.ones((1, 2, 3, 4)) gfg = geek.rollaxis(arr, 3, 1).shape print (gfg) Output : (1, 4, 2, 3) Code #2 : # Python program explaining# numpy.rollaxis() function # importing numpy as geek import numpy as geek arr = geek.ones((1, 2, 3, 4)) gfg = geek.rollaxis(arr, 2).shape print (gfg) Output : (3, 1, 2, 4) Python numpy-arrayManipulation 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 | os.path.join() method Introduction To PYTHON Python OOPs Concepts How to drop one or multiple columns in Pandas Dataframe How To Convert Python Dictionary To JSON? Check if element exists in list in Python Python | Get unique values from a list Create a directory in Python
[ { "code": null, "e": 28, "s": 0, "text": "\n22 Apr, 2020" }, { "code": null, "e": 124, "s": 28, "text": "numpy.rollaxis() function roll the specified axis backwards, until it lies in a given position." }, { "code": null, "e": 640, "s": 124, "text": "Syntax : numpy.rollaxis(arr, axis, start=0)Parameters :arr : [ndarray] Input array.axis : [int] The axis to roll backwards. The positions of the other axes do not change relative to one another.start : [int, optional] The axis is rolled until it lies before this position. The default, 0, results in a “complete” roll.Return : [ndarray] In earlier NumPy versions, arr is returned only if the order of the axes is changed, otherwise the input array is returned. For NumPy >= 1.10.0, a view of arr is always returned." }, { "code": null, "e": 650, "s": 640, "text": "Code #1 :" }, { "code": "# Python program explaining# numpy.rollaxis() function # importing numpy as geek import numpy as geek arr = geek.ones((1, 2, 3, 4)) gfg = geek.rollaxis(arr, 3, 1).shape print (gfg)", "e": 835, "s": 650, "text": null }, { "code": null, "e": 844, "s": 835, "text": "Output :" }, { "code": null, "e": 858, "s": 844, "text": "(1, 4, 2, 3)\n" }, { "code": null, "e": 869, "s": 858, "text": " Code #2 :" }, { "code": "# Python program explaining# numpy.rollaxis() function # importing numpy as geek import numpy as geek arr = geek.ones((1, 2, 3, 4)) gfg = geek.rollaxis(arr, 2).shape print (gfg)", "e": 1051, "s": 869, "text": null }, { "code": null, "e": 1060, "s": 1051, "text": "Output :" }, { "code": null, "e": 1074, "s": 1060, "text": "(3, 1, 2, 4)\n" }, { "code": null, "e": 1105, "s": 1074, "text": "Python numpy-arrayManipulation" }, { "code": null, "e": 1118, "s": 1105, "text": "Python-numpy" }, { "code": null, "e": 1125, "s": 1118, "text": "Python" }, { "code": null, "e": 1223, "s": 1125, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1255, "s": 1223, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 1282, "s": 1255, "text": "Python Classes and Objects" }, { "code": null, "e": 1313, "s": 1282, "text": "Python | os.path.join() method" }, { "code": null, "e": 1336, "s": 1313, "text": "Introduction To PYTHON" }, { "code": null, "e": 1357, "s": 1336, "text": "Python OOPs Concepts" }, { "code": null, "e": 1413, "s": 1357, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 1455, "s": 1413, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 1497, "s": 1455, "text": "Check if element exists in list in Python" }, { "code": null, "e": 1536, "s": 1497, "text": "Python | Get unique values from a list" } ]
java.net.Socket Class in Java
29 Mar, 2021 The java.net.Socket class allows us to create socket objects that help us in implementing all fundamental socket operations. We can perform various networking operations such as sending, reading data and closing connections. Each Socket object that has been created using with java.net.Socket class has been associated exactly with 1 remote host, for connecting to another different host, we must create a new socket object. The syntax for importing Socket class from java.net package : import java.net.Socket; Methods used in Socket class : Applications of Socket Class: 1. Socket class is implemented in creating a stream socket and which is connected to a specified port number and port address. public Socket(InetAddress address, int port) 2. Socket class is used for the creation of socket and connecting to the specified remote address on the specified remote port in javax.net SocketFactory.createSocket(InetAddress address, int port, InetAddress localAddress, int localPort) 3. In javax.ssl.net, the Socket class is used to return a socket layered over an existing socket connected to the named host at a given port. SSLSocketFactory.createSocket(Socket s, String host, int port, boolean autoClose) 4. In javax.rmi.ssl, Socket class is used for creating an SSL socket. SslRMIClientSocketFactory.createSocket(String host, int port) 5. In java.nio.channels, Socket class is used for retrieving a socket associated with its channel SocketChannel.socket() Java Example for Socket class Implementation : 1. For Server Side: Java import java.io.*;import java.net.*;public class MyServer { public static void main(String[] args) { try { ServerSocket ss = new ServerSocket(6666); // establishes connection Socket soc = ss.accept(); // invoking input stream DataInputStream dis = new DataInputStream(s.getInputStream()); String str = (String)dis.readUTF(); System.out.println("message= " + str); // closing socket ss.close(); } // for catching Exception in run time catch (Exception e) { System.out.println(e); } }} Output on Client : 2. For Client Side : Java import java.io.*;import java.net.*;public class MyClient { public static void main(String[] args) { try { // initializing Socket Socket soc = new Socket("localhost", 6666); DataOutputStream d = new DataOutputStream( soc.getOutputStream()); // message to display d.writeUTF("Hello GFG Readers!"); d.flush(); // closing DataOutputStream d.close(); // closing socket soc.close(); } // to initialize Exception in run time catch (Exception e) { System.out.println(e); } }} Output on server : Java-net-package Picked Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Interfaces in Java ArrayList in Java Collections in Java Stream In Java Multidimensional Arrays in Java Singleton Class in Java Set in Java Stack Class in Java Initializing a List in Java Introduction to Java
[ { "code": null, "e": 53, "s": 25, "text": "\n29 Mar, 2021" }, { "code": null, "e": 478, "s": 53, "text": "The java.net.Socket class allows us to create socket objects that help us in implementing all fundamental socket operations. We can perform various networking operations such as sending, reading data and closing connections. Each Socket object that has been created using with java.net.Socket class has been associated exactly with 1 remote host, for connecting to another different host, we must create a new socket object." }, { "code": null, "e": 540, "s": 478, "text": "The syntax for importing Socket class from java.net package :" }, { "code": null, "e": 564, "s": 540, "text": "import java.net.Socket;" }, { "code": null, "e": 597, "s": 564, "text": " Methods used in Socket class : " }, { "code": null, "e": 627, "s": 597, "text": "Applications of Socket Class:" }, { "code": null, "e": 754, "s": 627, "text": "1. Socket class is implemented in creating a stream socket and which is connected to a specified port number and port address." }, { "code": null, "e": 799, "s": 754, "text": "public Socket(InetAddress address, int port)" }, { "code": null, "e": 939, "s": 799, "text": "2. Socket class is used for the creation of socket and connecting to the specified remote address on the specified remote port in javax.net" }, { "code": null, "e": 1042, "s": 939, "text": " SocketFactory.createSocket(InetAddress address, int port, InetAddress localAddress, int localPort)" }, { "code": null, "e": 1184, "s": 1042, "text": "3. In javax.ssl.net, the Socket class is used to return a socket layered over an existing socket connected to the named host at a given port." }, { "code": null, "e": 1266, "s": 1184, "text": "SSLSocketFactory.createSocket(Socket s, String host, int port, boolean autoClose)" }, { "code": null, "e": 1336, "s": 1266, "text": "4. In javax.rmi.ssl, Socket class is used for creating an SSL socket." }, { "code": null, "e": 1398, "s": 1336, "text": "SslRMIClientSocketFactory.createSocket(String host, int port)" }, { "code": null, "e": 1496, "s": 1398, "text": "5. In java.nio.channels, Socket class is used for retrieving a socket associated with its channel" }, { "code": null, "e": 1519, "s": 1496, "text": "SocketChannel.socket()" }, { "code": null, "e": 1566, "s": 1519, "text": "Java Example for Socket class Implementation :" }, { "code": null, "e": 1586, "s": 1566, "text": "1. For Server Side:" }, { "code": null, "e": 1591, "s": 1586, "text": "Java" }, { "code": "import java.io.*;import java.net.*;public class MyServer { public static void main(String[] args) { try { ServerSocket ss = new ServerSocket(6666); // establishes connection Socket soc = ss.accept(); // invoking input stream DataInputStream dis = new DataInputStream(s.getInputStream()); String str = (String)dis.readUTF(); System.out.println(\"message= \" + str); // closing socket ss.close(); } // for catching Exception in run time catch (Exception e) { System.out.println(e); } }}", "e": 2308, "s": 1591, "text": null }, { "code": null, "e": 2327, "s": 2308, "text": "Output on Client :" }, { "code": null, "e": 2348, "s": 2327, "text": "2. For Client Side :" }, { "code": null, "e": 2353, "s": 2348, "text": "Java" }, { "code": "import java.io.*;import java.net.*;public class MyClient { public static void main(String[] args) { try { // initializing Socket Socket soc = new Socket(\"localhost\", 6666); DataOutputStream d = new DataOutputStream( soc.getOutputStream()); // message to display d.writeUTF(\"Hello GFG Readers!\"); d.flush(); // closing DataOutputStream d.close(); // closing socket soc.close(); } // to initialize Exception in run time catch (Exception e) { System.out.println(e); } }}", "e": 3087, "s": 2353, "text": null }, { "code": null, "e": 3106, "s": 3087, "text": "Output on server :" }, { "code": null, "e": 3123, "s": 3106, "text": "Java-net-package" }, { "code": null, "e": 3130, "s": 3123, "text": "Picked" }, { "code": null, "e": 3135, "s": 3130, "text": "Java" }, { "code": null, "e": 3140, "s": 3135, "text": "Java" }, { "code": null, "e": 3238, "s": 3140, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3257, "s": 3238, "text": "Interfaces in Java" }, { "code": null, "e": 3275, "s": 3257, "text": "ArrayList in Java" }, { "code": null, "e": 3295, "s": 3275, "text": "Collections in Java" }, { "code": null, "e": 3310, "s": 3295, "text": "Stream In Java" }, { "code": null, "e": 3342, "s": 3310, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 3366, "s": 3342, "text": "Singleton Class in Java" }, { "code": null, "e": 3378, "s": 3366, "text": "Set in Java" }, { "code": null, "e": 3398, "s": 3378, "text": "Stack Class in Java" }, { "code": null, "e": 3426, "s": 3398, "text": "Initializing a List in Java" } ]
Shaping and reshaping NumPy and pandas objects to avoid errors | Towards Data Science
Shape errors are the bane of many folks learning data science. I would bet money that people have quit their data science learning journey due to frustration with getting data into the shape required for machine learning algorithms. Having a stronger understanding of how to reshape your data will spare you tears, save you time, and help you grow as a data scientist. In this article, you’ll see how to get your data in the shape you need it. 🎉 First, let’s make sure we’re using similar package versions. Let’s import the libraries we’ll need under their usual aliases. All code is available here. import sysimport numpy as npimport pandas as pdimport sklearnfrom sklearn.preprocessing import OneHotEncoderfrom sklearn.linear_model import LogisticRegression If you don’t have the libraries you need installed, uncomment the following cell and run it. Then run the cell imports again. You may need to restart your kernel. # !pip install -U numpy pandas scikit-learn Let’s check our package versions. print(f"Python: {sys.version}")print(f'NumPy: {np.__version__}')print(f'pandas: {pd.__version__}')print(f'scikit-learn: {sklearn.__version__}')Python: 3.8.5 (default, Sep 4 2020, 02:22:02) [Clang 10.0.0 ]NumPy: 1.19.2pandas: 1.2.0scikit-learn: 0.24.0 A pandas DataFrame has two dimensions: the rows and the columns. Let’s make a tiny DataFrame with some hurricane data. df_hurricanes = pd.DataFrame(dict( name=['Zeta', 'Andrew', 'Agnes'], year=[2020, 1992, 1972 ]))df_hurricanes You can see the number of dimensions for a pandas data structure with the ndim attribute. df_hurricanes.ndim2 A DataFrame has both rows and columns, so it has two dimensions. The shape attribute shows the number of items in each dimension. Checking a DataFrame’s shape returns a tuple with two integers. The first is the number of rows and the second is the number of columns. 👍 df_hurricanes.shape(3, 2) We have three rows and two columns. Cool. 😎 The size attribute shows us how many cells we have. df_hurricanes.size6 3 * 2 = 6 It’s easy to get the number of dimensions and size form the shape attribute so that’s the one to remember and the one we’ll use. 🚀 Let’s make a pandas Series from our DataFrame. Use just the brackets syntax to select a column by passing the name of the column as a string. You get back a Series. years_series = df_hurricanes['year']years_series0 20201 19922 1972Name: year, dtype: int64type(years_series)pandas.core.series.Series What does the shape of a pandas Series look like? We can use the Series shape attribute to find out. years_series.shape(3,) We have a tuple with just one value, the number of rows. Remember that the index doesn’t count as a column. ☝️ What happens if we use just the brackets again, except this time we pass a list containing a single column name? years_df = df_hurricanes[['year']]years_df type(years_df)pandas.core.frame.DataFrame My variable name might have given away the answer. 😉 You always get back a DataFrame if you pass a list of column names. years_df.shape(3, 1) Take away: the shape of a pandas Series and the shape of a pandas DataFrame with one column are different! A DataFrame has a shape of rows by columns and a Series has a shape of rows. This is a key point that trips folks up. Now that we know about finding the shape in pandas, let’s look at using NumPy. Pandas extends NumPy. NumPy’s ndarray is its core data structure — we’ll just refer to it as an array from here on. There are many ways to create NumPy arrays, depending upon your goals. Check out my guide on the topic here. Let’s make a NumPy array from our DataFrame and check its shape. two_d_arr = df_hurricanes.to_numpy()two_d_arrarray([['Zeta', 2020], ['Andrew', 1992], ['Agnes', 1972]], dtype=object)type(two_d_arr)numpy.ndarraytwo_d_arr.shape(3, 2) The shape returned matches what we saw when we used pandas. Pandas and NumPy share some attributes and methods, including the shape attribute. Let’s convert the pandas Series we made earlier into a NumPy array and check its shape. one_d_arr = years_series.to_numpy()one_d_arrarray([2020, 1992, 1972])type(one_d_arr)numpy.ndarrayone_d_arr.shape(3,) Again, we see the same result in pandas and NumPy. Cool! Things get tricky when an object expects data to arrive in a certain shape. For example, most scikit-learn transformers and estimators expect to be fed their predictive X data in two-dimensional form. The target variable, y is expected to be one-dimensional. Let’s demonstrate how to reshape with a silly example where we use year to predict the hurricane name. We’ll make x lowercase because it has just one dimension. x = df_hurricanes['year']x0 20201 19922 1972Name: year, dtype: int64type(x)pandas.core.series.Seriesx.shape(3,) Same goes for our output variable, y. y = df_hurricanes['name']y0 Zeta1 Andrew2 AgnesName: name, dtype: objecttype(y)pandas.core.series.Seriesy.shape(3,) Let’s instantiate and fit a LogisticRegression model. lr = LogisticRegression()lr.fit(x, y) And you get a value error. The last lines read: ValueError: Expected 2D array, got 1D array instead:array=[2020. 1992. 1972.].Reshape your data either using array.reshape(-1, 1) if your data has a single feature or array.reshape(1, -1) if it contains a single sample. Let’s try to follow the error message’s instructions: x.reshape(-1, 1) Reshaping is great if you passed a NumPy array, but we passed a pandas Series. So we get another error: AttributeError: 'Series' object has no attribute 'reshape' We could change our Series into a NumPy array and then reshape it to have two dimensions. However, as you saw above, there’s an easier way to make x a 2D object. Just pass the columns as a list using just the bracket syntax. I’ll make the result a capital X, because it will be a 2D array — and a capital letter is the statistical naming convention for a 2D array (also known as a matrix) . Let’s do it! X = df_hurricanes[['year']]X type(X)pandas.core.frame.DataFrameX.shape(3, 1) Now we can fit our model without errors! 😁 lr.fit(X, y)LogisticRegression() If our data were stored in a 1D NumPy array, then we could do what the error message suggests and turn it into a 2D array with reshape. Let's try that with the data we saved as a 1D NumPy array earlier. one_d_arrarray([2020, 1992, 1972])one_d_arr.shape(3,) Let’s reshape it! hard_coded_arr_shape = one_d_arr.reshape(3, 1)hard_coded_arr_shapearray([[2020], [1992], [1972]])hard_coded_arr_shape.shape(3, 1) Passing a positive integer means give that dimension that shape. So now our array has the shape 3, 1. However, it’s a better coding practice to use a flexible, dynamic option. So let’s use -1 with .reshape(). two_d_arr_from_reshape = one_d_arr.reshape(-1, 1)two_d_arr_from_reshapearray([[2020], [1992], [1972]])two_d_arr_from_reshape.shape(3, 1) Let’s unpack that code. We passed a 1 so the the second dimension — the columns — got a 1. We passed a negative integer for the other dimension. That means the remaining dimension becomes whatever shape is needed to make it hold all the original data. Think of -1 as fill in the blank to make a dimension so that all the data has a home. 🏠 In this case you end up with a 2D array with 3 rows and 1 column. -1 took on the value 3. It’s a good practice to make our code flexible so that it can handle how many ever observations we throw at it. So instead of hard-coding both dimensions, use -1. 🙂 The same principle can be used for reshaping higher dimensional arrays. Let’s make a three-dimensional array and then reshape it into a four-dimensional array. two_d_arrarray([['Zeta', 2020], ['Andrew', 1992], ['Agnes', 1972]], dtype=object)two_d_arr.shape(3, 2)three_d_arr = two_d_arr.reshape(2, 1, 3)three_d_arrarray([[['Zeta', 2020, 'Andrew']], [[1992, 'Agnes', 1972]]], dtype=object) Use -1, to indicate which dimension should be the one to be computed to give exactly all the data a home. arr = two_d_arr.reshape(1, 2, -1, 1)arrarray([[[['Zeta'], [2020], ['Andrew']], [[1992], ['Agnes'], [1972]]]], dtype=object) Note that if the reshape dimensions don’t make sense, you’ll get an error. Like this: two_d_arr.reshape(4, -1)two_d_arr--------------------------------------------------------------------ValueError: cannot reshape array of size 6 into shape (4,newaxis) We have six values, so we can only reshape the array into the number of dimensions that can hold exactly six values. In other words, the number of dimensions must form the product six. Remember that -1 is like a wildcard that can become any integer value. Scikit-learn expects a 2D array for most predictions. Say you have one single sample in a list that you want to use to make a prediction. You might naively think the following code will work. lr.predict(np.array([2012])) It doesn’t. ☹️ ValueError: Expected 2D array, got 1D array instead:array=[2012].Reshape your data either using array.reshape(-1, 1) if your data has a single feature or array.reshape(1, -1) if it contains a single sample. However, we can follow the helpful error suggestion to make a two-dimensional array with reshape(1, -1). lr.predict(np.array([2012]).reshape(1, -1))array(['Zeta'], dtype=object)np.array([2012]).reshape(1, -1).shape(1, 1) You’ve made the first dimension (the rows) 1 and the second dimension (the columns) match the number of features 1. Cool! Don’t be afraid to check the shape of an object — even just to confirm it is what you think it is. 🙂 While we’re on the topic of reshaping for scikit-learn, note that the text vectorization transformers such as CountVectorizer behave differently than other scikit-learn transformers. They assume you have just one column of text, so they expect a 1D array instead of a 2D array. You might need to reshape. ⚠️ In addition to reshaping with reshape, NumPy's flatten and ravel both return a 1D array. The differences are in whether they create a copy or a view of the original array and whether the data is stored contiguously in memory. Check out this nice Stack Overflow answer for more info. Let’s look at one other way to squeeze a 2D array into a 1D array. When you have a multi-dimensional array but one of the dimensions doesn’t hold any new information you can squeeze out the unnecessary dimension with .squeeze(). For example, let's use the array we made earlier. two_d_arr_from_reshapearray([[2020], [1992], [1972]])two_d_arr_from_reshape.shape(3, 1)squeezed = np.squeeze(two_d_arr_from_reshape)squeezed.shape(3,) Ta da! Note that the TensorFlow and PyTorch libraries play nicely with NumPy and can handle higher dimensional arrays representing things like video data. Getting the data into the shape the input layer to your neural network requires is a frequent source of errors. You can use the tools above to reshape your data into the required dimensions. 🚀 You’ve seen how to reshape NumPy arrays. Hopefully future code you see will make more sense and you’ll be able to quickly manipulate NumPy arrays into the shapes you need. If you found this article on reshaping NumPy arrays to be helpful, please share it on your favorite social media. 😀 I help people learn how to data things with Python, pandas, and other tools. If that sounds cool to you, check out my other guides and join my 15,000+ followers on Medium to get the latest content. Happy reshaping! 🔵🔷
[ { "code": null, "e": 405, "s": 172, "text": "Shape errors are the bane of many folks learning data science. I would bet money that people have quit their data science learning journey due to frustration with getting data into the shape required for machine learning algorithms." }, { "code": null, "e": 618, "s": 405, "text": "Having a stronger understanding of how to reshape your data will spare you tears, save you time, and help you grow as a data scientist. In this article, you’ll see how to get your data in the shape you need it. 🎉" }, { "code": null, "e": 772, "s": 618, "text": "First, let’s make sure we’re using similar package versions. Let’s import the libraries we’ll need under their usual aliases. All code is available here." }, { "code": null, "e": 932, "s": 772, "text": "import sysimport numpy as npimport pandas as pdimport sklearnfrom sklearn.preprocessing import OneHotEncoderfrom sklearn.linear_model import LogisticRegression" }, { "code": null, "e": 1095, "s": 932, "text": "If you don’t have the libraries you need installed, uncomment the following cell and run it. Then run the cell imports again. You may need to restart your kernel." }, { "code": null, "e": 1139, "s": 1095, "text": "# !pip install -U numpy pandas scikit-learn" }, { "code": null, "e": 1173, "s": 1139, "text": "Let’s check our package versions." }, { "code": null, "e": 1425, "s": 1173, "text": "print(f\"Python: {sys.version}\")print(f'NumPy: {np.__version__}')print(f'pandas: {pd.__version__}')print(f'scikit-learn: {sklearn.__version__}')Python: 3.8.5 (default, Sep 4 2020, 02:22:02) [Clang 10.0.0 ]NumPy: 1.19.2pandas: 1.2.0scikit-learn: 0.24.0" }, { "code": null, "e": 1490, "s": 1425, "text": "A pandas DataFrame has two dimensions: the rows and the columns." }, { "code": null, "e": 1544, "s": 1490, "text": "Let’s make a tiny DataFrame with some hurricane data." }, { "code": null, "e": 1660, "s": 1544, "text": "df_hurricanes = pd.DataFrame(dict( name=['Zeta', 'Andrew', 'Agnes'], year=[2020, 1992, 1972 ]))df_hurricanes" }, { "code": null, "e": 1750, "s": 1660, "text": "You can see the number of dimensions for a pandas data structure with the ndim attribute." }, { "code": null, "e": 1770, "s": 1750, "text": "df_hurricanes.ndim2" }, { "code": null, "e": 1835, "s": 1770, "text": "A DataFrame has both rows and columns, so it has two dimensions." }, { "code": null, "e": 2039, "s": 1835, "text": "The shape attribute shows the number of items in each dimension. Checking a DataFrame’s shape returns a tuple with two integers. The first is the number of rows and the second is the number of columns. 👍" }, { "code": null, "e": 2065, "s": 2039, "text": "df_hurricanes.shape(3, 2)" }, { "code": null, "e": 2109, "s": 2065, "text": "We have three rows and two columns. Cool. 😎" }, { "code": null, "e": 2161, "s": 2109, "text": "The size attribute shows us how many cells we have." }, { "code": null, "e": 2181, "s": 2161, "text": "df_hurricanes.size6" }, { "code": null, "e": 2191, "s": 2181, "text": "3 * 2 = 6" }, { "code": null, "e": 2322, "s": 2191, "text": "It’s easy to get the number of dimensions and size form the shape attribute so that’s the one to remember and the one we’ll use. 🚀" }, { "code": null, "e": 2487, "s": 2322, "text": "Let’s make a pandas Series from our DataFrame. Use just the brackets syntax to select a column by passing the name of the column as a string. You get back a Series." }, { "code": null, "e": 2630, "s": 2487, "text": "years_series = df_hurricanes['year']years_series0 20201 19922 1972Name: year, dtype: int64type(years_series)pandas.core.series.Series" }, { "code": null, "e": 2731, "s": 2630, "text": "What does the shape of a pandas Series look like? We can use the Series shape attribute to find out." }, { "code": null, "e": 2754, "s": 2731, "text": "years_series.shape(3,)" }, { "code": null, "e": 2865, "s": 2754, "text": "We have a tuple with just one value, the number of rows. Remember that the index doesn’t count as a column. ☝️" }, { "code": null, "e": 2978, "s": 2865, "text": "What happens if we use just the brackets again, except this time we pass a list containing a single column name?" }, { "code": null, "e": 3021, "s": 2978, "text": "years_df = df_hurricanes[['year']]years_df" }, { "code": null, "e": 3063, "s": 3021, "text": "type(years_df)pandas.core.frame.DataFrame" }, { "code": null, "e": 3184, "s": 3063, "text": "My variable name might have given away the answer. 😉 You always get back a DataFrame if you pass a list of column names." }, { "code": null, "e": 3205, "s": 3184, "text": "years_df.shape(3, 1)" }, { "code": null, "e": 3430, "s": 3205, "text": "Take away: the shape of a pandas Series and the shape of a pandas DataFrame with one column are different! A DataFrame has a shape of rows by columns and a Series has a shape of rows. This is a key point that trips folks up." }, { "code": null, "e": 3531, "s": 3430, "text": "Now that we know about finding the shape in pandas, let’s look at using NumPy. Pandas extends NumPy." }, { "code": null, "e": 3734, "s": 3531, "text": "NumPy’s ndarray is its core data structure — we’ll just refer to it as an array from here on. There are many ways to create NumPy arrays, depending upon your goals. Check out my guide on the topic here." }, { "code": null, "e": 3799, "s": 3734, "text": "Let’s make a NumPy array from our DataFrame and check its shape." }, { "code": null, "e": 3978, "s": 3799, "text": "two_d_arr = df_hurricanes.to_numpy()two_d_arrarray([['Zeta', 2020], ['Andrew', 1992], ['Agnes', 1972]], dtype=object)type(two_d_arr)numpy.ndarraytwo_d_arr.shape(3, 2)" }, { "code": null, "e": 4121, "s": 3978, "text": "The shape returned matches what we saw when we used pandas. Pandas and NumPy share some attributes and methods, including the shape attribute." }, { "code": null, "e": 4209, "s": 4121, "text": "Let’s convert the pandas Series we made earlier into a NumPy array and check its shape." }, { "code": null, "e": 4326, "s": 4209, "text": "one_d_arr = years_series.to_numpy()one_d_arrarray([2020, 1992, 1972])type(one_d_arr)numpy.ndarrayone_d_arr.shape(3,)" }, { "code": null, "e": 4383, "s": 4326, "text": "Again, we see the same result in pandas and NumPy. Cool!" }, { "code": null, "e": 4745, "s": 4383, "text": "Things get tricky when an object expects data to arrive in a certain shape. For example, most scikit-learn transformers and estimators expect to be fed their predictive X data in two-dimensional form. The target variable, y is expected to be one-dimensional. Let’s demonstrate how to reshape with a silly example where we use year to predict the hurricane name." }, { "code": null, "e": 4803, "s": 4745, "text": "We’ll make x lowercase because it has just one dimension." }, { "code": null, "e": 4924, "s": 4803, "text": "x = df_hurricanes['year']x0 20201 19922 1972Name: year, dtype: int64type(x)pandas.core.series.Seriesx.shape(3,)" }, { "code": null, "e": 4962, "s": 4924, "text": "Same goes for our output variable, y." }, { "code": null, "e": 5090, "s": 4962, "text": "y = df_hurricanes['name']y0 Zeta1 Andrew2 AgnesName: name, dtype: objecttype(y)pandas.core.series.Seriesy.shape(3,)" }, { "code": null, "e": 5144, "s": 5090, "text": "Let’s instantiate and fit a LogisticRegression model." }, { "code": null, "e": 5182, "s": 5144, "text": "lr = LogisticRegression()lr.fit(x, y)" }, { "code": null, "e": 5230, "s": 5182, "text": "And you get a value error. The last lines read:" }, { "code": null, "e": 5450, "s": 5230, "text": "ValueError: Expected 2D array, got 1D array instead:array=[2020. 1992. 1972.].Reshape your data either using array.reshape(-1, 1) if your data has a single feature or array.reshape(1, -1) if it contains a single sample." }, { "code": null, "e": 5504, "s": 5450, "text": "Let’s try to follow the error message’s instructions:" }, { "code": null, "e": 5521, "s": 5504, "text": "x.reshape(-1, 1)" }, { "code": null, "e": 5625, "s": 5521, "text": "Reshaping is great if you passed a NumPy array, but we passed a pandas Series. So we get another error:" }, { "code": null, "e": 5684, "s": 5625, "text": "AttributeError: 'Series' object has no attribute 'reshape'" }, { "code": null, "e": 5909, "s": 5684, "text": "We could change our Series into a NumPy array and then reshape it to have two dimensions. However, as you saw above, there’s an easier way to make x a 2D object. Just pass the columns as a list using just the bracket syntax." }, { "code": null, "e": 6075, "s": 5909, "text": "I’ll make the result a capital X, because it will be a 2D array — and a capital letter is the statistical naming convention for a 2D array (also known as a matrix) ." }, { "code": null, "e": 6088, "s": 6075, "text": "Let’s do it!" }, { "code": null, "e": 6117, "s": 6088, "text": "X = df_hurricanes[['year']]X" }, { "code": null, "e": 6165, "s": 6117, "text": "type(X)pandas.core.frame.DataFrameX.shape(3, 1)" }, { "code": null, "e": 6208, "s": 6165, "text": "Now we can fit our model without errors! 😁" }, { "code": null, "e": 6241, "s": 6208, "text": "lr.fit(X, y)LogisticRegression()" }, { "code": null, "e": 6444, "s": 6241, "text": "If our data were stored in a 1D NumPy array, then we could do what the error message suggests and turn it into a 2D array with reshape. Let's try that with the data we saved as a 1D NumPy array earlier." }, { "code": null, "e": 6498, "s": 6444, "text": "one_d_arrarray([2020, 1992, 1972])one_d_arr.shape(3,)" }, { "code": null, "e": 6516, "s": 6498, "text": "Let’s reshape it!" }, { "code": null, "e": 6658, "s": 6516, "text": "hard_coded_arr_shape = one_d_arr.reshape(3, 1)hard_coded_arr_shapearray([[2020], [1992], [1972]])hard_coded_arr_shape.shape(3, 1)" }, { "code": null, "e": 6760, "s": 6658, "text": "Passing a positive integer means give that dimension that shape. So now our array has the shape 3, 1." }, { "code": null, "e": 6867, "s": 6760, "text": "However, it’s a better coding practice to use a flexible, dynamic option. So let’s use -1 with .reshape()." }, { "code": null, "e": 7016, "s": 6867, "text": "two_d_arr_from_reshape = one_d_arr.reshape(-1, 1)two_d_arr_from_reshapearray([[2020], [1992], [1972]])two_d_arr_from_reshape.shape(3, 1)" }, { "code": null, "e": 7107, "s": 7016, "text": "Let’s unpack that code. We passed a 1 so the the second dimension — the columns — got a 1." }, { "code": null, "e": 7268, "s": 7107, "text": "We passed a negative integer for the other dimension. That means the remaining dimension becomes whatever shape is needed to make it hold all the original data." }, { "code": null, "e": 7356, "s": 7268, "text": "Think of -1 as fill in the blank to make a dimension so that all the data has a home. 🏠" }, { "code": null, "e": 7446, "s": 7356, "text": "In this case you end up with a 2D array with 3 rows and 1 column. -1 took on the value 3." }, { "code": null, "e": 7611, "s": 7446, "text": "It’s a good practice to make our code flexible so that it can handle how many ever observations we throw at it. So instead of hard-coding both dimensions, use -1. 🙂" }, { "code": null, "e": 7771, "s": 7611, "text": "The same principle can be used for reshaping higher dimensional arrays. Let’s make a three-dimensional array and then reshape it into a four-dimensional array." }, { "code": null, "e": 8017, "s": 7771, "text": "two_d_arrarray([['Zeta', 2020], ['Andrew', 1992], ['Agnes', 1972]], dtype=object)two_d_arr.shape(3, 2)three_d_arr = two_d_arr.reshape(2, 1, 3)three_d_arrarray([[['Zeta', 2020, 'Andrew']], [[1992, 'Agnes', 1972]]], dtype=object)" }, { "code": null, "e": 8123, "s": 8017, "text": "Use -1, to indicate which dimension should be the one to be computed to give exactly all the data a home." }, { "code": null, "e": 8286, "s": 8123, "text": "arr = two_d_arr.reshape(1, 2, -1, 1)arrarray([[[['Zeta'], [2020], ['Andrew']], [[1992], ['Agnes'], [1972]]]], dtype=object)" }, { "code": null, "e": 8372, "s": 8286, "text": "Note that if the reshape dimensions don’t make sense, you’ll get an error. Like this:" }, { "code": null, "e": 8539, "s": 8372, "text": "two_d_arr.reshape(4, -1)two_d_arr--------------------------------------------------------------------ValueError: cannot reshape array of size 6 into shape (4,newaxis)" }, { "code": null, "e": 8656, "s": 8539, "text": "We have six values, so we can only reshape the array into the number of dimensions that can hold exactly six values." }, { "code": null, "e": 8795, "s": 8656, "text": "In other words, the number of dimensions must form the product six. Remember that -1 is like a wildcard that can become any integer value." }, { "code": null, "e": 8849, "s": 8795, "text": "Scikit-learn expects a 2D array for most predictions." }, { "code": null, "e": 8987, "s": 8849, "text": "Say you have one single sample in a list that you want to use to make a prediction. You might naively think the following code will work." }, { "code": null, "e": 9016, "s": 8987, "text": "lr.predict(np.array([2012]))" }, { "code": null, "e": 9031, "s": 9016, "text": "It doesn’t. ☹️" }, { "code": null, "e": 9238, "s": 9031, "text": "ValueError: Expected 2D array, got 1D array instead:array=[2012].Reshape your data either using array.reshape(-1, 1) if your data has a single feature or array.reshape(1, -1) if it contains a single sample." }, { "code": null, "e": 9343, "s": 9238, "text": "However, we can follow the helpful error suggestion to make a two-dimensional array with reshape(1, -1)." }, { "code": null, "e": 9459, "s": 9343, "text": "lr.predict(np.array([2012]).reshape(1, -1))array(['Zeta'], dtype=object)np.array([2012]).reshape(1, -1).shape(1, 1)" }, { "code": null, "e": 9581, "s": 9459, "text": "You’ve made the first dimension (the rows) 1 and the second dimension (the columns) match the number of features 1. Cool!" }, { "code": null, "e": 9682, "s": 9581, "text": "Don’t be afraid to check the shape of an object — even just to confirm it is what you think it is. 🙂" }, { "code": null, "e": 9990, "s": 9682, "text": "While we’re on the topic of reshaping for scikit-learn, note that the text vectorization transformers such as CountVectorizer behave differently than other scikit-learn transformers. They assume you have just one column of text, so they expect a 1D array instead of a 2D array. You might need to reshape. ⚠️" }, { "code": null, "e": 10273, "s": 9990, "text": "In addition to reshaping with reshape, NumPy's flatten and ravel both return a 1D array. The differences are in whether they create a copy or a view of the original array and whether the data is stored contiguously in memory. Check out this nice Stack Overflow answer for more info." }, { "code": null, "e": 10340, "s": 10273, "text": "Let’s look at one other way to squeeze a 2D array into a 1D array." }, { "code": null, "e": 10552, "s": 10340, "text": "When you have a multi-dimensional array but one of the dimensions doesn’t hold any new information you can squeeze out the unnecessary dimension with .squeeze(). For example, let's use the array we made earlier." }, { "code": null, "e": 10715, "s": 10552, "text": "two_d_arr_from_reshapearray([[2020], [1992], [1972]])two_d_arr_from_reshape.shape(3, 1)squeezed = np.squeeze(two_d_arr_from_reshape)squeezed.shape(3,)" }, { "code": null, "e": 10722, "s": 10715, "text": "Ta da!" }, { "code": null, "e": 11063, "s": 10722, "text": "Note that the TensorFlow and PyTorch libraries play nicely with NumPy and can handle higher dimensional arrays representing things like video data. Getting the data into the shape the input layer to your neural network requires is a frequent source of errors. You can use the tools above to reshape your data into the required dimensions. 🚀" }, { "code": null, "e": 11235, "s": 11063, "text": "You’ve seen how to reshape NumPy arrays. Hopefully future code you see will make more sense and you’ll be able to quickly manipulate NumPy arrays into the shapes you need." }, { "code": null, "e": 11351, "s": 11235, "text": "If you found this article on reshaping NumPy arrays to be helpful, please share it on your favorite social media. 😀" }, { "code": null, "e": 11549, "s": 11351, "text": "I help people learn how to data things with Python, pandas, and other tools. If that sounds cool to you, check out my other guides and join my 15,000+ followers on Medium to get the latest content." } ]
How to toggle a div visibility using jQuery?
To toggle a div visibility in jQuery, use the toggle() method. It checks the div element for visibility i.e. the show() method if div is hidden. And hide() id the div element is visible. This eventually creates a toggle effect. The toggle( speed, [callback]) method toggles displaying each of the set of matched elements using a graceful animation and firing an optional callback after completion. Here is the description of all the parameters used by this method − speed − A string representing one of the three predefined speeds ("slow", "normal", or "fast") or the number of milliseconds to run the animation (e.g. 1000). callback − This is optional parameter representing a function to call once the animation is complete. You can try to run the following code to toggle div visibility using jQuery − Live Demo <html> <head> <title>jQuery toggle() method</title> <script src = "https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script> <script> $(document).ready(function() { $("#toggle").click(function(){ $(".target").toggle( 'slow', function(){ $(".log").text('Toggle Transition Complete'); }); }); }); </script> <style> p { background-color:#bca; width:200px; border:1px solid green; } </style> </head> <body> <p>Click on the following button:</p> <button id = "toggle"> Toggle </button> <div class = "target"> <img src = "../images/jquery.jpg" alt = "jQuery" /> </div> <div class = "log"></div> </body> </html>
[ { "code": null, "e": 1290, "s": 1062, "text": "To toggle a div visibility in jQuery, use the toggle() method. It checks the div element for visibility i.e. the show() method if div is hidden. And hide() id the div element is visible. This eventually creates a toggle effect." }, { "code": null, "e": 1460, "s": 1290, "text": "The toggle( speed, [callback]) method toggles displaying each of the set of matched elements using a graceful animation and firing an optional callback after completion." }, { "code": null, "e": 1528, "s": 1460, "text": "Here is the description of all the parameters used by this method −" }, { "code": null, "e": 1687, "s": 1528, "text": "speed − A string representing one of the three predefined speeds (\"slow\", \"normal\", or \"fast\") or the number of milliseconds to run the animation (e.g. 1000)." }, { "code": null, "e": 1789, "s": 1687, "text": "callback − This is optional parameter representing a function to call once the animation is complete." }, { "code": null, "e": 1867, "s": 1789, "text": "You can try to run the following code to toggle div visibility using jQuery −" }, { "code": null, "e": 1877, "s": 1867, "text": "Live Demo" }, { "code": null, "e": 2784, "s": 1877, "text": "<html>\n\n <head>\n <title>jQuery toggle() method</title>\n <script src = \"https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js\"></script>\n \n <script>\n \n $(document).ready(function() {\n\n $(\"#toggle\").click(function(){\n $(\".target\").toggle( 'slow', function(){\n $(\".log\").text('Toggle Transition Complete');\n });\n });\n });\n \n </script>\n \n <style>\n p {\n background-color:#bca;\n width:200px;\n border:1px solid green;\n }\n </style>\n </head>\n \n <body>\n\n <p>Click on the following button:</p>\n <button id = \"toggle\"> Toggle </button>\n\n <div class = \"target\">\n <img src = \"../images/jquery.jpg\" alt = \"jQuery\" />\n </div>\n \n <div class = \"log\"></div>\n \n </body>\n</html>" } ]
Simple Arithmetic Operators Example Program In C++
C++ has 5 basic arithmetic operators. They are − Addition(+) Subtraction(-) Division(/) Multiplication(*) Modulo(%) These operators can operate on any arithmetic operations in C++. Let's have a look at an example − #include <iostream> using namespace std; main() { int a = 21; int b = 10; int c ; c = a + b; cout << "Line 1 - Value of c is :" << c << endl ; c = a - b; cout << "Line 2 - Value of c is :" << c << endl ; c = a * b; cout << "Line 3 - Value of c is :" << c << endl ; c = a / b; cout << "Line 4 - Value of c is :" << c << endl ; c = a % b; cout << "Line 5 - Value of c is :" << c << endl ; return 0; } This will give the output − Line 1 - Value of c is :31 Line 2 - Value of c is :11 Line 3 - Value of c is :210 Line 4 - Value of c is :2 Line 5 - Value of c is :1
[ { "code": null, "e": 1111, "s": 1062, "text": "C++ has 5 basic arithmetic operators. They are −" }, { "code": null, "e": 1123, "s": 1111, "text": "Addition(+)" }, { "code": null, "e": 1138, "s": 1123, "text": "Subtraction(-)" }, { "code": null, "e": 1150, "s": 1138, "text": "Division(/)" }, { "code": null, "e": 1168, "s": 1150, "text": "Multiplication(*)" }, { "code": null, "e": 1178, "s": 1168, "text": "Modulo(%)" }, { "code": null, "e": 1277, "s": 1178, "text": "These operators can operate on any arithmetic operations in C++. Let's have a look at an example −" }, { "code": null, "e": 1737, "s": 1277, "text": "#include <iostream>\nusing namespace std;\nmain() {\n int a = 21;\n int b = 10;\n int c ;\n c = a + b;\n cout << \"Line 1 - Value of c is :\" << c << endl ;\n \n c = a - b;\n cout << \"Line 2 - Value of c is :\" << c << endl ;\n \n c = a * b;\n cout << \"Line 3 - Value of c is :\" << c << endl ;\n \n c = a / b;\n cout << \"Line 4 - Value of c is :\" << c << endl ;\n \n c = a % b;\n cout << \"Line 5 - Value of c is :\" << c << endl ;\n return 0;\n}" }, { "code": null, "e": 1765, "s": 1737, "text": "This will give the output −" }, { "code": null, "e": 1902, "s": 1765, "text": "Line 1 - Value of c is :31\nLine 2 - Value of c is :11\nLine 3 - Value of c is :210\nLine 4 - Value of c is :2\nLine 5 - Value of c is :1" } ]
Menu Driven C++ Program for a Simple Calculator - GeeksforGeeks
16 Jul, 2019 Problem Statement:Write a menu-driven program using the Switch case to calculate the following: Addition of two numbersDifference between two numbersProduct of two numbersDivision of two numbersHCF of two numbersLCM of two numbers Addition of two numbers Difference between two numbers Product of two numbers Division of two numbers HCF of two numbers LCM of two numbers Examples: Input: num1 = 5, num2 = 7, choice = 1 Output: Sum is 12 Input: num1 = 5, num2 = 7, choice = 5 Output: GCD is 1 Implementation: // C++ program to illustrate// Menu-Driven program using Switch-case #include <bits/stdc++.h>using namespace std; // Function to display the menuvoid menu(){ cout << "Press 1 to calculate Sum of Numbers\n"; cout << "Press 2 to calculate Difference of Numbers\n"; cout << "Press 3 to calculate Product of numbers\n"; cout << "Press 4 to calculate Division of numbers\n"; cout << "Press 5 to calculate HCF of numbers\n"; cout << "Press 6 to calculate LCM of numbers\n"; cout << "Press 7 to exit\n";} // Function to calculate and display the resultvoid result(int choice, int a, int b){ // Display the result switch (choice) { case 1: { cout << "Sum is " << (a + b) << "\n"; break; } case 2: { cout << "Difference is " << (a - b) << "\n"; break; } case 3: { cout << "Product is " << (a * b) << "\n"; break; } case 4: { cout << "Division is " << (a / b) << "\n"; break; } case 5: { cout << "GCD is " << __gcd(a, b) << "\n"; break; } case 6: { cout << "LCM is " << ((a * b) / __gcd(a, b)) << "\n"; break; } case 7: { cout << "Thank you\n"; break; } default: printf("Wrong Input\n"); }} int main(){ // Get the two numbers int a = 5, b = 7; int choice, res; // Display the menu menu(); // Enter the choice cout << "Enter your choice:\n"; choice = 1; cout << "Choice is " << choice << endl; // Display the result // according to the choice result(choice, a, b); return 0;} Press 1 to calculate Sum of Numbers Press 2 to calculate Difference of Numbers Press 3 to calculate Product of numbers Press 4 to calculate Division of numbers Press 5 to calculate HCF of numbers Press 6 to calculate LCM of numbers Press 7 to exit Enter your choice: Choice is 1 Sum is 12 Time Complexity: O(n). Menu driven programs C++ Programs Mathematical School Programming Mathematical Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments CSV file management using C++ C++ Program for QuickSort cin in C++ Generics in C++ delete keyword in C++ Program for Fibonacci numbers Write a program to print all permutations of a given string C++ Data Types Set in C++ Standard Template Library (STL) Coin Change | DP-7
[ { "code": null, "e": 24514, "s": 24486, "text": "\n16 Jul, 2019" }, { "code": null, "e": 24610, "s": 24514, "text": "Problem Statement:Write a menu-driven program using the Switch case to calculate the following:" }, { "code": null, "e": 24745, "s": 24610, "text": "Addition of two numbersDifference between two numbersProduct of two numbersDivision of two numbersHCF of two numbersLCM of two numbers" }, { "code": null, "e": 24769, "s": 24745, "text": "Addition of two numbers" }, { "code": null, "e": 24800, "s": 24769, "text": "Difference between two numbers" }, { "code": null, "e": 24823, "s": 24800, "text": "Product of two numbers" }, { "code": null, "e": 24847, "s": 24823, "text": "Division of two numbers" }, { "code": null, "e": 24866, "s": 24847, "text": "HCF of two numbers" }, { "code": null, "e": 24885, "s": 24866, "text": "LCM of two numbers" }, { "code": null, "e": 24895, "s": 24885, "text": "Examples:" }, { "code": null, "e": 25008, "s": 24895, "text": "Input: num1 = 5, num2 = 7, choice = 1\nOutput: Sum is 12\n\nInput: num1 = 5, num2 = 7, choice = 5\nOutput: GCD is 1\n" }, { "code": null, "e": 25024, "s": 25008, "text": "Implementation:" }, { "code": "// C++ program to illustrate// Menu-Driven program using Switch-case #include <bits/stdc++.h>using namespace std; // Function to display the menuvoid menu(){ cout << \"Press 1 to calculate Sum of Numbers\\n\"; cout << \"Press 2 to calculate Difference of Numbers\\n\"; cout << \"Press 3 to calculate Product of numbers\\n\"; cout << \"Press 4 to calculate Division of numbers\\n\"; cout << \"Press 5 to calculate HCF of numbers\\n\"; cout << \"Press 6 to calculate LCM of numbers\\n\"; cout << \"Press 7 to exit\\n\";} // Function to calculate and display the resultvoid result(int choice, int a, int b){ // Display the result switch (choice) { case 1: { cout << \"Sum is \" << (a + b) << \"\\n\"; break; } case 2: { cout << \"Difference is \" << (a - b) << \"\\n\"; break; } case 3: { cout << \"Product is \" << (a * b) << \"\\n\"; break; } case 4: { cout << \"Division is \" << (a / b) << \"\\n\"; break; } case 5: { cout << \"GCD is \" << __gcd(a, b) << \"\\n\"; break; } case 6: { cout << \"LCM is \" << ((a * b) / __gcd(a, b)) << \"\\n\"; break; } case 7: { cout << \"Thank you\\n\"; break; } default: printf(\"Wrong Input\\n\"); }} int main(){ // Get the two numbers int a = 5, b = 7; int choice, res; // Display the menu menu(); // Enter the choice cout << \"Enter your choice:\\n\"; choice = 1; cout << \"Choice is \" << choice << endl; // Display the result // according to the choice result(choice, a, b); return 0;}", "e": 26650, "s": 25024, "text": null }, { "code": null, "e": 26940, "s": 26650, "text": "Press 1 to calculate Sum of Numbers\nPress 2 to calculate Difference of Numbers\nPress 3 to calculate Product of numbers\nPress 4 to calculate Division of numbers\nPress 5 to calculate HCF of numbers\nPress 6 to calculate LCM of numbers\nPress 7 to exit\nEnter your choice:\nChoice is 1\nSum is 12\n" }, { "code": null, "e": 26963, "s": 26940, "text": "Time Complexity: O(n)." }, { "code": null, "e": 26984, "s": 26963, "text": "Menu driven programs" }, { "code": null, "e": 26997, "s": 26984, "text": "C++ Programs" }, { "code": null, "e": 27010, "s": 26997, "text": "Mathematical" }, { "code": null, "e": 27029, "s": 27010, "text": "School Programming" }, { "code": null, "e": 27042, "s": 27029, "text": "Mathematical" }, { "code": null, "e": 27140, "s": 27042, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27149, "s": 27140, "text": "Comments" }, { "code": null, "e": 27162, "s": 27149, "text": "Old Comments" }, { "code": null, "e": 27192, "s": 27162, "text": "CSV file management using C++" }, { "code": null, "e": 27218, "s": 27192, "text": "C++ Program for QuickSort" }, { "code": null, "e": 27229, "s": 27218, "text": "cin in C++" }, { "code": null, "e": 27245, "s": 27229, "text": "Generics in C++" }, { "code": null, "e": 27267, "s": 27245, "text": "delete keyword in C++" }, { "code": null, "e": 27297, "s": 27267, "text": "Program for Fibonacci numbers" }, { "code": null, "e": 27357, "s": 27297, "text": "Write a program to print all permutations of a given string" }, { "code": null, "e": 27372, "s": 27357, "text": "C++ Data Types" }, { "code": null, "e": 27415, "s": 27372, "text": "Set in C++ Standard Template Library (STL)" } ]
Convert a Binary String to another by flipping prefixes minimum number of times - GeeksforGeeks
17 Jan, 2022 Given two binary strings A and B of length N, the task is to convert the string A to B by repeatedly flipping a prefix of A, i.e. reverse the order of occurrence of bits in the chosen prefix. Print the number of flips required and the length of all prefixes. Examples: Input: A = “01”, B = “10”Output:31 2 1Explanation:Operation 1: Select the prefix of length 1 from the string A (= “01”). Flipping the prefix “0” modifies the string to “11”.Operation 2: Select the prefix of length 2 from the string A (= “11”). Flipping the prefix “11” modifies the string to “00”.Operation 3: Select the prefix of length 1 from the string A (= “00”). Flipping the prefix “0” to “1” modifies the string to “10”, which is the same as the string B.Therefore, the total number of operations required is 3. Input: A = “0”, B = “1”Output:11 Approach: The given problem can be solved by fixing the bits one-by-one. To fix the ith bit, when A[i] and B[i] are unequal, flip the prefix of length i followed by flipping the prefix of length 1. Now, flip the prefix of length i. These three operations do not change any other bits in A. Perform these operations at all indices where A[i] is unequal B[i]. Since 3 operations are used per bit, overall 3 * N operations will be used. In order to minimize the number of operations, the above approach can be modified by fixing the bits one by one in reverse order. To fix the ith bit, either the prefix of length i is required to be flipped or the first bit, and then the prefix of length i is required to be flipped. But in reverse order, the previously fixed bits do not get flipped again by this procedure and at most 2 operations are needed per bit. Therefore, the minimum number of operations required is 2*N. Below is the implementation of the above approach: C++14 Java Python3 C# Javascript // C++ program for the above approach #include <bits/stdc++.h> using namespace std; // Function to count minimum number // of operations required to convert // string a to another string b void minOperations(string a, string b, int n) { // Store the lengths of each // prefixes selected vector<int> ops; // Traverse the string for (int i = n - 1; i >= 0; i--) { if (a[i] != b[i]) { // If first character // is same as b[i] if (a[0] == b[i]) { // Insert 1 to ops[] ops.push_back(1); // And, flip the bit a[0] = '0' + !(a[0] - '0'); } // Reverse the prefix // string of length i + 1 reverse(a.begin(), a.begin() + i + 1); // Flip the characters // in this prefix length for (int j = 0; j <= i; j++) { a[j] = '0' + !(a[j] - '0'); } // Push (i + 1) to array ops[] ops.push_back(i + 1); } } // Print the number of operations cout << ops.size() << "\n"; // Print the length of // each prefixes stored for (int x : ops) { cout << x << ' '; } } // Driver Code int main() { string a = "10", b = "01"; int N = a.size(); minOperations(a, b, N); return 0; } // Java program for the above approach import java.io.*; import java.lang.*; import java.util.*; class GFG { // Function to count minimum number // of operations required to convert // string a to another string b static void minOperations(String s1, String s2, int n) { char a[] = s1.toCharArray(); char b[] = s2.toCharArray(); // Store the lengths of each // prefixes selected ArrayList<Integer> ops = new ArrayList<>(); // Traverse the string for (int i = n - 1; i >= 0; i--) { if (a[i] != b[i]) { // If first character // is same as b[i] if (a[0] == b[i]) { // Insert 1 to ops[] ops.add(1); // And, flip the bit a[0] = (a[0] == '0' ? '1' : '0'); } // Reverse the prefix // string of length i + 1 reverse(a, 0, i); // Flip the characters // in this prefix length for (int j = 0; j <= i; j++) { a[j] = (a[j] == '0' ? '1' : '0'); } // Push (i + 1) to array ops[] ops.add(i + 1); } } // Print the number of operations System.out.println(ops.size()); // Print the length of // each prefixes stored for (int x : ops) { System.out.print(x + " "); } } // Function to reverse a[] // from start to end static void reverse(char a[], int start, int end) { while (start < end) { char temp = a[start]; a[start] = a[end]; a[end] = temp; start++; end--; } } // Driver code public static void main(String[] args) { String a = "10", b = "01"; int N = a.length(); minOperations(a, b, N); } } // This code is contributed by Kingash. # Python 3 program for the above approach # Function to count minimum number # of operations required to convert # string a to another string b def minOperations(a, b, n): # Store the lengths of each # prefixes selected ops = [] a = list(a) # Traverse the string for i in range(n - 1, -1, -1): if (a[i] != b[i]): # If first character # is same as b[i] if (a[0] == b[i]): # Insert 1 to ops[] ops.append(1) # And, flip the bit if(ord(a[0]) - ord('0')): a[0] = chr(ord('0') + ord('0')) else: a[0] = chr(ord('0') + ord('1')) # Reverse the prefix # string of length i + 1 a[:i+1].reverse() # Flip the characters # in this prefix length for j in range(i+1): if(ord(a[j]) - ord('0')): a[j] = chr(ord('0') + ord('0')) else: a[j] = chr(ord('0') + ord('1')) # Push (i + 1) to array ops[] ops.append(i + 1) # Print the number of operations print(len(ops)) # Print the length of # each prefixes stored for x in ops: print(x, end=" ") # Driver Code if __name__ == "__main__": a = "10" b = "01" N = len(a) minOperations(a, b, N) # This code is contributed by ukasp. // C# program to implement // the above approach using System; using System.Collections.Generic; class GFG { // Function to count minimum number // of operations required to convert // string a to another string b static void minOperations(string s1, string s2, int n) { char[] a = s1.ToCharArray(); char[] b = s2.ToCharArray(); // Store the lengths of each // prefixes selected List<int> ops = new List<int>(); // Traverse the string for (int i = n - 1; i >= 0; i--) { if (a[i] != b[i]) { // If first character // is same as b[i] if (a[0] == b[i]) { // Insert 1 to ops[] ops.Add(1); // And, flip the bit a[0] = (a[0] == '0' ? '1' : '0'); } // Reverse the prefix // string of length i + 1 reverse(a, 0, i); // Flip the characters // in this prefix length for (int j = 0; j <= i; j++) { a[j] = (a[j] == '0' ? '1' : '0'); } // Push (i + 1) to array ops[] ops.Add(i + 1); } } // Print the number of operations Console.WriteLine(ops.Count); // Print the length of // each prefixes stored foreach (int x in ops) { Console.Write(x + " "); } } // Function to reverse a[] // from start to end static void reverse(char[] a, int start, int end) { while (start < end) { char temp = a[start]; a[start] = a[end]; a[end] = temp; start++; end--; } } // Driver Code public static void Main() { string a = "10", b = "01"; int N = a.Length; minOperations(a, b, N); } } // This code is contributed by souravghosh0416. <script> // JavaScript program to implement // the above approach // Function to count minimum number // of operations required to convert // string a to another string b function minOperations(s1, s2, n) { var a = s1.split(""); var b = s2.split(""); // Store the lengths of each // prefixes selected var ops = []; // Traverse the string for (var i = n - 1; i >= 0; i--) { if (a[i] !== b[i]) { // If first character // is same as b[i] if (a[0] === b[i]) { // Insert 1 to ops[] ops.push(1); // And, flip the bit a[0] = a[0] === "0" ? "1" : "0"; } // Reverse the prefix // string of length i + 1 reverse(a, 0, i); // Flip the characters // in this prefix length for (var j = 0; j <= i; j++) { a[j] = a[j] === "0" ? "1" : "0"; } // Push (i + 1) to array ops[] ops.push(i + 1); } } // Print the number of operations document.write(ops.length + "<br>"); // Print the length of // each prefixes stored for (const x of ops) { document.write(x + " "); } } // Function to reverse a[] // from start to end function reverse(a, start, end) { while (start < end) { var temp = a[start]; a[start] = a[end]; a[end] = temp; start++; end--; } } // Driver Code var a = "10", b = "01"; var N = a.length; minOperations(a, b, N); </script> 3 1 2 1 Time Complexity: O(N2)Auxiliary Space: O(N) Kingash souravghosh0416 rdtank ukasp binary-string Technical Scripter 2020 Pattern Searching Strings Technical Scripter Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Check whether two strings contain same characters in same order Count of total Heads and Tails after N flips in a coin How to check Aadhaar number is valid or not using Regular Expression How to validate GUID (Globally Unique Identifier) using Regular Expression How to validate time in 24-hour format using Regular Expression Reverse a string in Java Write a program to reverse an array or string Longest Common Subsequence | DP-4 Write a program to print all permutations of a given string C++ Data Types
[ { "code": null, "e": 25091, "s": 25060, "text": " \n17 Jan, 2022\n" }, { "code": null, "e": 25350, "s": 25091, "text": "Given two binary strings A and B of length N, the task is to convert the string A to B by repeatedly flipping a prefix of A, i.e. reverse the order of occurrence of bits in the chosen prefix. Print the number of flips required and the length of all prefixes." }, { "code": null, "e": 25360, "s": 25350, "text": "Examples:" }, { "code": null, "e": 25879, "s": 25360, "text": "Input: A = “01”, B = “10”Output:31 2 1Explanation:Operation 1: Select the prefix of length 1 from the string A (= “01”). Flipping the prefix “0” modifies the string to “11”.Operation 2: Select the prefix of length 2 from the string A (= “11”). Flipping the prefix “11” modifies the string to “00”.Operation 3: Select the prefix of length 1 from the string A (= “00”). Flipping the prefix “0” to “1” modifies the string to “10”, which is the same as the string B.Therefore, the total number of operations required is 3." }, { "code": null, "e": 25912, "s": 25879, "text": "Input: A = “0”, B = “1”Output:11" }, { "code": null, "e": 26347, "s": 25912, "text": "Approach: The given problem can be solved by fixing the bits one-by-one. To fix the ith bit, when A[i] and B[i] are unequal, flip the prefix of length i followed by flipping the prefix of length 1. Now, flip the prefix of length i. These three operations do not change any other bits in A. Perform these operations at all indices where A[i] is unequal B[i]. Since 3 operations are used per bit, overall 3 * N operations will be used. " }, { "code": null, "e": 26827, "s": 26347, "text": "In order to minimize the number of operations, the above approach can be modified by fixing the bits one by one in reverse order. To fix the ith bit, either the prefix of length i is required to be flipped or the first bit, and then the prefix of length i is required to be flipped. But in reverse order, the previously fixed bits do not get flipped again by this procedure and at most 2 operations are needed per bit. Therefore, the minimum number of operations required is 2*N." }, { "code": null, "e": 26878, "s": 26827, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 26884, "s": 26878, "text": "C++14" }, { "code": null, "e": 26889, "s": 26884, "text": "Java" }, { "code": null, "e": 26897, "s": 26889, "text": "Python3" }, { "code": null, "e": 26900, "s": 26897, "text": "C#" }, { "code": null, "e": 26911, "s": 26900, "text": "Javascript" }, { "code": "\n\n\n\n\n\n\n// C++ program for the above approach\n#include <bits/stdc++.h>\nusing namespace std;\n \n// Function to count minimum number\n// of operations required to convert\n// string a to another string b\nvoid minOperations(string a, string b, int n)\n{\n // Store the lengths of each\n // prefixes selected\n vector<int> ops;\n \n // Traverse the string\n for (int i = n - 1; i >= 0; i--) {\n if (a[i] != b[i]) {\n \n // If first character\n // is same as b[i]\n if (a[0] == b[i]) {\n \n // Insert 1 to ops[]\n ops.push_back(1);\n \n // And, flip the bit\n a[0] = '0' + !(a[0] - '0');\n }\n \n // Reverse the prefix\n // string of length i + 1\n reverse(a.begin(), a.begin() + i + 1);\n \n // Flip the characters\n // in this prefix length\n for (int j = 0; j <= i; j++) {\n a[j] = '0' + !(a[j] - '0');\n }\n \n // Push (i + 1) to array ops[]\n ops.push_back(i + 1);\n }\n }\n \n // Print the number of operations\n cout << ops.size() << \"\\n\";\n \n // Print the length of\n // each prefixes stored\n for (int x : ops) {\n cout << x << ' ';\n }\n}\n \n// Driver Code\nint main()\n{\n string a = \"10\", b = \"01\";\n int N = a.size();\n \n minOperations(a, b, N);\n \n return 0;\n}\n\n\n\n\n\n", "e": 28330, "s": 26921, "text": null }, { "code": "\n\n\n\n\n\n\n// Java program for the above approach\nimport java.io.*;\nimport java.lang.*;\nimport java.util.*;\nclass GFG \n{\n \n // Function to count minimum number\n // of operations required to convert\n // string a to another string b\n static void minOperations(String s1, String s2, int n)\n {\n \n char a[] = s1.toCharArray();\n char b[] = s2.toCharArray();\n \n // Store the lengths of each\n // prefixes selected\n ArrayList<Integer> ops = new ArrayList<>();\n \n // Traverse the string\n for (int i = n - 1; i >= 0; i--) {\n if (a[i] != b[i]) {\n \n // If first character\n // is same as b[i]\n if (a[0] == b[i]) {\n \n // Insert 1 to ops[]\n ops.add(1);\n \n // And, flip the bit\n a[0] = (a[0] == '0' ? '1' : '0');\n }\n \n // Reverse the prefix\n // string of length i + 1\n reverse(a, 0, i);\n \n // Flip the characters\n // in this prefix length\n for (int j = 0; j <= i; j++) {\n a[j] = (a[j] == '0' ? '1' : '0');\n }\n \n // Push (i + 1) to array ops[]\n ops.add(i + 1);\n }\n }\n \n // Print the number of operations\n System.out.println(ops.size());\n \n // Print the length of\n // each prefixes stored\n for (int x : ops) {\n System.out.print(x + \" \");\n }\n }\n \n // Function to reverse a[]\n // from start to end\n static void reverse(char a[], int start, int end)\n {\n \n while (start < end) {\n char temp = a[start];\n a[start] = a[end];\n a[end] = temp;\n start++;\n end--;\n }\n }\n \n // Driver code\n public static void main(String[] args)\n {\n \n String a = \"10\", b = \"01\";\n int N = a.length();\n \n minOperations(a, b, N);\n }\n}\n \n// This code is contributed by Kingash.\n\n\n\n\n\n", "e": 30115, "s": 28340, "text": null }, { "code": "\n\n\n\n\n\n\n# Python 3 program for the above approach\n \n# Function to count minimum number\n# of operations required to convert\n# string a to another string b\ndef minOperations(a, b, n):\n \n # Store the lengths of each\n # prefixes selected\n ops = []\n a = list(a)\n \n # Traverse the string\n for i in range(n - 1, -1, -1):\n if (a[i] != b[i]):\n \n # If first character\n # is same as b[i]\n if (a[0] == b[i]):\n \n # Insert 1 to ops[]\n ops.append(1)\n \n # And, flip the bit\n if(ord(a[0]) - ord('0')):\n a[0] = chr(ord('0') + ord('0'))\n else:\n a[0] = chr(ord('0') + ord('1'))\n \n # Reverse the prefix\n # string of length i + 1\n \n a[:i+1].reverse()\n \n # Flip the characters\n # in this prefix length\n for j in range(i+1):\n if(ord(a[j]) - ord('0')):\n a[j] = chr(ord('0') + ord('0'))\n else:\n a[j] = chr(ord('0') + ord('1'))\n \n # Push (i + 1) to array ops[]\n ops.append(i + 1)\n \n # Print the number of operations\n print(len(ops))\n \n # Print the length of\n # each prefixes stored\n for x in ops:\n print(x, end=\" \")\n \n# Driver Code\nif __name__ == \"__main__\":\n \n a = \"10\"\n b = \"01\"\n N = len(a)\n \n minOperations(a, b, N)\n \n # This code is contributed by ukasp.\n\n\n\n\n\n", "e": 31629, "s": 30125, "text": null }, { "code": "\n\n\n\n\n\n\n// C# program to implement\n// the above approach\nusing System;\nusing System.Collections.Generic; \n \nclass GFG\n{\n \n // Function to count minimum number\n // of operations required to convert\n // string a to another string b\n static void minOperations(string s1, string s2, int n)\n {\n \n char[] a = s1.ToCharArray();\n char[] b = s2.ToCharArray();\n \n // Store the lengths of each\n // prefixes selected\n List<int> ops = new List<int>();\n \n // Traverse the string\n for (int i = n - 1; i >= 0; i--) {\n if (a[i] != b[i]) {\n \n // If first character\n // is same as b[i]\n if (a[0] == b[i]) {\n \n // Insert 1 to ops[]\n ops.Add(1);\n \n // And, flip the bit\n a[0] = (a[0] == '0' ? '1' : '0');\n }\n \n // Reverse the prefix\n // string of length i + 1\n reverse(a, 0, i);\n \n // Flip the characters\n // in this prefix length\n for (int j = 0; j <= i; j++) {\n a[j] = (a[j] == '0' ? '1' : '0');\n }\n \n // Push (i + 1) to array ops[]\n ops.Add(i + 1);\n }\n }\n \n // Print the number of operations\n Console.WriteLine(ops.Count);\n \n // Print the length of\n // each prefixes stored\n foreach (int x in ops) {\n Console.Write(x + \" \");\n }\n }\n \n // Function to reverse a[]\n // from start to end\n static void reverse(char[] a, int start, int end)\n {\n \n while (start < end) {\n char temp = a[start];\n a[start] = a[end];\n a[end] = temp;\n start++;\n end--;\n }\n }\n \n // Driver Code\n public static void Main()\n {\n string a = \"10\", b = \"01\";\n int N = a.Length;\n \n minOperations(a, b, N);\n }\n}\n \n// This code is contributed by souravghosh0416.\n\n\n\n\n\n", "e": 33396, "s": 31639, "text": null }, { "code": "\n\n\n\n\n\n\n<script>\n // JavaScript program to implement\n // the above approach\n // Function to count minimum number\n // of operations required to convert\n // string a to another string b\n function minOperations(s1, s2, n) {\n var a = s1.split(\"\");\n var b = s2.split(\"\");\n \n // Store the lengths of each\n // prefixes selected\n var ops = [];\n \n // Traverse the string\n for (var i = n - 1; i >= 0; i--) {\n if (a[i] !== b[i]) {\n // If first character\n // is same as b[i]\n if (a[0] === b[i]) {\n // Insert 1 to ops[]\n ops.push(1);\n \n // And, flip the bit\n a[0] = a[0] === \"0\" ? \"1\" : \"0\";\n }\n \n // Reverse the prefix\n // string of length i + 1\n reverse(a, 0, i);\n \n // Flip the characters\n // in this prefix length\n for (var j = 0; j <= i; j++) {\n a[j] = a[j] === \"0\" ? \"1\" : \"0\";\n }\n \n // Push (i + 1) to array ops[]\n ops.push(i + 1);\n }\n }\n \n // Print the number of operations\n document.write(ops.length + \"<br>\");\n \n // Print the length of\n // each prefixes stored\n for (const x of ops) {\n document.write(x + \" \");\n }\n }\n \n // Function to reverse a[]\n // from start to end\n function reverse(a, start, end) {\n while (start < end) {\n var temp = a[start];\n a[start] = a[end];\n a[end] = temp;\n start++;\n end--;\n }\n }\n \n // Driver Code\n var a = \"10\", b = \"01\";\n var N = a.length;\n \n minOperations(a, b, N);\n</script>\n\n\n\n\n\n", "e": 35183, "s": 33406, "text": null }, { "code": null, "e": 35191, "s": 35183, "text": "3\n1 2 1" }, { "code": null, "e": 35238, "s": 35193, "text": "Time Complexity: O(N2)Auxiliary Space: O(N) " }, { "code": null, "e": 35246, "s": 35238, "text": "Kingash" }, { "code": null, "e": 35262, "s": 35246, "text": "souravghosh0416" }, { "code": null, "e": 35269, "s": 35262, "text": "rdtank" }, { "code": null, "e": 35275, "s": 35269, "text": "ukasp" }, { "code": null, "e": 35291, "s": 35275, "text": "\nbinary-string\n" }, { "code": null, "e": 35317, "s": 35291, "text": "\nTechnical Scripter 2020\n" }, { "code": null, "e": 35337, "s": 35317, "text": "\nPattern Searching\n" }, { "code": null, "e": 35347, "s": 35337, "text": "\nStrings\n" }, { "code": null, "e": 35368, "s": 35347, "text": "\nTechnical Scripter\n" }, { "code": null, "e": 35573, "s": 35368, "text": "Writing code in comment? \n Please use ide.geeksforgeeks.org, \n generate link and share the link here.\n " }, { "code": null, "e": 35637, "s": 35573, "text": "Check whether two strings contain same characters in same order" }, { "code": null, "e": 35692, "s": 35637, "text": "Count of total Heads and Tails after N flips in a coin" }, { "code": null, "e": 35761, "s": 35692, "text": "How to check Aadhaar number is valid or not using Regular Expression" }, { "code": null, "e": 35836, "s": 35761, "text": "How to validate GUID (Globally Unique Identifier) using Regular Expression" }, { "code": null, "e": 35900, "s": 35836, "text": "How to validate time in 24-hour format using Regular Expression" }, { "code": null, "e": 35925, "s": 35900, "text": "Reverse a string in Java" }, { "code": null, "e": 35971, "s": 35925, "text": "Write a program to reverse an array or string" }, { "code": null, "e": 36005, "s": 35971, "text": "Longest Common Subsequence | DP-4" }, { "code": null, "e": 36066, "s": 36005, "text": "Write a program to print all permutations of a given string" } ]
Convert Singly Linked List to XOR Linked List - GeeksforGeeks
28 Mar, 2022 Prerequisite: XOR Linked List – A Memory Efficient Doubly Linked List | Set 1 XOR Linked List – A Memory Efficient Doubly Linked List | Set 2 An XOR linked list is a memory efficient doubly linked list in which the next pointer of every node stores the XOR of previous and next node’s address. Given a singly linked list, the task is to convert the given singly list to a XOR linked list. Approach: Since in XOR linked list each next pointer stores the XOR of prev and next nodes’s address. So the idea is to traverse the given singly linked list and keep track of the previous node in a pointer say prev.Now, while traversing the list, change the next pointer of every node as: current -> next = XOR(prev, current->next) Printing the XOR linked list: While printing XOR linked list we have to find the exact address of the next node every time. As we have seen above that the next pointer of every node stores the XOR value of prev and next node’s address. Therefore, the next node’s address can be obtained by finding XOR of prev and next pointer of current node in the XOR linked list.So, to print the XOR linked list, traverse it by maintaining a prev pointer which stores the address of the previous node and to find the next node, calculate XOR of prev with next of current node.Below is the implementation of the above approach: CPP Java Python3 C# Javascript // C++ program to Convert a Singly Linked// List to XOR Linked List #include <bits/stdc++.h> using namespace std; // Linked List nodestruct Node { int data; struct Node* next;}; // Utility function to create new nodeNode* newNode(int data){ Node* temp = new Node; temp->data = data; temp->next = NULL; return temp;} // Print singly linked list before conversionvoid print(Node* head){ while (head) { // print current node cout << head->data << " "; head = head->next; } cout << endl;} // Function to find XORed value of// the node addressesNode* XOR(Node* a, Node* b){ return (Node*)((uintptr_t)(a) ^ (uintptr_t)(b));} // Function to convert singly linked// list to XOR linked listvoid convert(Node* head){ Node* curr = head; Node* prev = NULL; Node* next = curr->next; while (curr) { // store curr->next in next next = curr->next; // change curr->next to XOR of prev and next curr->next = XOR(prev, next); // prev will change to curr for next iteration prev = curr; // curr is now pointing to next for next iteration curr = next; }} // Function to print XORed linked listvoid printXOR(Node* head){ Node* curr = head; Node* prev = NULL; while (curr) { // print current node cout << curr->data << " "; Node* temp = curr; /* compute curr as prev^curr->next as it is previously set as prev^curr->next so this time curr would be prev^prev^curr->next which is curr->next */ curr = XOR(prev, curr->next); prev = temp; } cout << endl;} // Driver Codeint main(){ // Create following singly linked list // 1->2->3->4 Node* head = newNode(1); head->next = newNode(2); head->next->next = newNode(3); head->next->next->next = newNode(4); cout << "Before Conversion : " << endl; print(head); convert(head); cout << "After Conversion : " << endl; printXOR(head); return 0;} // Java program to Convert a Singly Linked// List to XOR Linked Listimport java.io.*; // Linked List nodeclass Node{ int data; Node next; // Utility function to create new node Node(int item) { data = item; next = null; }}class GFG{ public static Node root; // Print singly linked list before conversion static void print(Node head) { while (head != null) { // print current node System.out.print(head.data + " "); head = head.next; } System.out.println(); } // Function to find XORed value of // the node addresses static Node XOR(Node a, Node b) { return b; } // Function to convert singly linked // list to XOR linked list static void convert(Node head) { Node curr = head; Node prev = null; Node next = curr.next; while(curr != null) { // store curr->next in next next = curr.next; // change curr->next to XOR of prev and next curr.next = XOR(prev, next); // prev will change to curr for next iteration prev = curr; // curr is now pointing to next for next iteration curr = next; } } // Function to print XORed linked list static void printXOR(Node head) { Node curr = head; Node prev = null; while(curr != null) { // print current node System.out.print(curr.data + " "); Node temp = curr; /* compute curr as prev^curr->next as it is previously set as prev^curr->next so this time curr would be prev^prev^curr->next which is curr->next */ curr = XOR(prev, curr.next); prev = temp; } System.out.println(); } // Driver Code public static void main (String[] args) { // Create following singly linked list // 1->2->3->4 GFG tree = new GFG(); tree.root = new Node(1); tree.root.next = new Node(2); tree.root.next.next = new Node(3); tree.root.next.next.next = new Node(4); System.out.println("Before Conversion : "); print(root); convert(root); System.out.println("After Conversion : "); printXOR(root); }} // This code is contributed by avanitrachhadiya2155 # Python3 program to Convert a Singly Linked# List to XOR Linked List # Linked List nodeclass Node: def __init__(self,d): self.data = d self.next = None # Print singly linked list before conversiondef printt(head): while (head): # print current node print(head.data, end=" ") head = head.next print() # Function to find XORed value of# the node addressesdef XOR(a, b): return b # Function to convert singly linked# list to XOR linked listdef convert(head): curr = head prev = None next = curr.next while (curr): # store curr.next in next next = curr.next # change curr.next to XOR of prev and next curr.next = XOR(prev, next) # prev will change to curr for next iteration prev = curr # curr is now pointing to next for next iteration curr = next # Function to print XORed linked listdef printXOR(head): curr = head prev = None while (curr): # print current node print(curr.data, end=" ") temp = curr # /* compute curr as prev^curr.next as # it is previously set as prev^curr.next so # this time curr would be prev^prev^curr.next # which is curr.next */ curr = XOR(prev, curr.next) prev = temp print() # Driver Codeif __name__ == '__main__': # Create following singly linked list # 1.2.3.4 head = Node(1) head.next = Node(2) head.next.next = Node(3) head.next.next.next = Node(4) print("Before Conversion : ") printt(head) convert(head) print("After Conversion : ") printXOR(head) # This code is contributed by mohitkumar29 using System;class Node{ public int data; public Node next; // Utility function to create new node public Node(int item) { data = item; next = null; }} public class GFG{ static Node root; // Print singly linked list before conversion static void print(Node head) { while (head != null) { // print current node Console.Write(head.data + " "); head = head.next; } Console.WriteLine(); } // Function to find XORed value of // the node addresses static Node XOR(Node a, Node b) { return b; } // Function to convert singly linked // list to XOR linked list static void convert(Node head) { Node curr = head; Node prev = null; Node next = curr.next; while(curr != null) { // store curr->next in next next = curr.next; // change curr->next to XOR of prev and next curr.next = XOR(prev, next); // prev will change to curr for next iteration prev = curr; // curr is now pointing to next for next iteration curr = next; } } // Function to print XORed linked list static void printXOR(Node head) { Node curr = head; Node prev = null; while(curr != null) { // print current node Console.Write(curr.data + " "); Node temp = curr; /* compute curr as prev^curr->next as it is previously set as prev^curr->next so this time curr would be prev^prev^curr->next which is curr->next */ curr = XOR(prev, curr.next); prev = temp; } Console.WriteLine(); } // Driver Code static public void Main () { // Create following singly linked list // 1->2->3->4 GFG.root = new Node(1); GFG.root.next = new Node(2); GFG.root.next.next = new Node(3); GFG.root.next.next.next = new Node(4); Console.WriteLine("Before Conversion : "); print(root); convert(root); Console.WriteLine("After Conversion : "); printXOR(root); }} // This code is contributed by rag2127 <script>// javascript program to Convert a Singly Linked// List to XOR Linked List// Linked List nodeclass Node { // Utility function to create new node constructor(val) { this.data = val; this.next = null; }}var root; // Print singly linked list before conversion function print( head) { while (head != null) { // print current node document.write(head.data + " "); head = head.next; } document.write("<br/>"); } // Function to find XORed value of // the node addresses function XOR( a, b) { return b; } // Function to convert singly linked // list to XOR linked list function convert( head) { var curr = head; var prev = null; var next = curr.next; while (curr != null) { // store curr->next in next next = curr.next; // change curr->next to XOR of prev and next curr.next = XOR(prev, next); // prev will change to curr for next iteration prev = curr; // curr is now pointing to next for next iteration curr = next; } } // Function to print XORed linked list function printXOR( head) { var curr = head; var prev = null; while (curr != null) { // print current node document.write(curr.data + " "); var temp = curr; /* * compute curr as prev^curr->next as it is previously set as prev^curr->next so * this time curr would be prev^prev^curr->next which is curr->next */ curr = XOR(prev, curr.next); prev = temp; } document.write(); } // Driver Code // Create following singly linked list // 1->2->3->4 root = new Node(1); root.next = new Node(2); root.next.next = new Node(3); root.next.next.next = new Node(4); document.write("Before Conversion : <br/>"); print(root); convert(root); document.write("After Conversion : <br/>"); printXOR(root); // This code contributed by gauravrajput1</script> Before Conversion : 1 2 3 4 After Conversion : 1 2 3 4 Akanksha_Rai mohit kumar 29 avanitrachhadiya2155 rag2127 GauravRajput1 sagar0719kumar khushboogoyal499 as5853535 sumitgumber28 Bitwise-XOR doubly linked list Linked List Linked List Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Delete a node in a Doubly Linked List Given a linked list which is sorted, how will you insert in sorted way Insert a node at a specific position in a linked list Circular Linked List | Set 2 (Traversal) Program to implement Singly Linked List in C++ using class Swap nodes in a linked list without swapping data Priority Queue using Linked List Circular Singly Linked List | Insertion Real-time application of Data Structures Insertion Sort for Singly Linked List
[ { "code": null, "e": 24568, "s": 24540, "text": "\n28 Mar, 2022" }, { "code": null, "e": 24584, "s": 24568, "text": "Prerequisite: " }, { "code": null, "e": 24648, "s": 24584, "text": "XOR Linked List – A Memory Efficient Doubly Linked List | Set 1" }, { "code": null, "e": 24712, "s": 24648, "text": "XOR Linked List – A Memory Efficient Doubly Linked List | Set 2" }, { "code": null, "e": 24960, "s": 24712, "text": "An XOR linked list is a memory efficient doubly linked list in which the next pointer of every node stores the XOR of previous and next node’s address. Given a singly linked list, the task is to convert the given singly list to a XOR linked list. " }, { "code": null, "e": 25252, "s": 24960, "text": "Approach: Since in XOR linked list each next pointer stores the XOR of prev and next nodes’s address. So the idea is to traverse the given singly linked list and keep track of the previous node in a pointer say prev.Now, while traversing the list, change the next pointer of every node as: " }, { "code": null, "e": 25295, "s": 25252, "text": "current -> next = XOR(prev, current->next)" }, { "code": null, "e": 25911, "s": 25295, "text": "Printing the XOR linked list: While printing XOR linked list we have to find the exact address of the next node every time. As we have seen above that the next pointer of every node stores the XOR value of prev and next node’s address. Therefore, the next node’s address can be obtained by finding XOR of prev and next pointer of current node in the XOR linked list.So, to print the XOR linked list, traverse it by maintaining a prev pointer which stores the address of the previous node and to find the next node, calculate XOR of prev with next of current node.Below is the implementation of the above approach: " }, { "code": null, "e": 25915, "s": 25911, "text": "CPP" }, { "code": null, "e": 25920, "s": 25915, "text": "Java" }, { "code": null, "e": 25928, "s": 25920, "text": "Python3" }, { "code": null, "e": 25931, "s": 25928, "text": "C#" }, { "code": null, "e": 25942, "s": 25931, "text": "Javascript" }, { "code": "// C++ program to Convert a Singly Linked// List to XOR Linked List #include <bits/stdc++.h> using namespace std; // Linked List nodestruct Node { int data; struct Node* next;}; // Utility function to create new nodeNode* newNode(int data){ Node* temp = new Node; temp->data = data; temp->next = NULL; return temp;} // Print singly linked list before conversionvoid print(Node* head){ while (head) { // print current node cout << head->data << \" \"; head = head->next; } cout << endl;} // Function to find XORed value of// the node addressesNode* XOR(Node* a, Node* b){ return (Node*)((uintptr_t)(a) ^ (uintptr_t)(b));} // Function to convert singly linked// list to XOR linked listvoid convert(Node* head){ Node* curr = head; Node* prev = NULL; Node* next = curr->next; while (curr) { // store curr->next in next next = curr->next; // change curr->next to XOR of prev and next curr->next = XOR(prev, next); // prev will change to curr for next iteration prev = curr; // curr is now pointing to next for next iteration curr = next; }} // Function to print XORed linked listvoid printXOR(Node* head){ Node* curr = head; Node* prev = NULL; while (curr) { // print current node cout << curr->data << \" \"; Node* temp = curr; /* compute curr as prev^curr->next as it is previously set as prev^curr->next so this time curr would be prev^prev^curr->next which is curr->next */ curr = XOR(prev, curr->next); prev = temp; } cout << endl;} // Driver Codeint main(){ // Create following singly linked list // 1->2->3->4 Node* head = newNode(1); head->next = newNode(2); head->next->next = newNode(3); head->next->next->next = newNode(4); cout << \"Before Conversion : \" << endl; print(head); convert(head); cout << \"After Conversion : \" << endl; printXOR(head); return 0;}", "e": 27964, "s": 25942, "text": null }, { "code": "// Java program to Convert a Singly Linked// List to XOR Linked Listimport java.io.*; // Linked List nodeclass Node{ int data; Node next; // Utility function to create new node Node(int item) { data = item; next = null; }}class GFG{ public static Node root; // Print singly linked list before conversion static void print(Node head) { while (head != null) { // print current node System.out.print(head.data + \" \"); head = head.next; } System.out.println(); } // Function to find XORed value of // the node addresses static Node XOR(Node a, Node b) { return b; } // Function to convert singly linked // list to XOR linked list static void convert(Node head) { Node curr = head; Node prev = null; Node next = curr.next; while(curr != null) { // store curr->next in next next = curr.next; // change curr->next to XOR of prev and next curr.next = XOR(prev, next); // prev will change to curr for next iteration prev = curr; // curr is now pointing to next for next iteration curr = next; } } // Function to print XORed linked list static void printXOR(Node head) { Node curr = head; Node prev = null; while(curr != null) { // print current node System.out.print(curr.data + \" \"); Node temp = curr; /* compute curr as prev^curr->next as it is previously set as prev^curr->next so this time curr would be prev^prev^curr->next which is curr->next */ curr = XOR(prev, curr.next); prev = temp; } System.out.println(); } // Driver Code public static void main (String[] args) { // Create following singly linked list // 1->2->3->4 GFG tree = new GFG(); tree.root = new Node(1); tree.root.next = new Node(2); tree.root.next.next = new Node(3); tree.root.next.next.next = new Node(4); System.out.println(\"Before Conversion : \"); print(root); convert(root); System.out.println(\"After Conversion : \"); printXOR(root); }} // This code is contributed by avanitrachhadiya2155", "e": 30469, "s": 27964, "text": null }, { "code": "# Python3 program to Convert a Singly Linked# List to XOR Linked List # Linked List nodeclass Node: def __init__(self,d): self.data = d self.next = None # Print singly linked list before conversiondef printt(head): while (head): # print current node print(head.data, end=\" \") head = head.next print() # Function to find XORed value of# the node addressesdef XOR(a, b): return b # Function to convert singly linked# list to XOR linked listdef convert(head): curr = head prev = None next = curr.next while (curr): # store curr.next in next next = curr.next # change curr.next to XOR of prev and next curr.next = XOR(prev, next) # prev will change to curr for next iteration prev = curr # curr is now pointing to next for next iteration curr = next # Function to print XORed linked listdef printXOR(head): curr = head prev = None while (curr): # print current node print(curr.data, end=\" \") temp = curr # /* compute curr as prev^curr.next as # it is previously set as prev^curr.next so # this time curr would be prev^prev^curr.next # which is curr.next */ curr = XOR(prev, curr.next) prev = temp print() # Driver Codeif __name__ == '__main__': # Create following singly linked list # 1.2.3.4 head = Node(1) head.next = Node(2) head.next.next = Node(3) head.next.next.next = Node(4) print(\"Before Conversion : \") printt(head) convert(head) print(\"After Conversion : \") printXOR(head) # This code is contributed by mohitkumar29", "e": 32143, "s": 30469, "text": null }, { "code": "using System;class Node{ public int data; public Node next; // Utility function to create new node public Node(int item) { data = item; next = null; }} public class GFG{ static Node root; // Print singly linked list before conversion static void print(Node head) { while (head != null) { // print current node Console.Write(head.data + \" \"); head = head.next; } Console.WriteLine(); } // Function to find XORed value of // the node addresses static Node XOR(Node a, Node b) { return b; } // Function to convert singly linked // list to XOR linked list static void convert(Node head) { Node curr = head; Node prev = null; Node next = curr.next; while(curr != null) { // store curr->next in next next = curr.next; // change curr->next to XOR of prev and next curr.next = XOR(prev, next); // prev will change to curr for next iteration prev = curr; // curr is now pointing to next for next iteration curr = next; } } // Function to print XORed linked list static void printXOR(Node head) { Node curr = head; Node prev = null; while(curr != null) { // print current node Console.Write(curr.data + \" \"); Node temp = curr; /* compute curr as prev^curr->next as it is previously set as prev^curr->next so this time curr would be prev^prev^curr->next which is curr->next */ curr = XOR(prev, curr.next); prev = temp; } Console.WriteLine(); } // Driver Code static public void Main () { // Create following singly linked list // 1->2->3->4 GFG.root = new Node(1); GFG.root.next = new Node(2); GFG.root.next.next = new Node(3); GFG.root.next.next.next = new Node(4); Console.WriteLine(\"Before Conversion : \"); print(root); convert(root); Console.WriteLine(\"After Conversion : \"); printXOR(root); }} // This code is contributed by rag2127", "e": 34530, "s": 32143, "text": null }, { "code": "<script>// javascript program to Convert a Singly Linked// List to XOR Linked List// Linked List nodeclass Node { // Utility function to create new node constructor(val) { this.data = val; this.next = null; }}var root; // Print singly linked list before conversion function print( head) { while (head != null) { // print current node document.write(head.data + \" \"); head = head.next; } document.write(\"<br/>\"); } // Function to find XORed value of // the node addresses function XOR( a, b) { return b; } // Function to convert singly linked // list to XOR linked list function convert( head) { var curr = head; var prev = null; var next = curr.next; while (curr != null) { // store curr->next in next next = curr.next; // change curr->next to XOR of prev and next curr.next = XOR(prev, next); // prev will change to curr for next iteration prev = curr; // curr is now pointing to next for next iteration curr = next; } } // Function to print XORed linked list function printXOR( head) { var curr = head; var prev = null; while (curr != null) { // print current node document.write(curr.data + \" \"); var temp = curr; /* * compute curr as prev^curr->next as it is previously set as prev^curr->next so * this time curr would be prev^prev^curr->next which is curr->next */ curr = XOR(prev, curr.next); prev = temp; } document.write(); } // Driver Code // Create following singly linked list // 1->2->3->4 root = new Node(1); root.next = new Node(2); root.next.next = new Node(3); root.next.next.next = new Node(4); document.write(\"Before Conversion : <br/>\"); print(root); convert(root); document.write(\"After Conversion : <br/>\"); printXOR(root); // This code contributed by gauravrajput1</script>", "e": 36718, "s": 34530, "text": null }, { "code": null, "e": 36776, "s": 36718, "text": "Before Conversion : \n1 2 3 4 \nAfter Conversion : \n1 2 3 4" }, { "code": null, "e": 36791, "s": 36778, "text": "Akanksha_Rai" }, { "code": null, "e": 36806, "s": 36791, "text": "mohit kumar 29" }, { "code": null, "e": 36827, "s": 36806, "text": "avanitrachhadiya2155" }, { "code": null, "e": 36835, "s": 36827, "text": "rag2127" }, { "code": null, "e": 36849, "s": 36835, "text": "GauravRajput1" }, { "code": null, "e": 36864, "s": 36849, "text": "sagar0719kumar" }, { "code": null, "e": 36881, "s": 36864, "text": "khushboogoyal499" }, { "code": null, "e": 36891, "s": 36881, "text": "as5853535" }, { "code": null, "e": 36905, "s": 36891, "text": "sumitgumber28" }, { "code": null, "e": 36917, "s": 36905, "text": "Bitwise-XOR" }, { "code": null, "e": 36936, "s": 36917, "text": "doubly linked list" }, { "code": null, "e": 36948, "s": 36936, "text": "Linked List" }, { "code": null, "e": 36960, "s": 36948, "text": "Linked List" }, { "code": null, "e": 37058, "s": 36960, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 37067, "s": 37058, "text": "Comments" }, { "code": null, "e": 37080, "s": 37067, "text": "Old Comments" }, { "code": null, "e": 37118, "s": 37080, "text": "Delete a node in a Doubly Linked List" }, { "code": null, "e": 37189, "s": 37118, "text": "Given a linked list which is sorted, how will you insert in sorted way" }, { "code": null, "e": 37243, "s": 37189, "text": "Insert a node at a specific position in a linked list" }, { "code": null, "e": 37284, "s": 37243, "text": "Circular Linked List | Set 2 (Traversal)" }, { "code": null, "e": 37343, "s": 37284, "text": "Program to implement Singly Linked List in C++ using class" }, { "code": null, "e": 37393, "s": 37343, "text": "Swap nodes in a linked list without swapping data" }, { "code": null, "e": 37426, "s": 37393, "text": "Priority Queue using Linked List" }, { "code": null, "e": 37466, "s": 37426, "text": "Circular Singly Linked List | Insertion" }, { "code": null, "e": 37507, "s": 37466, "text": "Real-time application of Data Structures" } ]
Python 3 - dictionary keys() Method
The method keys() returns a list of all the available keys in the dictionary. Following is the syntax for keys() method − dict.keys() NA This method returns a list of all the available keys in the dictionary. The following example shows the usage of keys() method. #!/usr/bin/python3 dict = {'Name': 'Zara', 'Age': 7} print ("Value : %s" % dict.keys()) When we run above program, it produces the following result − Value : dict_keys(['Age', 'Name']) 187 Lectures 17.5 hours Malhar Lathkar 55 Lectures 8 hours Arnab Chakraborty 136 Lectures 11 hours In28Minutes Official 75 Lectures 13 hours Eduonix Learning Solutions 70 Lectures 8.5 hours Lets Kode It 63 Lectures 6 hours Abhilash Nelson Print Add Notes Bookmark this page
[ { "code": null, "e": 2418, "s": 2340, "text": "The method keys() returns a list of all the available keys in the dictionary." }, { "code": null, "e": 2462, "s": 2418, "text": "Following is the syntax for keys() method −" }, { "code": null, "e": 2475, "s": 2462, "text": "dict.keys()\n" }, { "code": null, "e": 2478, "s": 2475, "text": "NA" }, { "code": null, "e": 2550, "s": 2478, "text": "This method returns a list of all the available keys in the dictionary." }, { "code": null, "e": 2606, "s": 2550, "text": "The following example shows the usage of keys() method." }, { "code": null, "e": 2696, "s": 2606, "text": "#!/usr/bin/python3\n\ndict = {'Name': 'Zara', 'Age': 7}\nprint (\"Value : %s\" % dict.keys())" }, { "code": null, "e": 2758, "s": 2696, "text": "When we run above program, it produces the following result −" }, { "code": null, "e": 2794, "s": 2758, "text": "Value : dict_keys(['Age', 'Name'])\n" }, { "code": null, "e": 2831, "s": 2794, "text": "\n 187 Lectures \n 17.5 hours \n" }, { "code": null, "e": 2847, "s": 2831, "text": " Malhar Lathkar" }, { "code": null, "e": 2880, "s": 2847, "text": "\n 55 Lectures \n 8 hours \n" }, { "code": null, "e": 2899, "s": 2880, "text": " Arnab Chakraborty" }, { "code": null, "e": 2934, "s": 2899, "text": "\n 136 Lectures \n 11 hours \n" }, { "code": null, "e": 2956, "s": 2934, "text": " In28Minutes Official" }, { "code": null, "e": 2990, "s": 2956, "text": "\n 75 Lectures \n 13 hours \n" }, { "code": null, "e": 3018, "s": 2990, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 3053, "s": 3018, "text": "\n 70 Lectures \n 8.5 hours \n" }, { "code": null, "e": 3067, "s": 3053, "text": " Lets Kode It" }, { "code": null, "e": 3100, "s": 3067, "text": "\n 63 Lectures \n 6 hours \n" }, { "code": null, "e": 3117, "s": 3100, "text": " Abhilash Nelson" }, { "code": null, "e": 3124, "s": 3117, "text": " Print" }, { "code": null, "e": 3135, "s": 3124, "text": " Add Notes" } ]
C# program to find the maximum of three numbers
Firstly, let’s set the three numbers − int num1, num2, num3; // set the value of the three numbers num1 = 10; num2 = 20; num3 = 50; Now check the first number with the second number. If num1 > num2, then check num1 with num3. If num1 is greater than num3, that would mean the largest number is num1. You can try to run the following code to find the maximum of three numbers. Live Demo using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Demo { class MyApplication { static void Main(string[] args) { int num1, num2, num3; // set the value of the three numbers num1 = 10; num2 = 20; num3 = 50; if (num1 > num2) { if (num1 > num3) { Console.Write("Number one is the largest!\n"); } else { Console.Write("Number three is the largest!\n"); } } else if (num2 > num3) Console.Write("Number two is the largest!\n"); else Console.Write("Number three is the largest!\n"); } } } Number three is the largest!
[ { "code": null, "e": 1101, "s": 1062, "text": "Firstly, let’s set the three numbers −" }, { "code": null, "e": 1194, "s": 1101, "text": "int num1, num2, num3;\n// set the value of the three numbers\nnum1 = 10;\nnum2 = 20;\nnum3 = 50;" }, { "code": null, "e": 1362, "s": 1194, "text": "Now check the first number with the second number. If num1 > num2, then check num1 with num3. If num1 is greater than num3, that would mean the largest number is num1." }, { "code": null, "e": 1438, "s": 1362, "text": "You can try to run the following code to find the maximum of three numbers." }, { "code": null, "e": 1448, "s": 1438, "text": "Live Demo" }, { "code": null, "e": 2147, "s": 1448, "text": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\nnamespace Demo {\n class MyApplication {\n static void Main(string[] args) {\n int num1, num2, num3;\n // set the value of the three numbers\n num1 = 10;\n num2 = 20;\n num3 = 50;\n if (num1 > num2) {\n if (num1 > num3) {\n Console.Write(\"Number one is the largest!\\n\");\n } else {\n Console.Write(\"Number three is the largest!\\n\");\n }\n }\n else if (num2 > num3)\n Console.Write(\"Number two is the largest!\\n\");\n else\n Console.Write(\"Number three is the largest!\\n\");\n }\n }\n}" }, { "code": null, "e": 2176, "s": 2147, "text": "Number three is the largest!" } ]
Java Examples - Read-only Collection
How to make a collection read-only ? Following example shows how to make a collection read-only by using Collections.unmodifiableList() method of Collection class. import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; public class Main { public static void main(String[] argv) throws Exception { List stuff = Arrays.asList(new String[] { "a", "b" }); List list = new ArrayList(stuff); list = Collections.unmodifiableList(list); try { list.set(0, "new value"); } catch (UnsupportedOperationException e) { } Set set = new HashSet(stuff); set = Collections.unmodifiableSet(set); Map map = new HashMap(); map = Collections.unmodifiableMap(map); System.out.println("Collection is read-only now."); } } The above code sample will produce the following result. Collection is read-only now. Print Add Notes Bookmark this page
[ { "code": null, "e": 2105, "s": 2068, "text": "How to make a collection read-only ?" }, { "code": null, "e": 2232, "s": 2105, "text": "Following example shows how to make a collection read-only by using Collections.unmodifiableList() method of Collection class." }, { "code": null, "e": 2995, "s": 2232, "text": "import java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.Collections;\nimport java.util.HashMap;\nimport java.util.HashSet;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Set;\n\npublic class Main {\n public static void main(String[] argv) throws Exception {\n List stuff = Arrays.asList(new String[] { \"a\", \"b\" });\n List list = new ArrayList(stuff);\n list = Collections.unmodifiableList(list);\n try {\n list.set(0, \"new value\");\n } catch (UnsupportedOperationException e) {\n }\n Set set = new HashSet(stuff);\n set = Collections.unmodifiableSet(set);\n Map map = new HashMap();\n map = Collections.unmodifiableMap(map);\n System.out.println(\"Collection is read-only now.\");\n }\n}" }, { "code": null, "e": 3052, "s": 2995, "text": "The above code sample will produce the following result." }, { "code": null, "e": 3082, "s": 3052, "text": "Collection is read-only now.\n" }, { "code": null, "e": 3089, "s": 3082, "text": " Print" }, { "code": null, "e": 3100, "s": 3089, "text": " Add Notes" } ]
How to log in to the Azure account using Az CLI command in PowerShell?
To login to the Azure account using Azure CLI, we need to use the az login command. Once you type the az login command, it will prompt for the Azure portal login console. If you need to log in with the device authentication code in the browser, you need to use the parameter –use-device-code. PS C:\> az login --use-device-code To sign in, use a web browser to open the page https://microsoft.com/devicelogin and enter the code ‘DeviceCode’ to authenticate. You need to open a website https://microsoft.com/devicelogin/ and have to enter a code. If you are not already connected with the Microsoft Azure portal, you need to log in first. You can also provide the username and password in the command line as shown below. PS C:\> az login --username azureusername --password azurepassword If the password is not provided, it will prompt for the secret password. PS C:\> az login --username azureuseraccount Password:
[ { "code": null, "e": 1233, "s": 1062, "text": "To login to the Azure account using Azure CLI, we need to use the az login command. Once you type the az login command, it will prompt for the Azure portal login console." }, { "code": null, "e": 1355, "s": 1233, "text": "If you need to log in with the device authentication code in the browser, you need to use the parameter –use-device-code." }, { "code": null, "e": 1520, "s": 1355, "text": "PS C:\\> az login --use-device-code\nTo sign in, use a web browser to open the page https://microsoft.com/devicelogin and enter the code ‘DeviceCode’ to authenticate." }, { "code": null, "e": 1700, "s": 1520, "text": "You need to open a website https://microsoft.com/devicelogin/ and have to enter a code. If you are not already connected with the Microsoft Azure portal, you need to log in first." }, { "code": null, "e": 1783, "s": 1700, "text": "You can also provide the username and password in the command line as shown below." }, { "code": null, "e": 1850, "s": 1783, "text": "PS C:\\> az login --username azureusername --password azurepassword" }, { "code": null, "e": 1923, "s": 1850, "text": "If the password is not provided, it will prompt for the secret password." }, { "code": null, "e": 1978, "s": 1923, "text": "PS C:\\> az login --username azureuseraccount\nPassword:" } ]
Truncate with condition in MySQL?
In MySQL, there is no way to truncate with condition. You cannot use truncate statement with where clause. If you want the condition, use delete command − DELETE FROM yourTableName WHERE youCondition; The above syntax is fine but if you want a faster solution, then DELETE is not good in comparison to Truncate. The advantage with truncate is that it does not write to the logs. Let us create a table. The query to create a table is as follows − mysql> create table DeleteDemo -> ( -> Id int, -> Name varchar(100) -> ); Query OK, 0 rows affected (1.22 sec) Insert some records in the table using insert command. The query is as follows − mysql> insert into DeleteDemo values(101,'Carol'); Query OK, 1 row affected (0.15 sec) mysql> insert into DeleteDemo values(102,'Sam'); Query OK, 1 row affected (0.15 sec) mysql> insert into DeleteDemo values(103,'Bob'); Query OK, 1 row affected (0.16 sec) mysql> insert into DeleteDemo values(104,'Mike'); Query OK, 1 row affected (0.17 sec) mysql> insert into DeleteDemo values(105,'John'); Query OK, 1 row affected (0.09 sec) mysql> insert into DeleteDemo values(106,'Maria'); Query OK, 1 row affected (0.20 sec) mysql> insert into DeleteDemo values(107,'Johnson'); Query OK, 1 row affected (0.17 sec) Let us now display all records from the table using select command. The query is as follows − mysql> select *from DeleteDemo; +------+---------+ | Id | Name | +------+---------+ | 101 | Carol | | 102 | Sam | | 103 | Bob | | 104 | Mike | | 105 | John | | 106 | Maria | | 107 | Johnson | +------+---------+ 7 rows in set (0.00 sec) Now you can use delete command but that won’t truncate with where clause. The query to delete records from the table using where clause is as follows − mysql> delete from DeleteDemo where Id>104; Query OK, 3 rows affected (0.13 sec) Let us check the table data once again using select command. The query is as follows − mysql> select *from DeleteDemo; +------+-------+ | Id | Name | +------+-------+ | 101 | Carol | | 102 | Sam | | 103 | Bob | | 104 | Mike | +------+-------+ 4 rows in set (0.00 sec) Look at the above sample output, all records greater than 104 is deleted from the table.
[ { "code": null, "e": 1169, "s": 1062, "text": "In MySQL, there is no way to truncate with condition. You cannot use truncate statement with where clause." }, { "code": null, "e": 1217, "s": 1169, "text": "If you want the condition, use delete command −" }, { "code": null, "e": 1263, "s": 1217, "text": "DELETE FROM yourTableName WHERE youCondition;" }, { "code": null, "e": 1441, "s": 1263, "text": "The above syntax is fine but if you want a faster solution, then DELETE is not good in comparison to Truncate. The advantage with truncate is that it does not write to the logs." }, { "code": null, "e": 1508, "s": 1441, "text": "Let us create a table. The query to create a table is as follows −" }, { "code": null, "e": 1631, "s": 1508, "text": "mysql> create table DeleteDemo\n -> (\n -> Id int,\n -> Name varchar(100)\n -> );\nQuery OK, 0 rows affected (1.22 sec)" }, { "code": null, "e": 1712, "s": 1631, "text": "Insert some records in the table using insert command. The query is as follows −" }, { "code": null, "e": 2323, "s": 1712, "text": "mysql> insert into DeleteDemo values(101,'Carol');\nQuery OK, 1 row affected (0.15 sec)\n\nmysql> insert into DeleteDemo values(102,'Sam');\nQuery OK, 1 row affected (0.15 sec)\n\nmysql> insert into DeleteDemo values(103,'Bob');\nQuery OK, 1 row affected (0.16 sec)\n\nmysql> insert into DeleteDemo values(104,'Mike');\nQuery OK, 1 row affected (0.17 sec)\n\nmysql> insert into DeleteDemo values(105,'John');\nQuery OK, 1 row affected (0.09 sec)\n\nmysql> insert into DeleteDemo values(106,'Maria');\nQuery OK, 1 row affected (0.20 sec)\n\nmysql> insert into DeleteDemo values(107,'Johnson');\nQuery OK, 1 row affected (0.17 sec)" }, { "code": null, "e": 2417, "s": 2323, "text": "Let us now display all records from the table using select command. The query is as follows −" }, { "code": null, "e": 2449, "s": 2417, "text": "mysql> select *from DeleteDemo;" }, { "code": null, "e": 2683, "s": 2449, "text": "+------+---------+\n| Id | Name |\n+------+---------+\n| 101 | Carol |\n| 102 | Sam |\n| 103 | Bob |\n| 104 | Mike |\n| 105 | John |\n| 106 | Maria |\n| 107 | Johnson |\n+------+---------+\n7 rows in set (0.00 sec)" }, { "code": null, "e": 2835, "s": 2683, "text": "Now you can use delete command but that won’t truncate with where clause. The query to delete records from the table using where clause is as follows −" }, { "code": null, "e": 2916, "s": 2835, "text": "mysql> delete from DeleteDemo where Id>104;\nQuery OK, 3 rows affected (0.13 sec)" }, { "code": null, "e": 3003, "s": 2916, "text": "Let us check the table data once again using select command. The query is as follows −" }, { "code": null, "e": 3035, "s": 3003, "text": "mysql> select *from DeleteDemo;" }, { "code": null, "e": 3196, "s": 3035, "text": "+------+-------+\n| Id | Name |\n+------+-------+\n| 101 | Carol |\n| 102 | Sam |\n| 103 | Bob |\n| 104 | Mike |\n+------+-------+\n4 rows in set (0.00 sec)" }, { "code": null, "e": 3285, "s": 3196, "text": "Look at the above sample output, all records greater than 104 is deleted from the table." } ]
In MySQL how to select the top 2 rows for each group?
To select the top 2 rows from each group, use the where condition with subquery. Let us create a table. The query to create a table is as follows: mysql> create table selectTop2FromEachGroup -> ( -> Name varchar(20), -> TotalScores int -> ); Query OK, 0 rows affected (0.80 sec) Now insert some records in the table using insert command. The query is as follows: mysql> insert into selectTop2FromEachGroup values('John',32); Query OK, 1 row affected (0.38 sec) mysql> insert into selectTop2FromEachGroup values('John',33); Query OK, 1 row affected (0.21 sec) mysql> insert into selectTop2FromEachGroup values('John',34); Query OK, 1 row affected (0.17 sec) mysql> insert into selectTop2FromEachGroup values('Carol',35); Query OK, 1 row affected (0.17 sec) mysql> insert into selectTop2FromEachGroup values('Carol',36); Query OK, 1 row affected (0.14 sec) mysql> insert into selectTop2FromEachGroup values('Carol',37); Query OK, 1 row affected (0.15 sec) Display all records from the table using select statement. The query is as follows: mysql> select *from selectTop2FromEachGroup; The following is the output: +-------+-------------+ | Name | TotalScores | +-------+-------------+ | John | 32 | | John | 33 | | John | 34 | | Carol | 35 | | Carol | 36 | | Carol | 37 | +-------+-------------+ 6 rows in set (0.00 sec) Here is the query to select top 2 rows from each group using where condition and subquery: mysql> select *from selectTop2FromEachGroup tbl -> where -> ( -> SELECT COUNT(*) -> FROM selectTop2FromEachGroup tbl1 -> WHERE tbl1.Name = tbl.Name AND -> tbl1.TotalScores >= tbl.TotalScores -> ) <= 2 ; The following is the output: +-------+-------------+ | Name | TotalScores | +-------+-------------+ | John | 33 | | John | 34 | | Carol | 36 | | Carol | 37 | +-------+-------------+ 4 rows in set (0.06 sec)
[ { "code": null, "e": 1209, "s": 1062, "text": "To select the top 2 rows from each group, use the where condition with subquery. Let us create a table. The query to create a table is as follows:" }, { "code": null, "e": 1353, "s": 1209, "text": "mysql> create table selectTop2FromEachGroup\n -> (\n -> Name varchar(20),\n -> TotalScores int\n -> );\nQuery OK, 0 rows affected (0.80 sec)" }, { "code": null, "e": 1437, "s": 1353, "text": "Now insert some records in the table using insert command. The query is as follows:" }, { "code": null, "e": 2028, "s": 1437, "text": "mysql> insert into selectTop2FromEachGroup values('John',32);\nQuery OK, 1 row affected (0.38 sec)\nmysql> insert into selectTop2FromEachGroup values('John',33);\nQuery OK, 1 row affected (0.21 sec)\nmysql> insert into selectTop2FromEachGroup values('John',34);\nQuery OK, 1 row affected (0.17 sec)\nmysql> insert into selectTop2FromEachGroup values('Carol',35);\nQuery OK, 1 row affected (0.17 sec)\nmysql> insert into selectTop2FromEachGroup values('Carol',36);\nQuery OK, 1 row affected (0.14 sec)\nmysql> insert into selectTop2FromEachGroup values('Carol',37);\nQuery OK, 1 row affected (0.15 sec)" }, { "code": null, "e": 2112, "s": 2028, "text": "Display all records from the table using select statement. The query is as follows:" }, { "code": null, "e": 2157, "s": 2112, "text": "mysql> select *from selectTop2FromEachGroup;" }, { "code": null, "e": 2186, "s": 2157, "text": "The following is the output:" }, { "code": null, "e": 2451, "s": 2186, "text": "+-------+-------------+\n| Name | TotalScores |\n+-------+-------------+\n| John | 32 |\n| John | 33 |\n| John | 34 |\n| Carol | 35 |\n| Carol | 36 |\n| Carol | 37 |\n+-------+-------------+\n6 rows in set (0.00 sec)" }, { "code": null, "e": 2542, "s": 2451, "text": "Here is the query to select top 2 rows from each group using where condition and subquery:" }, { "code": null, "e": 2778, "s": 2542, "text": "mysql> select *from selectTop2FromEachGroup tbl\n -> where\n -> (\n -> SELECT COUNT(*)\n -> FROM selectTop2FromEachGroup tbl1\n -> WHERE tbl1.Name = tbl.Name AND\n -> tbl1.TotalScores >= tbl.TotalScores\n -> ) <= 2 ;" }, { "code": null, "e": 2807, "s": 2778, "text": "The following is the output:" }, { "code": null, "e": 3024, "s": 2807, "text": "+-------+-------------+\n| Name | TotalScores |\n+-------+-------------+\n| John | 33 |\n| John | 34 |\n| Carol | 36 |\n| Carol | 37 |\n+-------+-------------+\n4 rows in set (0.06 sec)" } ]
Webcam Object Detection with Mask R-CNN on Google Colab | by Emad Ehsan | Towards Data Science
There are plenty of approaches to do Object Detection. YOLO (You Only Look Once) is the algorithm of choice for many, because it passes the image through the Fully Convolutional Neural Network (FCNN) only once. This makes the inference fast. About 30 frames per second on a GPU. Another popular approach is the use of Region Proposal Network (RPN). RPN based algorithms have two components. First component gives proposals for Regions of Interests (RoI)... i.e. where in the image might be objects. The second component does the image classification task on these proposed regions. This approach is slower. Mask R-CNN is a framework by Facebook AI that makes use of RPN for object detection. Mask R-CNN can operate at about 5 frames per second on a GPU. We will use Mask R-CNN. Why use a slow algorithm when there are faster alternatives? Glad you asked! Mask R-CNN also outputs object-masks in addition to object detection and bounding box prediction. The following sections contain an explanation of the code and concepts that will help in understanding object detection, and working with camera inputs with Mask R-CNN, on Colab. It’s not a step by step tutorial but hopefully, it would be as effective. At the end of this article, you will find the link to the Colab notebook to try it yourself. Matterport has a great implementation of Mask R-CNN using Keras and Tensorflow. They have provided Notebooks to play with Mask R-CNN, to train Mask R-CNN with your own dataset and to inspect the model and weights. If you don’t have a GPU machine or don’t want to go through the tedious task of setting up the development environment, Colab is the best temporary option. In my case, I had lost my favorite laptop recently. So, I am on my backup machine — a windows tablet with a keyboard. Colab enables you to work in a Jupyter Notebook in your browser, connected to a powerful GPU or a TPU (Tensor Processing Unit) virtual machine in Google Cloud. The VM comes pre-installed with Python, Tensorflow, Keras, PyTorch, Fastai and a lot of other important Machine Learning tools. All for free. Beware that your session progress gets lost due to a few minutes of inactivity. The Welcome to Colaboratory guide gets you started easily. And the Advanced Colab guide comes in handy when taking input from camera, communicating between different cells of the notebook, and communication between Python and JavaScript code. If you don’t have time to look at them, just remember the following. A cell in Colab notebook usually contains Python code. By default, the code runs inside /content directory of the connected Virtual Machine. Ubuntu is the operating system of Colab VMs and you can execute system commands by starting the line of the command with !. The following command will clone the repository. !git clone https://github.com/matterport/Mask_RCNN If you have multiple system commands in the same cell, then you must have %%shell as the first line of the cell followed by system commands. Thus, the following set of commands will clone the repository, change the directory to Mask_RCNN and setup the project. %%shell# clone Mask_RCNN repo and install packagesgit clone https://github.com/matterport/Mask_RCNNcd Mask_RCNNpython setup.py install The following code comes from Demo Notebook provided by Matterport. We only need to change the ROOT_DIR to ./Mask_RCNN, the project we just cloned. The python statement sys.path.append(ROOT_DIR) makes sure that the subsequent code executes within the context of Mask_RCNN directory where we have Mask R-CNN implementation available. The code imports the necessary libraries, classes and downloads the pre-trained Mask R-CNN model. Go through it. The comments make it easier to understand the code. Following code creates model object in inference mode, so we could run predictions. Then it loads the weights from the pre-trained model that we downloaded earlier, into the model object. Now we test the model on some images. Mask_RCNN repository has a directory named images that contains... you guessed it... some images. The following code takes an image from that directory, passes it through the model and displays the result on the notebook along with bounding box information. The result of the prediction In the advanced usage guide of Colab, they have provided code that can capture an image from a webcam in the notebook and then forward it to the Python code. Colab notebook has pre-installed python package called google.colab which contains handy helper methods. There's a method called output.eval_js which helps us evaluate the JavaScript code and returns the output to Python. And in JavaScript, we know that there is a method called getUserMedia() which enables us to capture the audio and/or video stream from user's webcam and microphone. Have a look at the following JavaScript code. Using getUserMedia() method of WebRTC API of JavaScript, it captures the video stream of the webcam and draws the individual frames on HTML canvas. Like google.colab Python package, we have google.colab library available to us in JavaScript. This library will help us invoke a Python method using kernel.invokeFunction function from our JavaScript code. The image captured from webcam is converted to Base64 format. This Base64 image is passed to a Python callback method, which we will define later. We already discussed that having %%shell as the first line of the Colab notebook cell makes it run as terminal commands. Similarly, you can write JavaScript in the whole cell by starting the cell with %%javascript. But we will simply put the JavaScript code we wrote above, inside the Python code. Like this: The JavaScript code we wrote above invokes notebook.run_algo method of our Python code. The following code defines a Python method run_algo which accepts a Base64 image, converts it to a numpy array and then passes it through the Mask R-CNN model we created above. Then it shows the output image and processing stats. Important! Don’t forget to surround the Python code of your callback method in try / except block and log it. Because it will be invoked by JavaScript and there will be no sign of what error occurred while calling the Python callback. Let’s register run_algo as notebook.run_algo. Now it will be invoke-able by the JavaScript code. We also call the take_photo() Python method we defined above, to start the video stream and object detection. You are now ready to try Mask R-CNN on camera in Google Colab. The notebook will walk you step by step through the process. The process we used above converts the camera stream to images in a browser (JavaScript) and sends individual images to our Python code for object detection. This is obviously not real-time. So, I spent hours trying to upload the WebRTC stream from the JavaScript (peer A) to the Python Server (peer B) without success. Perhaps my unfamiliarity with the combination of async / await with Python Threads was the main hindrance. I was trying to use aiohttp as Python server that will handle WebRTC connection using aiortc. The Python library aiortc makes it easy to create Python as a peer of WebRTC. Here is the link to the Colab notebook with an incomplete effort of creating WebRTC server. Originally published at https://emadehsan.com on January 29, 2020.
[ { "code": null, "e": 451, "s": 172, "text": "There are plenty of approaches to do Object Detection. YOLO (You Only Look Once) is the algorithm of choice for many, because it passes the image through the Fully Convolutional Neural Network (FCNN) only once. This makes the inference fast. About 30 frames per second on a GPU." }, { "code": null, "e": 950, "s": 451, "text": "Another popular approach is the use of Region Proposal Network (RPN). RPN based algorithms have two components. First component gives proposals for Regions of Interests (RoI)... i.e. where in the image might be objects. The second component does the image classification task on these proposed regions. This approach is slower. Mask R-CNN is a framework by Facebook AI that makes use of RPN for object detection. Mask R-CNN can operate at about 5 frames per second on a GPU. We will use Mask R-CNN." }, { "code": null, "e": 1027, "s": 950, "text": "Why use a slow algorithm when there are faster alternatives? Glad you asked!" }, { "code": null, "e": 1125, "s": 1027, "text": "Mask R-CNN also outputs object-masks in addition to object detection and bounding box prediction." }, { "code": null, "e": 1471, "s": 1125, "text": "The following sections contain an explanation of the code and concepts that will help in understanding object detection, and working with camera inputs with Mask R-CNN, on Colab. It’s not a step by step tutorial but hopefully, it would be as effective. At the end of this article, you will find the link to the Colab notebook to try it yourself." }, { "code": null, "e": 1685, "s": 1471, "text": "Matterport has a great implementation of Mask R-CNN using Keras and Tensorflow. They have provided Notebooks to play with Mask R-CNN, to train Mask R-CNN with your own dataset and to inspect the model and weights." }, { "code": null, "e": 1841, "s": 1685, "text": "If you don’t have a GPU machine or don’t want to go through the tedious task of setting up the development environment, Colab is the best temporary option." }, { "code": null, "e": 2341, "s": 1841, "text": "In my case, I had lost my favorite laptop recently. So, I am on my backup machine — a windows tablet with a keyboard. Colab enables you to work in a Jupyter Notebook in your browser, connected to a powerful GPU or a TPU (Tensor Processing Unit) virtual machine in Google Cloud. The VM comes pre-installed with Python, Tensorflow, Keras, PyTorch, Fastai and a lot of other important Machine Learning tools. All for free. Beware that your session progress gets lost due to a few minutes of inactivity." }, { "code": null, "e": 2653, "s": 2341, "text": "The Welcome to Colaboratory guide gets you started easily. And the Advanced Colab guide comes in handy when taking input from camera, communicating between different cells of the notebook, and communication between Python and JavaScript code. If you don’t have time to look at them, just remember the following." }, { "code": null, "e": 2918, "s": 2653, "text": "A cell in Colab notebook usually contains Python code. By default, the code runs inside /content directory of the connected Virtual Machine. Ubuntu is the operating system of Colab VMs and you can execute system commands by starting the line of the command with !." }, { "code": null, "e": 2967, "s": 2918, "text": "The following command will clone the repository." }, { "code": null, "e": 3018, "s": 2967, "text": "!git clone https://github.com/matterport/Mask_RCNN" }, { "code": null, "e": 3279, "s": 3018, "text": "If you have multiple system commands in the same cell, then you must have %%shell as the first line of the cell followed by system commands. Thus, the following set of commands will clone the repository, change the directory to Mask_RCNN and setup the project." }, { "code": null, "e": 3414, "s": 3279, "text": "%%shell# clone Mask_RCNN repo and install packagesgit clone https://github.com/matterport/Mask_RCNNcd Mask_RCNNpython setup.py install" }, { "code": null, "e": 3562, "s": 3414, "text": "The following code comes from Demo Notebook provided by Matterport. We only need to change the ROOT_DIR to ./Mask_RCNN, the project we just cloned." }, { "code": null, "e": 3912, "s": 3562, "text": "The python statement sys.path.append(ROOT_DIR) makes sure that the subsequent code executes within the context of Mask_RCNN directory where we have Mask R-CNN implementation available. The code imports the necessary libraries, classes and downloads the pre-trained Mask R-CNN model. Go through it. The comments make it easier to understand the code." }, { "code": null, "e": 4100, "s": 3912, "text": "Following code creates model object in inference mode, so we could run predictions. Then it loads the weights from the pre-trained model that we downloaded earlier, into the model object." }, { "code": null, "e": 4396, "s": 4100, "text": "Now we test the model on some images. Mask_RCNN repository has a directory named images that contains... you guessed it... some images. The following code takes an image from that directory, passes it through the model and displays the result on the notebook along with bounding box information." }, { "code": null, "e": 4425, "s": 4396, "text": "The result of the prediction" }, { "code": null, "e": 4583, "s": 4425, "text": "In the advanced usage guide of Colab, they have provided code that can capture an image from a webcam in the notebook and then forward it to the Python code." }, { "code": null, "e": 4970, "s": 4583, "text": "Colab notebook has pre-installed python package called google.colab which contains handy helper methods. There's a method called output.eval_js which helps us evaluate the JavaScript code and returns the output to Python. And in JavaScript, we know that there is a method called getUserMedia() which enables us to capture the audio and/or video stream from user's webcam and microphone." }, { "code": null, "e": 5370, "s": 4970, "text": "Have a look at the following JavaScript code. Using getUserMedia() method of WebRTC API of JavaScript, it captures the video stream of the webcam and draws the individual frames on HTML canvas. Like google.colab Python package, we have google.colab library available to us in JavaScript. This library will help us invoke a Python method using kernel.invokeFunction function from our JavaScript code." }, { "code": null, "e": 5517, "s": 5370, "text": "The image captured from webcam is converted to Base64 format. This Base64 image is passed to a Python callback method, which we will define later." }, { "code": null, "e": 5826, "s": 5517, "text": "We already discussed that having %%shell as the first line of the Colab notebook cell makes it run as terminal commands. Similarly, you can write JavaScript in the whole cell by starting the cell with %%javascript. But we will simply put the JavaScript code we wrote above, inside the Python code. Like this:" }, { "code": null, "e": 6144, "s": 5826, "text": "The JavaScript code we wrote above invokes notebook.run_algo method of our Python code. The following code defines a Python method run_algo which accepts a Base64 image, converts it to a numpy array and then passes it through the Mask R-CNN model we created above. Then it shows the output image and processing stats." }, { "code": null, "e": 6379, "s": 6144, "text": "Important! Don’t forget to surround the Python code of your callback method in try / except block and log it. Because it will be invoked by JavaScript and there will be no sign of what error occurred while calling the Python callback." }, { "code": null, "e": 6586, "s": 6379, "text": "Let’s register run_algo as notebook.run_algo. Now it will be invoke-able by the JavaScript code. We also call the take_photo() Python method we defined above, to start the video stream and object detection." }, { "code": null, "e": 6710, "s": 6586, "text": "You are now ready to try Mask R-CNN on camera in Google Colab. The notebook will walk you step by step through the process." }, { "code": null, "e": 7401, "s": 6710, "text": "The process we used above converts the camera stream to images in a browser (JavaScript) and sends individual images to our Python code for object detection. This is obviously not real-time. So, I spent hours trying to upload the WebRTC stream from the JavaScript (peer A) to the Python Server (peer B) without success. Perhaps my unfamiliarity with the combination of async / await with Python Threads was the main hindrance. I was trying to use aiohttp as Python server that will handle WebRTC connection using aiortc. The Python library aiortc makes it easy to create Python as a peer of WebRTC. Here is the link to the Colab notebook with an incomplete effort of creating WebRTC server." } ]
How to merge two object arrays of different size by key in JavaScript
Suppose, we have an object like this − const obj = { "part1": [{"id": 1, "a": 50},{"id": 2, "a": 55},{"id": 4, "a": 100}], "part2":[{"id": 1, "b": 40}, {"id": 3, "b": 45}, {"id": 4, "b": 110}] }; We are required to write a JavaScript function that takes in one such object. The function should merge part1 and part2 of the object to form an array of objects like this − const output = [ {"id": 1, "a": 50, "b": 40}, {"id": 2, "a": 55}, {"id": 3, "b": 45}, {"id": 4, "a": 100, "b": 110} ]; The code for this will be − const obj = { "part1": [{"id": 1, "a": 50},{"id": 2, "a": 55},{"id": 4, "a": 100}], "part2":[{"id": 1, "b": 40}, {"id": 3, "b": 45}, {"id": 4, "b": 110}] }; const mergeObject = (obj = {}) => { let result = []; result = Object.keys(obj).reduce(function (hash) { return function (r, k) { obj[k].forEach(function (o) { if (!hash[o.id]) { hash[o.id] = {}; r.push(hash[o.id]); } Object.keys(o).forEach(function (l) { hash[o.id][l] = o[l]; }); }); return r; }; }(Object.create(null)), []).sort((a, b) => { return a['id'] − b['id']; }); return result; }; console.log(mergeObject(obj)); And the output in the console will be − [ { id: 1, a: 50, b: 40 }, { id: 2, a: 55 }, { id: 3, b: 45 }, { id: 4, a: 100, b: 110 } ]
[ { "code": null, "e": 1101, "s": 1062, "text": "Suppose, we have an object like this −" }, { "code": null, "e": 1264, "s": 1101, "text": "const obj = {\n \"part1\": [{\"id\": 1, \"a\": 50},{\"id\": 2, \"a\": 55},{\"id\": 4, \"a\": 100}],\n \"part2\":[{\"id\": 1, \"b\": 40}, {\"id\": 3, \"b\": 45}, {\"id\": 4, \"b\": 110}]\n};" }, { "code": null, "e": 1438, "s": 1264, "text": "We are required to write a JavaScript function that takes in one such object. The function should merge part1 and part2 of the object to form an array of objects like this −" }, { "code": null, "e": 1569, "s": 1438, "text": "const output = [\n {\"id\": 1, \"a\": 50, \"b\": 40},\n {\"id\": 2, \"a\": 55},\n {\"id\": 3, \"b\": 45},\n {\"id\": 4, \"a\": 100, \"b\": 110}\n];" }, { "code": null, "e": 1597, "s": 1569, "text": "The code for this will be −" }, { "code": null, "e": 2335, "s": 1597, "text": "const obj = {\n \"part1\": [{\"id\": 1, \"a\": 50},{\"id\": 2, \"a\": 55},{\"id\": 4, \"a\": 100}],\n \"part2\":[{\"id\": 1, \"b\": 40}, {\"id\": 3, \"b\": 45}, {\"id\": 4, \"b\": 110}]\n};\nconst mergeObject = (obj = {}) => {\n let result = [];\n result = Object.keys(obj).reduce(function (hash) {\n return function (r, k) {\n obj[k].forEach(function (o) {\n if (!hash[o.id]) {\n hash[o.id] = {};\n r.push(hash[o.id]);\n }\n Object.keys(o).forEach(function (l) {\n hash[o.id][l] = o[l];\n });\n });\n return r;\n };\n }(Object.create(null)), []).sort((a, b) => {\n return a['id'] − b['id'];\n });\n return result;\n};\nconsole.log(mergeObject(obj));" }, { "code": null, "e": 2375, "s": 2335, "text": "And the output in the console will be −" }, { "code": null, "e": 2478, "s": 2375, "text": "[\n { id: 1, a: 50, b: 40 },\n { id: 2, a: 55 },\n { id: 3, b: 45 },\n { id: 4, a: 100, b: 110 }\n]" } ]
How to Create a Coin Flipping App using ReactJS? - GeeksforGeeks
07 Jul, 2021 Basically, we want to build an app to toss or flip the coin. each time coin is flipped randomly a side of a coin is shown from head and tail and also we want to keep track of how many times coins are flipped and how many times heads and tails appear from those. We create three components ‘App’ and ‘FlipCoin’ and ‘Coin’. The app component renders a single FlipCoin component only. There is no actual logic put inside the App component. FlipCoin component contains all the behind the logic. It has a default prop coin that is an array that contains two images head and tail (sides of a coin). It is a stateful component and has three states’ current faces, the total number of flips, and the number of heads. A click event handler is set to the button ‘flip’. The handler function basically chooses face head or tail randomly based on a randomly generated value and updates the current face state from the chosen face each time handler runs. The handler function also keeps track of how many times the flip button is clicked and how many times the head face generated randomly and updates its value to the respective state. The last Coin component is responsible for showing the correct coin face according to the randomly chosen side from the handler function in the FlipCoin component. FlipCoin uses a props system to communicate with the Coin component. Example: In this example, we will make a few changes on App.js, to import a component. In that component, we will include two sides of a coin of an image. And flip that as a single image. Filename- index.js: Javascript import React from 'react' import ReactDOM from 'react-dom' import App from './App' ReactDOM.render(<App />, document.querySelector('#root')) Filename- App.js: App component renders single FlipCoin component only Javascript import React from 'react'; import FlipCoin from './FlipCoin' const App=()=> { return ( <div className="App"> <FlipCoin /> </div> ); } export default App; Filename- FlipCoin.js: It contains all the behind logic. It is a stateful component. The states are currFace, totalFlips, and heads. It contains two sides of a coin as a default prop and updates the currFace state according to a random number that generates each time the component re-render. It is responsible for Setting event handler, updating all the states according to the user interaction render Coin component. Javascript import React,{ Component } from 'react' import Coin from './Coin' class FlipCoin extends Component{ static defaultProps = { coins : [ // Sides of the coin {side:'head', imgSrc: 'https://media.geeksforgeeks.org/wp-content/uploads/20200916123059/SHalfDollarObverse2016head-300x300.jpg'}, {side:'tail', imgSrc: 'https://media.geeksforgeeks.org/wp-content/uploads/20200916123125/tails-200x200.jpg'} ] } constructor(props){ super(props) // Responsible to render current updated coin face this.state = { // Track total number of flips currFace : null, totalFlips:0, heads: 0 } // Binding context of this keyword this.handleClick = this.handleClick.bind(this) } // Function takes array of different faces of a coin // and return a random chosen single face choice(arr){ const randomIdx = Math.floor(Math.random() * arr.length) return arr[randomIdx] } // Function responsible to update the states // according to users interactions flipCoin(){ const newFace = this.choice(this.props.coins) this.setState(curState => { const heads = curState.heads + (newFace.side === 'head' ? 1 : 0) return { currFace:newFace, totalFlips:curState.totalFlips + 1, heads:heads } }) } handleClick(){ this.flipCoin() } render(){ const {currFace, totalFlips, heads} = this.state return( <div> <h2>Let's flip a coin</h2> {/* If current face exist then show current face */} {currFace && <Coin info={currFace} />} {/* Button to flip the coin */} <button onClick={this.handleClick}>Flip Me!</button> <p> Out of {totalFlips} flips, there have been {heads} heads and {totalFlips - heads} tails </p> </div> ) } } export default FlipCoin Filename- Coin.js: Responsible to show a side of a coin according to the currFace state of FlipCoin component. FlipCoin component communicates with the Coin component through the props system Javascript import React,{ Component } from 'react' class Coin extends Component{ render(){ return( <div class='Coin'> <img style={{ width:'200px', height:'200px' }} src={this.props.info.imgSrc} /> </div> ) } } export default Coin Output : shubhamyadav4 varshagumber28 react-js Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Top 10 Front End Developer Skills That You Need in 2022 Installation of Node.js on Linux Top 10 Projects For Beginners To Practice HTML and CSS Skills How to fetch data from an API in ReactJS ? How to insert spaces/tabs in text using HTML/CSS? Difference between var, let and const keywords in JavaScript Convert a string to an integer in JavaScript How to set the default value for an HTML <select> element ? How to create footer to stay at the bottom of a Web page? How to calculate the number of days between two dates in javascript?
[ { "code": null, "e": 26829, "s": 26798, "text": " \n07 Jul, 2021\n" }, { "code": null, "e": 27091, "s": 26829, "text": "Basically, we want to build an app to toss or flip the coin. each time coin is flipped randomly a side of a coin is shown from head and tail and also we want to keep track of how many times coins are flipped and how many times heads and tails appear from those." }, { "code": null, "e": 28187, "s": 27091, "text": "We create three components ‘App’ and ‘FlipCoin’ and ‘Coin’. The app component renders a single FlipCoin component only. There is no actual logic put inside the App component. FlipCoin component contains all the behind the logic. It has a default prop coin that is an array that contains two images head and tail (sides of a coin). It is a stateful component and has three states’ current faces, the total number of flips, and the number of heads. A click event handler is set to the button ‘flip’. The handler function basically chooses face head or tail randomly based on a randomly generated value and updates the current face state from the chosen face each time handler runs. The handler function also keeps track of how many times the flip button is clicked and how many times the head face generated randomly and updates its value to the respective state. The last Coin component is responsible for showing the correct coin face according to the randomly chosen side from the handler function in the FlipCoin component. FlipCoin uses a props system to communicate with the Coin component. " }, { "code": null, "e": 28376, "s": 28187, "text": "Example: In this example, we will make a few changes on App.js, to import a component. In that component, we will include two sides of a coin of an image. And flip that as a single image." }, { "code": null, "e": 28396, "s": 28376, "text": "Filename- index.js:" }, { "code": null, "e": 28407, "s": 28396, "text": "Javascript" }, { "code": "\n\n\n\n\n\n\nimport React from 'react'\nimport ReactDOM from 'react-dom'\nimport App from './App'\n \nReactDOM.render(<App />, document.querySelector('#root'))\n\n\n\n\n\n", "e": 28573, "s": 28417, "text": null }, { "code": null, "e": 28645, "s": 28573, "text": "Filename- App.js: App component renders single FlipCoin component only " }, { "code": null, "e": 28656, "s": 28645, "text": "Javascript" }, { "code": "\n\n\n\n\n\n\nimport React from 'react';\nimport FlipCoin from './FlipCoin'\n \nconst App=()=> {\n return (\n <div className=\"App\">\n <FlipCoin />\n </div>\n );\n}\n \nexport default App;\n\n\n\n\n\n", "e": 28855, "s": 28666, "text": null }, { "code": null, "e": 29274, "s": 28855, "text": "Filename- FlipCoin.js: It contains all the behind logic. It is a stateful component. The states are currFace, totalFlips, and heads. It contains two sides of a coin as a default prop and updates the currFace state according to a random number that generates each time the component re-render. It is responsible for Setting event handler, updating all the states according to the user interaction render Coin component." }, { "code": null, "e": 29285, "s": 29274, "text": "Javascript" }, { "code": "\n\n\n\n\n\n\nimport React,{ Component } from 'react'\nimport Coin from './Coin'\n \nclass FlipCoin extends Component{\n static defaultProps = {\n coins : [\n \n // Sides of the coin\n {side:'head', imgSrc:\n'https://media.geeksforgeeks.org/wp-content/uploads/20200916123059/SHalfDollarObverse2016head-300x300.jpg'},\n {side:'tail', imgSrc:\n'https://media.geeksforgeeks.org/wp-content/uploads/20200916123125/tails-200x200.jpg'}\n ]\n }\n \n constructor(props){\n super(props)\n \n // Responsible to render current updated coin face\n this.state = {\n \n // Track total number of flips\n currFace : null,\n totalFlips:0,\n heads: 0\n }\n \n // Binding context of this keyword\n this.handleClick = this.handleClick.bind(this)\n }\n \n // Function takes array of different faces of a coin\n // and return a random chosen single face\n choice(arr){\n const randomIdx = Math.floor(Math.random() * arr.length)\n return arr[randomIdx]\n }\n \n // Function responsible to update the states\n // according to users interactions\n flipCoin(){\n const newFace = this.choice(this.props.coins)\n this.setState(curState => {\n const heads = curState.heads + \n (newFace.side === 'head' ? 1 : 0)\n return {\n currFace:newFace,\n totalFlips:curState.totalFlips + 1,\n heads:heads\n }\n })\n }\n \n handleClick(){\n this.flipCoin()\n }\n render(){\n const {currFace, totalFlips, heads} = this.state\n return(\n <div>\n <h2>Let's flip a coin</h2>\n \n {/* If current face exist then show current face */}\n {currFace && <Coin info={currFace} />}\n \n {/* Button to flip the coin */}\n <button onClick={this.handleClick}>Flip Me!</button>\n \n \n \n<p>\n Out of {totalFlips} flips, there have been {heads} heads \n and {totalFlips - heads} tails\n </p>\n \n \n \n </div>\n )\n }\n}\n \nexport default FlipCoin\n\n\n\n\n\n", "e": 31272, "s": 29295, "text": null }, { "code": null, "e": 31465, "s": 31272, "text": " Filename- Coin.js: Responsible to show a side of a coin according to the currFace state of FlipCoin component. FlipCoin component communicates with the Coin component through the props system" }, { "code": null, "e": 31476, "s": 31465, "text": "Javascript" }, { "code": "\n\n\n\n\n\n\nimport React,{ Component } from 'react'\n \nclass Coin extends Component{\n render(){\n return(\n <div class='Coin'>\n <img\n style={{ width:'200px', height:'200px' }}\n src={this.props.info.imgSrc} \n />\n </div>\n )\n }\n}\n \nexport default Coin\n\n\n\n\n\n", "e": 31783, "s": 31486, "text": null }, { "code": null, "e": 31794, "s": 31783, "text": " Output :" }, { "code": null, "e": 31808, "s": 31794, "text": "shubhamyadav4" }, { "code": null, "e": 31823, "s": 31808, "text": "varshagumber28" }, { "code": null, "e": 31834, "s": 31823, "text": "\nreact-js\n" }, { "code": null, "e": 31853, "s": 31834, "text": "\nWeb Technologies\n" }, { "code": null, "e": 32058, "s": 31853, "text": "Writing code in comment? \n Please use ide.geeksforgeeks.org, \n generate link and share the link here.\n " }, { "code": null, "e": 32114, "s": 32058, "text": "Top 10 Front End Developer Skills That You Need in 2022" }, { "code": null, "e": 32147, "s": 32114, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 32209, "s": 32147, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 32252, "s": 32209, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 32302, "s": 32252, "text": "How to insert spaces/tabs in text using HTML/CSS?" }, { "code": null, "e": 32363, "s": 32302, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 32408, "s": 32363, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 32468, "s": 32408, "text": "How to set the default value for an HTML <select> element ?" }, { "code": null, "e": 32526, "s": 32468, "text": "How to create footer to stay at the bottom of a Web page?" } ]
Tryit Editor v3.7
Tryit: Using align-self: center
[]
A non technical intro to NLP. While neural networks and CNNs have... | by Divyansh Rai | Towards Data Science
While neural networks and CNNs have made giant leaps in the field of computer vision, Natural language processing goes underappreciated. It is often overlooked because of not yet surpassing human level performance. Yet, as we’re going to see through this series we can make some pretty nifty tools that can help us not only gain insights but automate tasks. All the code mentioned is available here. You might’ve to copy some of the helper functions I’ve written from the github link. Mentioning it here would make everything too clustered. To start off, we’re going to do a basic analysis of the American president’s speeches right from the first president to the 2009 Obama speech. There are three libraries we’re going to use here1. nltk2. pyphen — To separate words into syllables 3. matplotlib — well, for plottingAll of these can be installed using pip install. You’ll need to download corpora. You can do that by executing the code given below nltk.download(‘inaugural’)nltk.download('stopwords') Or you can just execute nltk.download() and download “inaugral” and “stopwords” in the corpora section after the downloader pops up, as shown in the screen capture below. You can explore other corpus too this way. Now we import the nltk package and speeches with the following code(This might take a few seconds depending on your computer) import nltkfrom nltk.corpus import stopwords from nltk.corpus import inauguralfrom nltk.tokenize import word_tokenize, sent_tokenizeimport matplotlib.pyplot as pltimport pyphen As we’ve imported the inaugural speeches now, we can take a look at the data. We can see that we’ve got data of 56 presidents, from Washington to Obama in 2009. Let’s take a look at the speeches. To get the raw format of data, we can simply use inaugural.raw() . But as we can see, we can’t clearly divide it into words. Fortunately, we’ve got inaugural.words() to do the work for us. Now that we’ve got our speech broken down into words, we can start doing some basic analysis on it. We start by getting a frequency distribution. This will tell us how many times does a particular word comes up. Plus it’s already arranged in the decreasing order. We’ve run into a problem, it’s overwhelmed with the presence of stopwords. Often there are words and punctuation that are repeated more often than others and they don’t usually give us more information about the data. nltk already has a small list of words like this, and they are called stopwords. They are available for multiple languages. We add a few more symbols to the list of stop words imported. So now that we’ve a list of stop words, we write a small code to delete all the stop words from the speech and find out the frequency distribution again. That’s better and gives us a few insights about the data too. But this only gives us the data about one speech, we need something that’ll allow us to compare more president’s speeches together. So we start counting how many 2,3,4 letter words president xyz used. We then take the average letter count per word of each president and plot it. “I feel happy” — has an average letter count per word of 3.33 (1+4+5)/3. “I exude euphoria” — has an average letter count per word of 4.66(1+5+8)/3. A higher letter count per word would mean the president mostly used “big” words. We first count how many x letter words were used by each president. While we were doing that, we also stored the average letter count per word in a variable called presidents_avg . Using matplotlib to chart it, we can see that it has clearly decreased over time/presidents. Going on the similar path, we start counting how many words were spoken by president xyz in one sentence. We then take the average word count per sentence for each president and plot it. A higher average word count per sentence would mean the president mostly used “big” sentences. We also store the average word count per sentence in a variable called presidents_avg_words_per_sentence . Using matplotlib to chart it, we can see that it has clearly decreased over time/presidents. Now let’s see if analysis of hapaxes can get us anything. In corpus linguistics, a hapax legomenon is a word that occurs only once within a context/speech. words.hapaxes() gives us all the unique words in the corpus given. But counting no. of unique words is not enough. We need to also divide it byt he length of the total speech. Why? Because speech length varies a lot, so a larger speech may have more unique words and we need to remove that bias. So we find the unique words in one speech and count them up, average them and plot them for each president. It seems to be decreasing a little, though it’s not very apparent. For the final analysis we calculate the syllable per word used by each president in his speech, we use pyphen library for this as normally nouns like “Afghasnistan” have no predefined number of syllables. We then take the average syllable per word for each president and plot it. When we see the graph, we see that it has decreased over time. So comparatively speaking, presidents nowadays use smaller words and shorter sentences as compared to the earlier presidents. This can be due to many reasons, English language itself evolves a lot over a period of 200 years but it can also be due the advances in media. As the president’s speeches started to reach the common man who’d naturally prefer shorter sentences and smaller words, president’s speeches started to change according to the new audience. They were less about impressing few educated men in Washington, and more about getting votes from the common man.
[ { "code": null, "e": 529, "s": 171, "text": "While neural networks and CNNs have made giant leaps in the field of computer vision, Natural language processing goes underappreciated. It is often overlooked because of not yet surpassing human level performance. Yet, as we’re going to see through this series we can make some pretty nifty tools that can help us not only gain insights but automate tasks." }, { "code": null, "e": 712, "s": 529, "text": "All the code mentioned is available here. You might’ve to copy some of the helper functions I’ve written from the github link. Mentioning it here would make everything too clustered." }, { "code": null, "e": 1039, "s": 712, "text": "To start off, we’re going to do a basic analysis of the American president’s speeches right from the first president to the 2009 Obama speech. There are three libraries we’re going to use here1. nltk2. pyphen — To separate words into syllables 3. matplotlib — well, for plottingAll of these can be installed using pip install." }, { "code": null, "e": 1122, "s": 1039, "text": "You’ll need to download corpora. You can do that by executing the code given below" }, { "code": null, "e": 1175, "s": 1122, "text": "nltk.download(‘inaugural’)nltk.download('stopwords')" }, { "code": null, "e": 1389, "s": 1175, "text": "Or you can just execute nltk.download() and download “inaugral” and “stopwords” in the corpora section after the downloader pops up, as shown in the screen capture below. You can explore other corpus too this way." }, { "code": null, "e": 1515, "s": 1389, "text": "Now we import the nltk package and speeches with the following code(This might take a few seconds depending on your computer)" }, { "code": null, "e": 1692, "s": 1515, "text": "import nltkfrom nltk.corpus import stopwords from nltk.corpus import inauguralfrom nltk.tokenize import word_tokenize, sent_tokenizeimport matplotlib.pyplot as pltimport pyphen" }, { "code": null, "e": 1853, "s": 1692, "text": "As we’ve imported the inaugural speeches now, we can take a look at the data. We can see that we’ve got data of 56 presidents, from Washington to Obama in 2009." }, { "code": null, "e": 2077, "s": 1853, "text": "Let’s take a look at the speeches. To get the raw format of data, we can simply use inaugural.raw() . But as we can see, we can’t clearly divide it into words. Fortunately, we’ve got inaugural.words() to do the work for us." }, { "code": null, "e": 2341, "s": 2077, "text": "Now that we’ve got our speech broken down into words, we can start doing some basic analysis on it. We start by getting a frequency distribution. This will tell us how many times does a particular word comes up. Plus it’s already arranged in the decreasing order." }, { "code": null, "e": 2745, "s": 2341, "text": "We’ve run into a problem, it’s overwhelmed with the presence of stopwords. Often there are words and punctuation that are repeated more often than others and they don’t usually give us more information about the data. nltk already has a small list of words like this, and they are called stopwords. They are available for multiple languages. We add a few more symbols to the list of stop words imported." }, { "code": null, "e": 2899, "s": 2745, "text": "So now that we’ve a list of stop words, we write a small code to delete all the stop words from the speech and find out the frequency distribution again." }, { "code": null, "e": 3093, "s": 2899, "text": "That’s better and gives us a few insights about the data too. But this only gives us the data about one speech, we need something that’ll allow us to compare more president’s speeches together." }, { "code": null, "e": 3240, "s": 3093, "text": "So we start counting how many 2,3,4 letter words president xyz used. We then take the average letter count per word of each president and plot it." }, { "code": null, "e": 3313, "s": 3240, "text": "“I feel happy” — has an average letter count per word of 3.33 (1+4+5)/3." }, { "code": null, "e": 3389, "s": 3313, "text": "“I exude euphoria” — has an average letter count per word of 4.66(1+5+8)/3." }, { "code": null, "e": 3538, "s": 3389, "text": "A higher letter count per word would mean the president mostly used “big” words. We first count how many x letter words were used by each president." }, { "code": null, "e": 3744, "s": 3538, "text": "While we were doing that, we also stored the average letter count per word in a variable called presidents_avg . Using matplotlib to chart it, we can see that it has clearly decreased over time/presidents." }, { "code": null, "e": 3931, "s": 3744, "text": "Going on the similar path, we start counting how many words were spoken by president xyz in one sentence. We then take the average word count per sentence for each president and plot it." }, { "code": null, "e": 4226, "s": 3931, "text": "A higher average word count per sentence would mean the president mostly used “big” sentences. We also store the average word count per sentence in a variable called presidents_avg_words_per_sentence . Using matplotlib to chart it, we can see that it has clearly decreased over time/presidents." }, { "code": null, "e": 4449, "s": 4226, "text": "Now let’s see if analysis of hapaxes can get us anything. In corpus linguistics, a hapax legomenon is a word that occurs only once within a context/speech. words.hapaxes() gives us all the unique words in the corpus given." }, { "code": null, "e": 4786, "s": 4449, "text": "But counting no. of unique words is not enough. We need to also divide it byt he length of the total speech. Why? Because speech length varies a lot, so a larger speech may have more unique words and we need to remove that bias. So we find the unique words in one speech and count them up, average them and plot them for each president." }, { "code": null, "e": 4853, "s": 4786, "text": "It seems to be decreasing a little, though it’s not very apparent." }, { "code": null, "e": 5058, "s": 4853, "text": "For the final analysis we calculate the syllable per word used by each president in his speech, we use pyphen library for this as normally nouns like “Afghasnistan” have no predefined number of syllables." }, { "code": null, "e": 5133, "s": 5058, "text": "We then take the average syllable per word for each president and plot it." }, { "code": null, "e": 5196, "s": 5133, "text": "When we see the graph, we see that it has decreased over time." } ]
Sort an array without changing position of negative numbers - GeeksforGeeks
31 May, 2021 Given an array arr[] of N integers, the task is to sort the array without changing the position of negative numbers (if any) i.e. the negative numbers need not be sorted.Examples: Input: arr[] = {2, -6, -3, 8, 4, 1} Output: 1 -6 -3 2 4 8Input: arr[] = {-2, -6, -3, -8, 4, 1} Output: -2 -6 -3 -8 1 4 Approach: Store all the non-negative elements of the array in another vector and sort this vector. Now, replace all the non-negative values in the original array with these sorted values.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; // Function to sort the array such that// negative values do not get affectedvoid sortArray(int a[], int n){ // Store all non-negative values vector<int> ans; for (int i = 0; i < n; i++) { if (a[i] >= 0) ans.push_back(a[i]); } // Sort non-negative values sort(ans.begin(), ans.end()); int j = 0; for (int i = 0; i < n; i++) { // If current element is non-negative then // update it such that all the // non-negative values are sorted if (a[i] >= 0) { a[i] = ans[j]; j++; } } // Print the sorted array for (int i = 0; i < n; i++) cout << a[i] << " ";} // Driver codeint main(){ int arr[] = { 2, -6, -3, 8, 4, 1 }; int n = sizeof(arr) / sizeof(arr[0]); sortArray(arr, n); return 0;} // Java implementation of the approachimport java.util.*; class GFG{ // Function to sort the array such that// negative values do not get affectedstatic void sortArray(int a[], int n){ // Store all non-negative values Vector<Integer> ans = new Vector<>(); for (int i = 0; i < n; i++) { if (a[i] >= 0) ans.add(a[i]); } // Sort non-negative values Collections.sort(ans); int j = 0; for (int i = 0; i < n; i++) { // If current element is non-negative then // update it such that all the // non-negative values are sorted if (a[i] >= 0) { a[i] = ans.get(j); j++; } } // Print the sorted array for (int i = 0; i < n; i++) System.out.print(a[i] + " ");} // Driver codepublic static void main(String[] args){ int arr[] = { 2, -6, -3, 8, 4, 1 }; int n = arr.length; sortArray(arr, n);}} // This code is contributed by 29AjayKumar # Python3 implementation of the approach # Function to sort the array such that# negative values do not get affecteddef sortArray(a, n): # Store all non-negative values ans=[] for i in range(n): if (a[i] >= 0): ans.append(a[i]) # Sort non-negative values ans = sorted(ans) j = 0 for i in range(n): # If current element is non-negative then # update it such that all the # non-negative values are sorted if (a[i] >= 0): a[i] = ans[j] j += 1 # Print the sorted array for i in range(n): print(a[i],end = " ") # Driver code arr = [2, -6, -3, 8, 4, 1] n = len(arr) sortArray(arr, n) # This code is contributed by mohit kumar 29 // C# implementation of above approachusing System.Collections.Generic;using System; class GFG{ // Function to sort the array such that// negative values do not get affectedstatic void sortArray(int []a, int n){ // Store all non-negative values List<int> ans = new List<int>(); for (int i = 0; i < n; i++) { if (a[i] >= 0) ans.Add(a[i]); } // Sort non-negative values ans.Sort(); int j = 0; for (int i = 0; i < n; i++) { // If current element is non-negative then // update it such that all the // non-negative values are sorted if (a[i] >= 0) { a[i] = ans[j]; j++; } } // Print the sorted array for (int i = 0; i < n; i++) Console.Write(a[i] + " ");} // Driver codepublic static void Main(String[] args){ int []arr = { 2, -6, -3, 8, 4, 1 }; int n = arr.Length; sortArray(arr, n);}} // This code is contributed by 29AjayKumar <script> // JavaScript implementation of the approach // Function to sort the array such that// negative values do not get affectedfunction sortArray(a, n){ // Store all non-negative values var ans = []; for (var i = 0; i < n; i++) { if (a[i] >= 0) ans.push(a[i]); } // Sort non-negative values ans.sort((a,b)=> a-b); var j = 0; for (var i = 0; i < n; i++) { // If current element is non-negative then // update it such that all the // non-negative values are sorted if (a[i] >= 0) { a[i] = ans[j]; j++; } } // Print the sorted array for (var i = 0; i < n; i++) document.write( a[i] + " ");} // Driver codevar arr = [2, -6, -3, 8, 4, 1];var n = arr.length;sortArray(arr, n); </script> 1 -6 -3 2 4 8 Time Complexity: O(n * log n) Auxiliary Space: O(n) 29AjayKumar mohit kumar 29 Akanksha_Rai subhammahato348 itsok Arrays Competitive Programming Sorting Arrays Sorting Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Maximum and minimum of an array using minimum number of comparisons Top 50 Array Coding Problems for Interviews Stack Data Structure (Introduction and Program) Introduction to Arrays Multidimensional Arrays in Java Competitive Programming - A Complete Guide Practice for cracking any coding interview Arrow operator -> in C/C++ with Examples Prefix Sum Array - Implementation and Applications in Competitive Programming Fast I/O for Competitive Programming
[ { "code": null, "e": 26743, "s": 26715, "text": "\n31 May, 2021" }, { "code": null, "e": 26925, "s": 26743, "text": "Given an array arr[] of N integers, the task is to sort the array without changing the position of negative numbers (if any) i.e. the negative numbers need not be sorted.Examples: " }, { "code": null, "e": 27045, "s": 26925, "text": "Input: arr[] = {2, -6, -3, 8, 4, 1} Output: 1 -6 -3 2 4 8Input: arr[] = {-2, -6, -3, -8, 4, 1} Output: -2 -6 -3 -8 1 4 " }, { "code": null, "e": 27285, "s": 27045, "text": "Approach: Store all the non-negative elements of the array in another vector and sort this vector. Now, replace all the non-negative values in the original array with these sorted values.Below is the implementation of the above approach: " }, { "code": null, "e": 27289, "s": 27285, "text": "C++" }, { "code": null, "e": 27294, "s": 27289, "text": "Java" }, { "code": null, "e": 27302, "s": 27294, "text": "Python3" }, { "code": null, "e": 27305, "s": 27302, "text": "C#" }, { "code": null, "e": 27316, "s": 27305, "text": "Javascript" }, { "code": "// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Function to sort the array such that// negative values do not get affectedvoid sortArray(int a[], int n){ // Store all non-negative values vector<int> ans; for (int i = 0; i < n; i++) { if (a[i] >= 0) ans.push_back(a[i]); } // Sort non-negative values sort(ans.begin(), ans.end()); int j = 0; for (int i = 0; i < n; i++) { // If current element is non-negative then // update it such that all the // non-negative values are sorted if (a[i] >= 0) { a[i] = ans[j]; j++; } } // Print the sorted array for (int i = 0; i < n; i++) cout << a[i] << \" \";} // Driver codeint main(){ int arr[] = { 2, -6, -3, 8, 4, 1 }; int n = sizeof(arr) / sizeof(arr[0]); sortArray(arr, n); return 0;}", "e": 28214, "s": 27316, "text": null }, { "code": "// Java implementation of the approachimport java.util.*; class GFG{ // Function to sort the array such that// negative values do not get affectedstatic void sortArray(int a[], int n){ // Store all non-negative values Vector<Integer> ans = new Vector<>(); for (int i = 0; i < n; i++) { if (a[i] >= 0) ans.add(a[i]); } // Sort non-negative values Collections.sort(ans); int j = 0; for (int i = 0; i < n; i++) { // If current element is non-negative then // update it such that all the // non-negative values are sorted if (a[i] >= 0) { a[i] = ans.get(j); j++; } } // Print the sorted array for (int i = 0; i < n; i++) System.out.print(a[i] + \" \");} // Driver codepublic static void main(String[] args){ int arr[] = { 2, -6, -3, 8, 4, 1 }; int n = arr.length; sortArray(arr, n);}} // This code is contributed by 29AjayKumar", "e": 29180, "s": 28214, "text": null }, { "code": "# Python3 implementation of the approach # Function to sort the array such that# negative values do not get affecteddef sortArray(a, n): # Store all non-negative values ans=[] for i in range(n): if (a[i] >= 0): ans.append(a[i]) # Sort non-negative values ans = sorted(ans) j = 0 for i in range(n): # If current element is non-negative then # update it such that all the # non-negative values are sorted if (a[i] >= 0): a[i] = ans[j] j += 1 # Print the sorted array for i in range(n): print(a[i],end = \" \") # Driver code arr = [2, -6, -3, 8, 4, 1] n = len(arr) sortArray(arr, n) # This code is contributed by mohit kumar 29", "e": 29911, "s": 29180, "text": null }, { "code": "// C# implementation of above approachusing System.Collections.Generic;using System; class GFG{ // Function to sort the array such that// negative values do not get affectedstatic void sortArray(int []a, int n){ // Store all non-negative values List<int> ans = new List<int>(); for (int i = 0; i < n; i++) { if (a[i] >= 0) ans.Add(a[i]); } // Sort non-negative values ans.Sort(); int j = 0; for (int i = 0; i < n; i++) { // If current element is non-negative then // update it such that all the // non-negative values are sorted if (a[i] >= 0) { a[i] = ans[j]; j++; } } // Print the sorted array for (int i = 0; i < n; i++) Console.Write(a[i] + \" \");} // Driver codepublic static void Main(String[] args){ int []arr = { 2, -6, -3, 8, 4, 1 }; int n = arr.Length; sortArray(arr, n);}} // This code is contributed by 29AjayKumar", "e": 30881, "s": 29911, "text": null }, { "code": "<script> // JavaScript implementation of the approach // Function to sort the array such that// negative values do not get affectedfunction sortArray(a, n){ // Store all non-negative values var ans = []; for (var i = 0; i < n; i++) { if (a[i] >= 0) ans.push(a[i]); } // Sort non-negative values ans.sort((a,b)=> a-b); var j = 0; for (var i = 0; i < n; i++) { // If current element is non-negative then // update it such that all the // non-negative values are sorted if (a[i] >= 0) { a[i] = ans[j]; j++; } } // Print the sorted array for (var i = 0; i < n; i++) document.write( a[i] + \" \");} // Driver codevar arr = [2, -6, -3, 8, 4, 1];var n = arr.length;sortArray(arr, n); </script>", "e": 31687, "s": 30881, "text": null }, { "code": null, "e": 31701, "s": 31687, "text": "1 -6 -3 2 4 8" }, { "code": null, "e": 31733, "s": 31703, "text": "Time Complexity: O(n * log n)" }, { "code": null, "e": 31755, "s": 31733, "text": "Auxiliary Space: O(n)" }, { "code": null, "e": 31767, "s": 31755, "text": "29AjayKumar" }, { "code": null, "e": 31782, "s": 31767, "text": "mohit kumar 29" }, { "code": null, "e": 31795, "s": 31782, "text": "Akanksha_Rai" }, { "code": null, "e": 31811, "s": 31795, "text": "subhammahato348" }, { "code": null, "e": 31817, "s": 31811, "text": "itsok" }, { "code": null, "e": 31824, "s": 31817, "text": "Arrays" }, { "code": null, "e": 31848, "s": 31824, "text": "Competitive Programming" }, { "code": null, "e": 31856, "s": 31848, "text": "Sorting" }, { "code": null, "e": 31863, "s": 31856, "text": "Arrays" }, { "code": null, "e": 31871, "s": 31863, "text": "Sorting" }, { "code": null, "e": 31969, "s": 31871, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 32037, "s": 31969, "text": "Maximum and minimum of an array using minimum number of comparisons" }, { "code": null, "e": 32081, "s": 32037, "text": "Top 50 Array Coding Problems for Interviews" }, { "code": null, "e": 32129, "s": 32081, "text": "Stack Data Structure (Introduction and Program)" }, { "code": null, "e": 32152, "s": 32129, "text": "Introduction to Arrays" }, { "code": null, "e": 32184, "s": 32152, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 32227, "s": 32184, "text": "Competitive Programming - A Complete Guide" }, { "code": null, "e": 32270, "s": 32227, "text": "Practice for cracking any coding interview" }, { "code": null, "e": 32311, "s": 32270, "text": "Arrow operator -> in C/C++ with Examples" }, { "code": null, "e": 32389, "s": 32311, "text": "Prefix Sum Array - Implementation and Applications in Competitive Programming" } ]
PrimePy module in Python - GeeksforGeeks
05 Aug, 2021 A prime number is a natural number greater than 1 whose only factors are 1 and the number itself. 2 is the only even Prime number. We can represent any prime number with ‘6n+1’ or ‘6n-1’ (except 2 and 3) where n is a natural number. primePy is that library of Python which is used to compute operations related to prime numbers. It will perform all the functions in less time with the help of the functions of this primePy module. This module does not come built-in with Python. You need to install it externally. To install this module type the below command in the terminal. pip install primePy 1. primes.check(n): It will return True if ‘n’ is a prime number otherwise it will return False. Example: Python3 # Importing primes function# From primePy Libraryfrom primePy import primes print(primes.check(105))print(primes.check(71)) Output: False True 2. primes.factor(n): It will return the lowest prime factor of ‘n’. Example: Python3 # Importing primes function# From primePy Libraryfrom primePy import primes a = primes.factor(15)print(a) a = primes.factor(75689456252)print(a) Output: 3 2 3. primes.factors(n): It will return all the prime factors of ‘n’ with repetition of factors if exist. Example: Python3 # Importing primes function# From primePy Libraryfrom primePy import primes a = primes.factors(774177)print(a) a = primes.factors(15)print(a) Output: [3, 151, 1709] [3, 5] 4. primes.first(n) : It will return first ‘n’ prime numbers. Example: Python3 # Importing primes function# From primePy Libraryfrom primePy import primes a = primes.first(5)print(a) a = primes.first(10)print(a) Output: [2, 3, 5, 7, 11] [2, 3, 5, 7, 11, 13, 17, 19, 23, 29] 5. primes.upto(n): It will return all the prime numbers less than or equal to ‘n’. Example: Python3 # Importing primes function# From primePy Libraryfrom primePy import primes a = primes.upto(17)print(a) a = primes.upto(100)print(a) Output: [2, 3, 5, 7, 11, 13, 17] [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97] 6. primes.between(m, n): It will return all the prime numbers between m and n. Example: Python3 # Importing primes function# From primePy Libraryfrom primePy import primes a = primes.between(4, 15)print(a) a = primes.between(25, 75)print(a) Output: [5, 7, 11, 13] [29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73] 7. primes.phi(n): It will return the number of integers less than ‘n’ which have no common factor with n. Example: Python3 # Importing primes function# From primePy Libraryfrom primePy import primes a = primes.phi(5)print(a) a = primes.phi(10)print(a) Output: 4 4 simmytarika5 python-modules Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Check if element exists in list in Python How To Convert Python Dictionary To JSON? How to drop one or multiple columns in Pandas Dataframe Python Classes and Objects Python | Get unique values from a list Python | os.path.join() method Create a directory in Python Defaultdict in Python Python | Pandas dataframe.groupby()
[ { "code": null, "e": 25537, "s": 25509, "text": "\n05 Aug, 2021" }, { "code": null, "e": 25770, "s": 25537, "text": "A prime number is a natural number greater than 1 whose only factors are 1 and the number itself. 2 is the only even Prime number. We can represent any prime number with ‘6n+1’ or ‘6n-1’ (except 2 and 3) where n is a natural number." }, { "code": null, "e": 25969, "s": 25770, "text": "primePy is that library of Python which is used to compute operations related to prime numbers. It will perform all the functions in less time with the help of the functions of this primePy module. " }, { "code": null, "e": 26116, "s": 25969, "text": "This module does not come built-in with Python. You need to install it externally. To install this module type the below command in the terminal. " }, { "code": null, "e": 26139, "s": 26116, "text": " pip install primePy " }, { "code": null, "e": 26236, "s": 26139, "text": "1. primes.check(n): It will return True if ‘n’ is a prime number otherwise it will return False." }, { "code": null, "e": 26245, "s": 26236, "text": "Example:" }, { "code": null, "e": 26253, "s": 26245, "text": "Python3" }, { "code": "# Importing primes function# From primePy Libraryfrom primePy import primes print(primes.check(105))print(primes.check(71))", "e": 26378, "s": 26253, "text": null }, { "code": null, "e": 26387, "s": 26378, "text": "Output: " }, { "code": null, "e": 26398, "s": 26387, "text": "False\nTrue" }, { "code": null, "e": 26466, "s": 26398, "text": "2. primes.factor(n): It will return the lowest prime factor of ‘n’." }, { "code": null, "e": 26476, "s": 26466, "text": "Example: " }, { "code": null, "e": 26484, "s": 26476, "text": "Python3" }, { "code": "# Importing primes function# From primePy Libraryfrom primePy import primes a = primes.factor(15)print(a) a = primes.factor(75689456252)print(a)", "e": 26630, "s": 26484, "text": null }, { "code": null, "e": 26639, "s": 26630, "text": "Output: " }, { "code": null, "e": 26643, "s": 26639, "text": "3\n2" }, { "code": null, "e": 26746, "s": 26643, "text": "3. primes.factors(n): It will return all the prime factors of ‘n’ with repetition of factors if exist." }, { "code": null, "e": 26756, "s": 26746, "text": "Example: " }, { "code": null, "e": 26764, "s": 26756, "text": "Python3" }, { "code": "# Importing primes function# From primePy Libraryfrom primePy import primes a = primes.factors(774177)print(a) a = primes.factors(15)print(a)", "e": 26907, "s": 26764, "text": null }, { "code": null, "e": 26916, "s": 26907, "text": "Output: " }, { "code": null, "e": 26938, "s": 26916, "text": "[3, 151, 1709]\n[3, 5]" }, { "code": null, "e": 26999, "s": 26938, "text": "4. primes.first(n) : It will return first ‘n’ prime numbers." }, { "code": null, "e": 27009, "s": 26999, "text": "Example: " }, { "code": null, "e": 27017, "s": 27009, "text": "Python3" }, { "code": "# Importing primes function# From primePy Libraryfrom primePy import primes a = primes.first(5)print(a) a = primes.first(10)print(a)", "e": 27151, "s": 27017, "text": null }, { "code": null, "e": 27160, "s": 27151, "text": "Output: " }, { "code": null, "e": 27214, "s": 27160, "text": "[2, 3, 5, 7, 11]\n[2, 3, 5, 7, 11, 13, 17, 19, 23, 29]" }, { "code": null, "e": 27297, "s": 27214, "text": "5. primes.upto(n): It will return all the prime numbers less than or equal to ‘n’." }, { "code": null, "e": 27307, "s": 27297, "text": "Example: " }, { "code": null, "e": 27315, "s": 27307, "text": "Python3" }, { "code": "# Importing primes function# From primePy Libraryfrom primePy import primes a = primes.upto(17)print(a) a = primes.upto(100)print(a)", "e": 27449, "s": 27315, "text": null }, { "code": null, "e": 27457, "s": 27449, "text": "Output:" }, { "code": null, "e": 27581, "s": 27457, "text": "[2, 3, 5, 7, 11, 13, 17] [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97] " }, { "code": null, "e": 27660, "s": 27581, "text": "6. primes.between(m, n): It will return all the prime numbers between m and n." }, { "code": null, "e": 27670, "s": 27660, "text": "Example: " }, { "code": null, "e": 27678, "s": 27670, "text": "Python3" }, { "code": "# Importing primes function# From primePy Libraryfrom primePy import primes a = primes.between(4, 15)print(a) a = primes.between(25, 75)print(a)", "e": 27824, "s": 27678, "text": null }, { "code": null, "e": 27833, "s": 27824, "text": "Output: " }, { "code": null, "e": 27897, "s": 27833, "text": "[5, 7, 11, 13]\n[29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73]" }, { "code": null, "e": 28003, "s": 27897, "text": "7. primes.phi(n): It will return the number of integers less than ‘n’ which have no common factor with n." }, { "code": null, "e": 28013, "s": 28003, "text": "Example: " }, { "code": null, "e": 28021, "s": 28013, "text": "Python3" }, { "code": "# Importing primes function# From primePy Libraryfrom primePy import primes a = primes.phi(5)print(a) a = primes.phi(10)print(a)", "e": 28151, "s": 28021, "text": null }, { "code": null, "e": 28160, "s": 28151, "text": "Output: " }, { "code": null, "e": 28164, "s": 28160, "text": "4\n4" }, { "code": null, "e": 28179, "s": 28166, "text": "simmytarika5" }, { "code": null, "e": 28194, "s": 28179, "text": "python-modules" }, { "code": null, "e": 28201, "s": 28194, "text": "Python" }, { "code": null, "e": 28299, "s": 28201, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28331, "s": 28299, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 28373, "s": 28331, "text": "Check if element exists in list in Python" }, { "code": null, "e": 28415, "s": 28373, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 28471, "s": 28415, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 28498, "s": 28471, "text": "Python Classes and Objects" }, { "code": null, "e": 28537, "s": 28498, "text": "Python | Get unique values from a list" }, { "code": null, "e": 28568, "s": 28537, "text": "Python | os.path.join() method" }, { "code": null, "e": 28597, "s": 28568, "text": "Create a directory in Python" }, { "code": null, "e": 28619, "s": 28597, "text": "Defaultdict in Python" } ]
PHP - MYSQL Group By Clause - GeeksforGeeks
27 Dec, 2021 In this article, we are going to connect PHP code to the database to perform aggregate operations along with the GROUP BY Clause. Here, in this article, we are going to sum the college strength with respect to the department of the college and display it on the web page. Let’s discuss it one by one. Requirements – xampp server Overview : PHP – PHP stands for hyper text preprocessor. It is used to create dynamic web pages and can connect with the MySQL database by using the Xampp server. MySQL –MySQL is a query language that is used to manage databases. The GROUP BY statement is used to arrange the data into groups by using aggregate operations. PHP – PHP stands for hyper text preprocessor. It is used to create dynamic web pages and can connect with the MySQL database by using the Xampp server. MySQL –MySQL is a query language that is used to manage databases. The GROUP BY statement is used to arrange the data into groups by using aggregate operations. Note : In the SELECT statement query, the GROUP BY clause is used with the SELECT statement.In the query, the GROUP BY clause is placed after the WHERE clause.GROUP BY will come before and will be placed before the ORDER BY clause if used any. In the SELECT statement query, the GROUP BY clause is used with the SELECT statement. In the query, the GROUP BY clause is placed after the WHERE clause. GROUP BY will come before and will be placed before the ORDER BY clause if used any. Aggregate operations :Aggregate operations include sum(), min(), max(), count() etc. Syntax : SELECT column1,column2,.....columnn, function_name(columnn) FROM table_data WHERE condition GROUP BY column1, column2; Approach : Create a database in xampp. Create a table in a database Insert the records into it by using PHP code. PHP’s script to get desired data from a table using group by clause Steps to implement :Here, we will implement step by step to perform aggregate operations along with the GROUP BY Clause. Let’s have a look. Start the xampp server Create a database named sravan and create a table named college_data with 4 columns. Open notepad and write the code to insert the records, Save the file under xampp folder named data1.php PHP Code implementation :Code shows inserting college details in the college database. PHP <?php//servername$servername = "localhost";//username$username = "root";//empty password$password = "";//sravan is the database name$dbname = "sravan"; // Create connection by passing these connection parameters$conn = new mysqli($servername, $username, $password, $dbname);// Check this connectionif ($conn->connect_error) { die("Connection failed: " . $conn->connect_error);}//insert records into table$sql = "INSERT INTO college_data VALUES (1,'vignan','IT',120);";$sql .= "INSERT INTO college_data VALUES (1,'vignan','BT',190);";$sql .= "INSERT INTO college_data VALUES (1,'vignan','Mech',120);";$sql .= "INSERT INTO college_data VALUES (2,'vvit','IT',220);"; if ($conn->multi_query($sql) === TRUE) { echo "data stored successfully";} else { echo "Error: " . $sql . "<br>" . $conn->error;} $conn->close();?> Run the file in the browser by typing localhost/data1.php Output : Table data – Querying through PHP code :Now our table contains data. Write PHP code to find the sum of the strength of the department using group by clause. Save the file as form.php PHP <html><body><center><?php//servername$servername = "localhost";//username$username = "root";//empty password$password = "";//sravan is the database name$dbname = "sravan"; // Create connection by passing these connection parameters$conn = new mysqli($servername, $username, $password, $dbname); //sql query to find total strength with respect to the department$sql = "SELECT department, SUM(strength) FROM college_data GROUP BY department";$result = $conn->query($sql);//display data on web pagewhile($row = mysqli_fetch_array($result)){ echo "<h1>" ;echo "Total strength in ". $row['department']. " = ". $row['SUM(strength)'];echo "</h1>"; echo "<br />";} //close the connection $conn->close();?></center></body></html> Output : rajeev0719singh PHP-MySQL SQL SQL Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Update Multiple Columns in Single Update Statement in SQL? SQL | Subquery How to Create a Table With Multiple Foreign Keys in SQL? What is Temporary Table in SQL? SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter SQL Query to Convert VARCHAR to INT SQL using Python How to Write a SQL Query For a Specific Date Range and Date Time? How to Select Data Between Two Dates and Times in SQL Server? SQL Query to Compare Two Dates
[ { "code": null, "e": 25513, "s": 25485, "text": "\n27 Dec, 2021" }, { "code": null, "e": 25814, "s": 25513, "text": "In this article, we are going to connect PHP code to the database to perform aggregate operations along with the GROUP BY Clause. Here, in this article, we are going to sum the college strength with respect to the department of the college and display it on the web page. Let’s discuss it one by one." }, { "code": null, "e": 25842, "s": 25814, "text": "Requirements – xampp server" }, { "code": null, "e": 25853, "s": 25842, "text": "Overview :" }, { "code": null, "e": 26166, "s": 25853, "text": "PHP – PHP stands for hyper text preprocessor. It is used to create dynamic web pages and can connect with the MySQL database by using the Xampp server. MySQL –MySQL is a query language that is used to manage databases. The GROUP BY statement is used to arrange the data into groups by using aggregate operations." }, { "code": null, "e": 26319, "s": 26166, "text": "PHP – PHP stands for hyper text preprocessor. It is used to create dynamic web pages and can connect with the MySQL database by using the Xampp server. " }, { "code": null, "e": 26480, "s": 26319, "text": "MySQL –MySQL is a query language that is used to manage databases. The GROUP BY statement is used to arrange the data into groups by using aggregate operations." }, { "code": null, "e": 26487, "s": 26480, "text": "Note :" }, { "code": null, "e": 26724, "s": 26487, "text": "In the SELECT statement query, the GROUP BY clause is used with the SELECT statement.In the query, the GROUP BY clause is placed after the WHERE clause.GROUP BY will come before and will be placed before the ORDER BY clause if used any." }, { "code": null, "e": 26810, "s": 26724, "text": "In the SELECT statement query, the GROUP BY clause is used with the SELECT statement." }, { "code": null, "e": 26878, "s": 26810, "text": "In the query, the GROUP BY clause is placed after the WHERE clause." }, { "code": null, "e": 26963, "s": 26878, "text": "GROUP BY will come before and will be placed before the ORDER BY clause if used any." }, { "code": null, "e": 27048, "s": 26963, "text": "Aggregate operations :Aggregate operations include sum(), min(), max(), count() etc." }, { "code": null, "e": 27057, "s": 27048, "text": "Syntax :" }, { "code": null, "e": 27177, "s": 27057, "text": "SELECT column1,column2,.....columnn, function_name(columnn)\nFROM table_data \nWHERE condition\nGROUP BY column1, column2;" }, { "code": null, "e": 27188, "s": 27177, "text": "Approach :" }, { "code": null, "e": 27216, "s": 27188, "text": "Create a database in xampp." }, { "code": null, "e": 27245, "s": 27216, "text": "Create a table in a database" }, { "code": null, "e": 27291, "s": 27245, "text": "Insert the records into it by using PHP code." }, { "code": null, "e": 27359, "s": 27291, "text": "PHP’s script to get desired data from a table using group by clause" }, { "code": null, "e": 27499, "s": 27359, "text": "Steps to implement :Here, we will implement step by step to perform aggregate operations along with the GROUP BY Clause. Let’s have a look." }, { "code": null, "e": 27522, "s": 27499, "text": "Start the xampp server" }, { "code": null, "e": 27607, "s": 27522, "text": "Create a database named sravan and create a table named college_data with 4 columns." }, { "code": null, "e": 27662, "s": 27607, "text": "Open notepad and write the code to insert the records," }, { "code": null, "e": 27711, "s": 27662, "text": "Save the file under xampp folder named data1.php" }, { "code": null, "e": 27799, "s": 27711, "text": "PHP Code implementation :Code shows inserting college details in the college database. " }, { "code": null, "e": 27803, "s": 27799, "text": "PHP" }, { "code": "<?php//servername$servername = \"localhost\";//username$username = \"root\";//empty password$password = \"\";//sravan is the database name$dbname = \"sravan\"; // Create connection by passing these connection parameters$conn = new mysqli($servername, $username, $password, $dbname);// Check this connectionif ($conn->connect_error) { die(\"Connection failed: \" . $conn->connect_error);}//insert records into table$sql = \"INSERT INTO college_data VALUES (1,'vignan','IT',120);\";$sql .= \"INSERT INTO college_data VALUES (1,'vignan','BT',190);\";$sql .= \"INSERT INTO college_data VALUES (1,'vignan','Mech',120);\";$sql .= \"INSERT INTO college_data VALUES (2,'vvit','IT',220);\"; if ($conn->multi_query($sql) === TRUE) { echo \"data stored successfully\";} else { echo \"Error: \" . $sql . \"<br>\" . $conn->error;} $conn->close();?>", "e": 28619, "s": 27803, "text": null }, { "code": null, "e": 28677, "s": 28619, "text": "Run the file in the browser by typing localhost/data1.php" }, { "code": null, "e": 28686, "s": 28677, "text": "Output :" }, { "code": null, "e": 28699, "s": 28686, "text": "Table data –" }, { "code": null, "e": 28755, "s": 28699, "text": "Querying through PHP code :Now our table contains data." }, { "code": null, "e": 28843, "s": 28755, "text": "Write PHP code to find the sum of the strength of the department using group by clause." }, { "code": null, "e": 28869, "s": 28843, "text": "Save the file as form.php" }, { "code": null, "e": 28873, "s": 28869, "text": "PHP" }, { "code": "<html><body><center><?php//servername$servername = \"localhost\";//username$username = \"root\";//empty password$password = \"\";//sravan is the database name$dbname = \"sravan\"; // Create connection by passing these connection parameters$conn = new mysqli($servername, $username, $password, $dbname); //sql query to find total strength with respect to the department$sql = \"SELECT department, SUM(strength) FROM college_data GROUP BY department\";$result = $conn->query($sql);//display data on web pagewhile($row = mysqli_fetch_array($result)){ echo \"<h1>\" ;echo \"Total strength in \". $row['department']. \" = \". $row['SUM(strength)'];echo \"</h1>\"; echo \"<br />\";} //close the connection $conn->close();?></center></body></html>", "e": 29602, "s": 28873, "text": null }, { "code": null, "e": 29611, "s": 29602, "text": "Output :" }, { "code": null, "e": 29627, "s": 29611, "text": "rajeev0719singh" }, { "code": null, "e": 29637, "s": 29627, "text": "PHP-MySQL" }, { "code": null, "e": 29641, "s": 29637, "text": "SQL" }, { "code": null, "e": 29645, "s": 29641, "text": "SQL" }, { "code": null, "e": 29743, "s": 29645, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29809, "s": 29743, "text": "How to Update Multiple Columns in Single Update Statement in SQL?" }, { "code": null, "e": 29824, "s": 29809, "text": "SQL | Subquery" }, { "code": null, "e": 29881, "s": 29824, "text": "How to Create a Table With Multiple Foreign Keys in SQL?" }, { "code": null, "e": 29913, "s": 29881, "text": "What is Temporary Table in SQL?" }, { "code": null, "e": 29991, "s": 29913, "text": "SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter" }, { "code": null, "e": 30027, "s": 29991, "text": "SQL Query to Convert VARCHAR to INT" }, { "code": null, "e": 30044, "s": 30027, "text": "SQL using Python" }, { "code": null, "e": 30110, "s": 30044, "text": "How to Write a SQL Query For a Specific Date Range and Date Time?" }, { "code": null, "e": 30172, "s": 30110, "text": "How to Select Data Between Two Dates and Times in SQL Server?" } ]
Interquartile Range to Detect Outliers in Data - GeeksforGeeks
03 Jun, 2020 An observation which differs from an overall pattern on a sample dataset is called an outlier. Outliers:The outliers may suggest experimental errors, variability in a measurement, or an anomaly. The age of a person may wrongly be recorded as 200 rather than 20 Years. Such an outlier should definitely be discarded from the dataset.However, not all outliers are bad. Some outliers signify that data is significantly different from others. For example, it may indicate an anomaly like bank fraud or a rare disease. Significance of outliers: Outliers badly affect mean and standard deviation of the dataset. These may statistically give erroneous results. Most machine learning algorithms do not work well in the presence of outlier. So it is desirable to detect and remove outliers. Outliers are highly useful in anomaly detection like fraud detection where the fraud transactions are very different from normal transactions. What is Interquartile Range IQR? IQR is used to measure variability by dividing a data set into quartiles. The data is sorted in ascending order and split into 4 equal parts. Q1, Q2, Q3 called first, second and third quartiles are the values which separate the 4 equal parts. Q1 represents the 25th percentile of the data. Q2 represents the 50th percentile of the data. Q3 represents the 75th percentile of the data. If a dataset has 2n / 2n+1 data points, thenQ1 = median of the dataset.Q2 = median of n smallest data points.Q3 = median of n highest data points. IQR is the range between the first and the third quartiles namely Q1 and Q3: IQR = Q3 – Q1. The data points which fall below Q1 – 1.5 IQR or above Q3 + 1.5 IQR are outliers. Example:Assume the data 6, 2, 1, 5, 4, 3, 50. If these values represent the number of chapatis eaten in lunch, then 50 is clearly an outlier.Step by step way to detect outlier in this dataset using Python: Step 1: Import necessary libraries. import numpy as np import seaborn as sns Step 2: Take the data and sort it in ascending order. data = [6, 2, 3, 4, 5, 1, 50]sort_data = np.sort(data)sort_data Output: array([ 1, 2, 3, 4, 5, 6, 50]) Step 3: Calculate Q1, Q2, Q3 and IQR. Q1 = np.percentile(data, 25, interpolation = 'midpoint') Q2 = np.percentile(data, 50, interpolation = 'midpoint') Q3 = np.percentile(data, 75, interpolation = 'midpoint') print('Q1 25 percentile of the given data is, ', Q1)print('Q1 50 percentile of the given data is, ', Q2)print('Q1 75 percentile of the given data is, ', Q3) IQR = Q3 - Q1 print('Interquartile range is', IQR) Output: Q1 25 percentile of the given data is, 2.5 Q1 50 percentile of the given data is, 4.0 Q1 75 percentile of the given data is, 5.5 Interquartile range is 3.0 Step 4: Find the lower and upper limits as Q1 – 1.5 IQR and Q3 + 1.5 IQR, respectively. low_lim = Q1 - 1.5 * IQRup_lim = Q3 + 1.5 * IQRprint('low_limit is', low_lim)print('up_limit is', up_lim) Output: low_limit is -2.0 up_limit is 10.0 Step 5: Data points greater than the upper limit or less than the lower limit are outliers outlier =[]for x in data: if ((x> up_lim) or (x<low_lim)): outlier.append(x)print(' outlier in the dataset is', outlier) Output: outlier in the dataset is [50] Step 6: Plot the box plot to highlight outliers. sns.boxplot(data) Step 7: Following code can also be used to calculate IQR from scipy import statsIQR = stats.iqr(data, interpolation = 'midpoint')IQR Output: 3.0 Conclusion: IQR and box plot are effective techniques to detect outliers in data. Machine Learning Python Python Programs Machine Learning Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Introduction to Recurrent Neural Network Support Vector Machine Algorithm Intuition of Adam Optimizer CNN | Introduction to Pooling Layer Convolutional Neural Network (CNN) in Machine Learning Read JSON file using Python Adding new column to existing DataFrame in Pandas Python map() function How to get column names in Pandas dataframe
[ { "code": null, "e": 25613, "s": 25585, "text": "\n03 Jun, 2020" }, { "code": null, "e": 25708, "s": 25613, "text": "An observation which differs from an overall pattern on a sample dataset is called an outlier." }, { "code": null, "e": 26127, "s": 25708, "text": "Outliers:The outliers may suggest experimental errors, variability in a measurement, or an anomaly. The age of a person may wrongly be recorded as 200 rather than 20 Years. Such an outlier should definitely be discarded from the dataset.However, not all outliers are bad. Some outliers signify that data is significantly different from others. For example, it may indicate an anomaly like bank fraud or a rare disease." }, { "code": null, "e": 26153, "s": 26127, "text": "Significance of outliers:" }, { "code": null, "e": 26267, "s": 26153, "text": "Outliers badly affect mean and standard deviation of the dataset. These may statistically give erroneous results." }, { "code": null, "e": 26395, "s": 26267, "text": "Most machine learning algorithms do not work well in the presence of outlier. So it is desirable to detect and remove outliers." }, { "code": null, "e": 26538, "s": 26395, "text": "Outliers are highly useful in anomaly detection like fraud detection where the fraud transactions are very different from normal transactions." }, { "code": null, "e": 26571, "s": 26538, "text": "What is Interquartile Range IQR?" }, { "code": null, "e": 26814, "s": 26571, "text": "IQR is used to measure variability by dividing a data set into quartiles. The data is sorted in ascending order and split into 4 equal parts. Q1, Q2, Q3 called first, second and third quartiles are the values which separate the 4 equal parts." }, { "code": null, "e": 26861, "s": 26814, "text": "Q1 represents the 25th percentile of the data." }, { "code": null, "e": 26908, "s": 26861, "text": "Q2 represents the 50th percentile of the data." }, { "code": null, "e": 26955, "s": 26908, "text": "Q3 represents the 75th percentile of the data." }, { "code": null, "e": 27102, "s": 26955, "text": "If a dataset has 2n / 2n+1 data points, thenQ1 = median of the dataset.Q2 = median of n smallest data points.Q3 = median of n highest data points." }, { "code": null, "e": 27276, "s": 27102, "text": "IQR is the range between the first and the third quartiles namely Q1 and Q3: IQR = Q3 – Q1. The data points which fall below Q1 – 1.5 IQR or above Q3 + 1.5 IQR are outliers." }, { "code": null, "e": 27482, "s": 27276, "text": "Example:Assume the data 6, 2, 1, 5, 4, 3, 50. If these values represent the number of chapatis eaten in lunch, then 50 is clearly an outlier.Step by step way to detect outlier in this dataset using Python:" }, { "code": null, "e": 27518, "s": 27482, "text": "Step 1: Import necessary libraries." }, { "code": "import numpy as np import seaborn as sns", "e": 27559, "s": 27518, "text": null }, { "code": null, "e": 27613, "s": 27559, "text": "Step 2: Take the data and sort it in ascending order." }, { "code": "data = [6, 2, 3, 4, 5, 1, 50]sort_data = np.sort(data)sort_data", "e": 27677, "s": 27613, "text": null }, { "code": null, "e": 27685, "s": 27677, "text": "Output:" }, { "code": null, "e": 27721, "s": 27685, "text": "array([ 1, 2, 3, 4, 5, 6, 50])" }, { "code": null, "e": 27759, "s": 27721, "text": "Step 3: Calculate Q1, Q2, Q3 and IQR." }, { "code": "Q1 = np.percentile(data, 25, interpolation = 'midpoint') Q2 = np.percentile(data, 50, interpolation = 'midpoint') Q3 = np.percentile(data, 75, interpolation = 'midpoint') print('Q1 25 percentile of the given data is, ', Q1)print('Q1 50 percentile of the given data is, ', Q2)print('Q1 75 percentile of the given data is, ', Q3) IQR = Q3 - Q1 print('Interquartile range is', IQR)", "e": 28141, "s": 27759, "text": null }, { "code": null, "e": 28149, "s": 28141, "text": "Output:" }, { "code": null, "e": 28305, "s": 28149, "text": "Q1 25 percentile of the given data is, 2.5\nQ1 50 percentile of the given data is, 4.0\nQ1 75 percentile of the given data is, 5.5\nInterquartile range is 3.0" }, { "code": null, "e": 28393, "s": 28305, "text": "Step 4: Find the lower and upper limits as Q1 – 1.5 IQR and Q3 + 1.5 IQR, respectively." }, { "code": "low_lim = Q1 - 1.5 * IQRup_lim = Q3 + 1.5 * IQRprint('low_limit is', low_lim)print('up_limit is', up_lim)", "e": 28499, "s": 28393, "text": null }, { "code": null, "e": 28507, "s": 28499, "text": "Output:" }, { "code": null, "e": 28542, "s": 28507, "text": "low_limit is -2.0\nup_limit is 10.0" }, { "code": null, "e": 28633, "s": 28542, "text": "Step 5: Data points greater than the upper limit or less than the lower limit are outliers" }, { "code": "outlier =[]for x in data: if ((x> up_lim) or (x<low_lim)): outlier.append(x)print(' outlier in the dataset is', outlier)", "e": 28765, "s": 28633, "text": null }, { "code": null, "e": 28773, "s": 28765, "text": "Output:" }, { "code": null, "e": 28805, "s": 28773, "text": " outlier in the dataset is [50]" }, { "code": null, "e": 28854, "s": 28805, "text": "Step 6: Plot the box plot to highlight outliers." }, { "code": "sns.boxplot(data)", "e": 28872, "s": 28854, "text": null }, { "code": null, "e": 28929, "s": 28872, "text": "Step 7: Following code can also be used to calculate IQR" }, { "code": "from scipy import statsIQR = stats.iqr(data, interpolation = 'midpoint')IQR", "e": 29005, "s": 28929, "text": null }, { "code": null, "e": 29013, "s": 29005, "text": "Output:" }, { "code": null, "e": 29017, "s": 29013, "text": "3.0" }, { "code": null, "e": 29099, "s": 29017, "text": "Conclusion: IQR and box plot are effective techniques to detect outliers in data." }, { "code": null, "e": 29116, "s": 29099, "text": "Machine Learning" }, { "code": null, "e": 29123, "s": 29116, "text": "Python" }, { "code": null, "e": 29139, "s": 29123, "text": "Python Programs" }, { "code": null, "e": 29156, "s": 29139, "text": "Machine Learning" }, { "code": null, "e": 29254, "s": 29156, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29295, "s": 29254, "text": "Introduction to Recurrent Neural Network" }, { "code": null, "e": 29328, "s": 29295, "text": "Support Vector Machine Algorithm" }, { "code": null, "e": 29356, "s": 29328, "text": "Intuition of Adam Optimizer" }, { "code": null, "e": 29392, "s": 29356, "text": "CNN | Introduction to Pooling Layer" }, { "code": null, "e": 29447, "s": 29392, "text": "Convolutional Neural Network (CNN) in Machine Learning" }, { "code": null, "e": 29475, "s": 29447, "text": "Read JSON file using Python" }, { "code": null, "e": 29525, "s": 29475, "text": "Adding new column to existing DataFrame in Pandas" }, { "code": null, "e": 29547, "s": 29525, "text": "Python map() function" } ]
Sum of minimum and maximum elements of all subarrays of size k. - GeeksforGeeks
27 Feb, 2022 Given an array of both positive and negative integers, the task is to compute sum of minimum and maximum elements of all sub-array of size k.Examples: Input : arr[] = {2, 5, -1, 7, -3, -1, -2} K = 4 Output : 18 Explanation : Subarrays of size 4 are : {2, 5, -1, 7}, min + max = -1 + 7 = 6 {5, -1, 7, -3}, min + max = -3 + 7 = 4 {-1, 7, -3, -1}, min + max = -3 + 7 = 4 {7, -3, -1, -2}, min + max = -3 + 7 = 4 Sum of all min & max = 6 + 4 + 4 + 4 = 18 This problem is mainly an extension of below problem. Maximum of all subarrays of size k Method 1 (Simple) Run two loops to generate all subarrays of size k and find maximum and minimum values. Finally, return sum of all maximum and minimum elements. Time taken by this solution is O(n*k). Method 2 (Efficient using Dequeue) The idea is to use Dequeue data structure and sliding window concept. We create two empty double-ended queues of size k (‘S’ , ‘G’) that only store indices of elements of current window that are not useless. An element is useless if it can not be maximum or minimum of next subarrays. a) In deque 'G', we maintain decreasing order of values from front to rear b) In deque 'S', we maintain increasing order of values from front to rear 1) First window size K 1.1) For deque 'G', if current element is greater than rear end element, we remove rear while current is greater. 1.2) For deque 'S', if current element is smaller than rear end element, we just pop it while current is smaller. 1.3) insert current element in both deque 'G' 'S' 2) After step 1, front of 'G' contains maximum element of first window and front of 'S' contains minimum element of first window. Remaining elements of G and S may store maximum/minimum for subsequent windows. 3) After that we do traversal for rest array elements. 3.1) Front element of deque 'G' is greatest and 'S' is smallest element of previous window 3.2) Remove all elements which are out of this window [remove element at front of queue ] 3.3) Repeat steps 1.1 , 1.2 ,1.3 4) Return sum of minimum and maximum element of all sub-array size k. Below is implementation of above idea C++ Java Python C# Javascript // C++ program to find sum of all minimum and maximum// elements Of Sub-array Size k.#include<bits/stdc++.h>using namespace std; // Returns sum of min and max element of all subarrays// of size kint SumOfKsubArray(int arr[] , int n , int k){ int sum = 0; // Initialize result // The queue will store indexes of useful elements // in every window // In deque 'G' we maintain decreasing order of // values from front to rear // In deque 'S' we maintain increasing order of // values from front to rear deque< int > S(k), G(k); // Process first window of size K int i = 0; for (i = 0; i < k; i++) { // Remove all previous greater elements // that are useless. while ( (!S.empty()) && arr[S.back()] >= arr[i]) S.pop_back(); // Remove from rear // Remove all previous smaller that are elements // are useless. while ( (!G.empty()) && arr[G.back()] <= arr[i]) G.pop_back(); // Remove from rear // Add current element at rear of both deque G.push_back(i); S.push_back(i); } // Process rest of the Array elements for ( ; i < n; i++ ) { // Element at the front of the deque 'G' & 'S' // is the largest and smallest // element of previous window respectively sum += arr[S.front()] + arr[G.front()]; // Remove all elements which are out of this // window while ( !S.empty() && S.front() <= i - k) S.pop_front(); while ( !G.empty() && G.front() <= i - k) G.pop_front(); // remove all previous greater element that are // useless while ( (!S.empty()) && arr[S.back()] >= arr[i]) S.pop_back(); // Remove from rear // remove all previous smaller that are elements // are useless while ( (!G.empty()) && arr[G.back()] <= arr[i]) G.pop_back(); // Remove from rear // Add current element at rear of both deque G.push_back(i); S.push_back(i); } // Sum of minimum and maximum element of last window sum += arr[S.front()] + arr[G.front()]; return sum;} // Driver program to test above functionsint main(){ int arr[] = {2, 5, -1, 7, -3, -1, -2} ; int n = sizeof(arr)/sizeof(arr[0]); int k = 3; cout << SumOfKsubArray(arr, n, k) ; return 0;} // Java program to find sum of all minimum and maximum// elements Of Sub-array Size k.import java.util.Deque;import java.util.LinkedList;public class Geeks { // Returns sum of min and max element of all subarrays // of size k public static int SumOfKsubArray(int arr[] , int k) { int sum = 0; // Initialize result // The queue will store indexes of useful elements // in every window // In deque 'G' we maintain decreasing order of // values from front to rear // In deque 'S' we maintain increasing order of // values from front to rear Deque<Integer> S=new LinkedList<>(),G=new LinkedList<>(); // Process first window of size K int i = 0; for (i = 0; i < k; i++) { // Remove all previous greater elements // that are useless. while ( !S.isEmpty() && arr[S.peekLast()] >= arr[i]) S.removeLast(); // Remove from rear // Remove all previous smaller that are elements // are useless. while ( !G.isEmpty() && arr[G.peekLast()] <= arr[i]) G.removeLast(); // Remove from rear // Add current element at rear of both deque G.addLast(i); S.addLast(i); } // Process rest of the Array elements for ( ; i < arr.length; i++ ) { // Element at the front of the deque 'G' & 'S' // is the largest and smallest // element of previous window respectively sum += arr[S.peekFirst()] + arr[G.peekFirst()]; // Remove all elements which are out of this // window while ( !S.isEmpty() && S.peekFirst() <= i - k) S.removeFirst(); while ( !G.isEmpty() && G.peekFirst() <= i - k) G.removeFirst(); // remove all previous greater element that are // useless while ( !S.isEmpty() && arr[S.peekLast()] >= arr[i]) S.removeLast(); // Remove from rear // remove all previous smaller that are elements // are useless while ( !G.isEmpty() && arr[G.peekLast()] <= arr[i]) G.removeLast(); // Remove from rear // Add current element at rear of both deque G.addLast(i); S.addLast(i); } // Sum of minimum and maximum element of last window sum += arr[S.peekFirst()] + arr[G.peekFirst()]; return sum; } public static void main(String args[]) { int arr[] = {2, 5, -1, 7, -3, -1, -2} ; int k = 3; System.out.println(SumOfKsubArray(arr, k)); }}//This code is contributed by Gaurav Tiwari # Python3 program to find Sum of all minimum and maximum# elements Of Sub-array Size k.from collections import deque # Returns Sum of min and max element of all subarrays# of size kdef SumOfKsubArray(arr, n , k): Sum = 0 # Initialize result # The queue will store indexes of useful elements # in every window # In deque 'G' we maintain decreasing order of # values from front to rear # In deque 'S' we maintain increasing order of # values from front to rear S = deque() G = deque() # Process first window of size K for i in range(k): # Remove all previous greater elements # that are useless. while ( len(S) > 0 and arr[S[-1]] >= arr[i]): S.pop() # Remove from rear # Remove all previous smaller that are elements # are useless. while ( len(G) > 0 and arr[G[-1]] <= arr[i]): G.pop() # Remove from rear # Add current element at rear of both deque G.append(i) S.append(i) # Process rest of the Array elements for i in range(k, n): # Element at the front of the deque 'G' & 'S' # is the largest and smallest # element of previous window respectively Sum += arr[S[0]] + arr[G[0]] # Remove all elements which are out of this # window while ( len(S) > 0 and S[0] <= i - k): S.popleft() while ( len(G) > 0 and G[0] <= i - k): G.popleft() # remove all previous greater element that are # useless while ( len(S) > 0 and arr[S[-1]] >= arr[i]): S.pop() # Remove from rear # remove all previous smaller that are elements # are useless while ( len(G) > 0 and arr[G[-1]] <= arr[i]): G.pop() # Remove from rear # Add current element at rear of both deque G.append(i) S.append(i) # Sum of minimum and maximum element of last window Sum += arr[S[0]] + arr[G[0]] return Sum # Driver program to test above functionsarr=[2, 5, -1, 7, -3, -1, -2]n = len(arr)k = 3print(SumOfKsubArray(arr, n, k)) # This code is contributed by mohit kumar // C# program to find sum of all minimum and maximum// elements Of Sub-array Size k.using System;using System.Collections.Generic;class Geeks{ // Returns sum of min and max element of all subarrays // of size k public static int SumOfKsubArray(int []arr , int k) { int sum = 0; // Initialize result // The queue will store indexes of useful elements // in every window // In deque 'G' we maintain decreasing order of // values from front to rear // In deque 'S' we maintain increasing order of // values from front to rear List<int> S = new List<int>(); List<int> G = new List<int>(); // Process first window of size K int i = 0; for (i = 0; i < k; i++) { // Remove all previous greater elements // that are useless. while ( S.Count != 0 && arr[S[S.Count - 1]] >= arr[i]) S.RemoveAt(S.Count - 1); // Remove from rear // Remove all previous smaller that are elements // are useless. while ( G.Count != 0 && arr[G[G.Count - 1]] <= arr[i]) G.RemoveAt(G.Count - 1); // Remove from rear // Add current element at rear of both deque G.Add(i); S.Add(i); } // Process rest of the Array elements for ( ; i < arr.Length; i++ ) { // Element at the front of the deque 'G' & 'S' // is the largest and smallest // element of previous window respectively sum += arr[S[0]] + arr[G[0]]; // Remove all elements which are out of this // window while ( S.Count != 0 && S[0] <= i - k) S.RemoveAt(0); while ( G.Count != 0 && G[0] <= i - k) G.RemoveAt(0); // remove all previous greater element that are // useless while ( S.Count != 0 && arr[S[S.Count-1]] >= arr[i]) S.RemoveAt(S.Count - 1 ); // Remove from rear // remove all previous smaller that are elements // are useless while ( G.Count != 0 && arr[G[G.Count - 1]] <= arr[i]) G.RemoveAt(G.Count - 1); // Remove from rear // Add current element at rear of both deque G.Add(i); S.Add(i); } // Sum of minimum and maximum element of last window sum += arr[S[0]] + arr[G[0]]; return sum; } // Driver code public static void Main(String []args) { int []arr = {2, 5, -1, 7, -3, -1, -2} ; int k = 3; Console.WriteLine(SumOfKsubArray(arr, k)); }} // This code is contributed by gauravrajput1 <script> // JavaScript program to find sum of all minimum and maximum// elements Of Sub-array Size k. // Returns sum of min and max element of all subarrays// of size kfunction SumOfKsubArray(arr , k){ let sum = 0; // Initialize result // The queue will store indexes of useful elements // in every window // In deque 'G' we maintain decreasing order of // values from front to rear // In deque 'S' we maintain increasing order of // values from front to rear let S = []; let G = []; // Process first window of size K let i = 0; for (i = 0; i < k; i++) { // Remove all previous greater elements // that are useless. while ( S.length != 0 && arr[S[S.length - 1]] >= arr[i]) S.pop(); // Remove from rear // Remove all previous smaller that are elements // are useless. while ( G.length != 0 && arr[G[G.length - 1]] <= arr[i]) G.pop(); // Remove from rear // Add current element at rear of both deque G.push(i); S.push(i); } // Process rest of the Array elements for ( ; i < arr.length; i++ ) { // Element at the front of the deque 'G' & 'S' // is the largest and smallest // element of previous window respectively sum += arr[S[0]] + arr[G[0]]; // Remove all elements which are out of this // window while ( S.length != 0 && S[0] <= i - k) S.shift(0); while ( G.length != 0 && G[0] <= i - k) G.shift(0); // remove all previous greater element that are // useless while ( S.length != 0 && arr[S[S.length-1]] >= arr[i]) S.pop(); // Remove from rear // remove all previous smaller that are elements // are useless while ( G.length != 0 && arr[G[G.length - 1]] <= arr[i]) G.pop(); // Remove from rear // Add current element at rear of both deque G.push(i); S.push(i); } // Sum of minimum and maximum element of last window sum += arr[S[0]] + arr[G[0]]; return sum;} // Driver code let arr = [2, 5, -1, 7, -3, -1, -2]; let k = 3; document.write(SumOfKsubArray(arr, k)); // This code is contributed by _saurabh_jaiswal </script> Output: 14 Time Complexity: O(n) Auxiliary Space: O(k) This article is contributed by Nishant_Singh (Pintu). If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. _Gaurav_Tiwari mohit kumar 29 GauravRajput1 _saurabh_jaiswal prophet1999 sliding-window subarray Arrays Queue sliding-window Arrays Queue 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 Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum) Python | Using 2D arrays/lists the right way Breadth First Search or BFS for a Graph Level Order Binary Tree Traversal Queue Interface In Java Queue in Python Queue | Set 1 (Introduction and Array Implementation)
[ { "code": null, "e": 26333, "s": 26305, "text": "\n27 Feb, 2022" }, { "code": null, "e": 26486, "s": 26333, "text": "Given an array of both positive and negative integers, the task is to compute sum of minimum and maximum elements of all sub-array of size k.Examples: " }, { "code": null, "e": 26875, "s": 26486, "text": "Input : arr[] = {2, 5, -1, 7, -3, -1, -2} \n K = 4\nOutput : 18\nExplanation : Subarrays of size 4 are : \n {2, 5, -1, 7}, min + max = -1 + 7 = 6\n {5, -1, 7, -3}, min + max = -3 + 7 = 4 \n {-1, 7, -3, -1}, min + max = -3 + 7 = 4\n {7, -3, -1, -2}, min + max = -3 + 7 = 4 \n Sum of all min & max = 6 + 4 + 4 + 4 \n = 18 " }, { "code": null, "e": 27167, "s": 26877, "text": "This problem is mainly an extension of below problem. Maximum of all subarrays of size k Method 1 (Simple) Run two loops to generate all subarrays of size k and find maximum and minimum values. Finally, return sum of all maximum and minimum elements. Time taken by this solution is O(n*k)." }, { "code": null, "e": 27489, "s": 27167, "text": "Method 2 (Efficient using Dequeue) The idea is to use Dequeue data structure and sliding window concept. We create two empty double-ended queues of size k (‘S’ , ‘G’) that only store indices of elements of current window that are not useless. An element is useless if it can not be maximum or minimum of next subarrays. " }, { "code": null, "e": 28585, "s": 27489, "text": " a) In deque 'G', we maintain decreasing order of \n values from front to rear\n b) In deque 'S', we maintain increasing order of \n values from front to rear\n\n1) First window size K\n 1.1) For deque 'G', if current element is greater \n than rear end element, we remove rear while \n current is greater.\n 1.2) For deque 'S', if current element is smaller \n than rear end element, we just pop it while \n current is smaller.\n 1.3) insert current element in both deque 'G' 'S'\n\n2) After step 1, front of 'G' contains maximum element\n of first window and front of 'S' contains minimum \n element of first window. Remaining elements of G\n and S may store maximum/minimum for subsequent \n windows.\n\n3) After that we do traversal for rest array elements.\n 3.1) Front element of deque 'G' is greatest and 'S' \n is smallest element of previous window \n 3.2) Remove all elements which are out of this \n window [remove element at front of queue ]\n 3.3) Repeat steps 1.1 , 1.2 ,1.3 \n\n4) Return sum of minimum and maximum element of all \n sub-array size k." }, { "code": null, "e": 28625, "s": 28585, "text": "Below is implementation of above idea " }, { "code": null, "e": 28629, "s": 28625, "text": "C++" }, { "code": null, "e": 28634, "s": 28629, "text": "Java" }, { "code": null, "e": 28641, "s": 28634, "text": "Python" }, { "code": null, "e": 28644, "s": 28641, "text": "C#" }, { "code": null, "e": 28655, "s": 28644, "text": "Javascript" }, { "code": "// C++ program to find sum of all minimum and maximum// elements Of Sub-array Size k.#include<bits/stdc++.h>using namespace std; // Returns sum of min and max element of all subarrays// of size kint SumOfKsubArray(int arr[] , int n , int k){ int sum = 0; // Initialize result // The queue will store indexes of useful elements // in every window // In deque 'G' we maintain decreasing order of // values from front to rear // In deque 'S' we maintain increasing order of // values from front to rear deque< int > S(k), G(k); // Process first window of size K int i = 0; for (i = 0; i < k; i++) { // Remove all previous greater elements // that are useless. while ( (!S.empty()) && arr[S.back()] >= arr[i]) S.pop_back(); // Remove from rear // Remove all previous smaller that are elements // are useless. while ( (!G.empty()) && arr[G.back()] <= arr[i]) G.pop_back(); // Remove from rear // Add current element at rear of both deque G.push_back(i); S.push_back(i); } // Process rest of the Array elements for ( ; i < n; i++ ) { // Element at the front of the deque 'G' & 'S' // is the largest and smallest // element of previous window respectively sum += arr[S.front()] + arr[G.front()]; // Remove all elements which are out of this // window while ( !S.empty() && S.front() <= i - k) S.pop_front(); while ( !G.empty() && G.front() <= i - k) G.pop_front(); // remove all previous greater element that are // useless while ( (!S.empty()) && arr[S.back()] >= arr[i]) S.pop_back(); // Remove from rear // remove all previous smaller that are elements // are useless while ( (!G.empty()) && arr[G.back()] <= arr[i]) G.pop_back(); // Remove from rear // Add current element at rear of both deque G.push_back(i); S.push_back(i); } // Sum of minimum and maximum element of last window sum += arr[S.front()] + arr[G.front()]; return sum;} // Driver program to test above functionsint main(){ int arr[] = {2, 5, -1, 7, -3, -1, -2} ; int n = sizeof(arr)/sizeof(arr[0]); int k = 3; cout << SumOfKsubArray(arr, n, k) ; return 0;}", "e": 31011, "s": 28655, "text": null }, { "code": "// Java program to find sum of all minimum and maximum// elements Of Sub-array Size k.import java.util.Deque;import java.util.LinkedList;public class Geeks { // Returns sum of min and max element of all subarrays // of size k public static int SumOfKsubArray(int arr[] , int k) { int sum = 0; // Initialize result // The queue will store indexes of useful elements // in every window // In deque 'G' we maintain decreasing order of // values from front to rear // In deque 'S' we maintain increasing order of // values from front to rear Deque<Integer> S=new LinkedList<>(),G=new LinkedList<>(); // Process first window of size K int i = 0; for (i = 0; i < k; i++) { // Remove all previous greater elements // that are useless. while ( !S.isEmpty() && arr[S.peekLast()] >= arr[i]) S.removeLast(); // Remove from rear // Remove all previous smaller that are elements // are useless. while ( !G.isEmpty() && arr[G.peekLast()] <= arr[i]) G.removeLast(); // Remove from rear // Add current element at rear of both deque G.addLast(i); S.addLast(i); } // Process rest of the Array elements for ( ; i < arr.length; i++ ) { // Element at the front of the deque 'G' & 'S' // is the largest and smallest // element of previous window respectively sum += arr[S.peekFirst()] + arr[G.peekFirst()]; // Remove all elements which are out of this // window while ( !S.isEmpty() && S.peekFirst() <= i - k) S.removeFirst(); while ( !G.isEmpty() && G.peekFirst() <= i - k) G.removeFirst(); // remove all previous greater element that are // useless while ( !S.isEmpty() && arr[S.peekLast()] >= arr[i]) S.removeLast(); // Remove from rear // remove all previous smaller that are elements // are useless while ( !G.isEmpty() && arr[G.peekLast()] <= arr[i]) G.removeLast(); // Remove from rear // Add current element at rear of both deque G.addLast(i); S.addLast(i); } // Sum of minimum and maximum element of last window sum += arr[S.peekFirst()] + arr[G.peekFirst()]; return sum; } public static void main(String args[]) { int arr[] = {2, 5, -1, 7, -3, -1, -2} ; int k = 3; System.out.println(SumOfKsubArray(arr, k)); }}//This code is contributed by Gaurav Tiwari", "e": 33751, "s": 31011, "text": null }, { "code": "# Python3 program to find Sum of all minimum and maximum# elements Of Sub-array Size k.from collections import deque # Returns Sum of min and max element of all subarrays# of size kdef SumOfKsubArray(arr, n , k): Sum = 0 # Initialize result # The queue will store indexes of useful elements # in every window # In deque 'G' we maintain decreasing order of # values from front to rear # In deque 'S' we maintain increasing order of # values from front to rear S = deque() G = deque() # Process first window of size K for i in range(k): # Remove all previous greater elements # that are useless. while ( len(S) > 0 and arr[S[-1]] >= arr[i]): S.pop() # Remove from rear # Remove all previous smaller that are elements # are useless. while ( len(G) > 0 and arr[G[-1]] <= arr[i]): G.pop() # Remove from rear # Add current element at rear of both deque G.append(i) S.append(i) # Process rest of the Array elements for i in range(k, n): # Element at the front of the deque 'G' & 'S' # is the largest and smallest # element of previous window respectively Sum += arr[S[0]] + arr[G[0]] # Remove all elements which are out of this # window while ( len(S) > 0 and S[0] <= i - k): S.popleft() while ( len(G) > 0 and G[0] <= i - k): G.popleft() # remove all previous greater element that are # useless while ( len(S) > 0 and arr[S[-1]] >= arr[i]): S.pop() # Remove from rear # remove all previous smaller that are elements # are useless while ( len(G) > 0 and arr[G[-1]] <= arr[i]): G.pop() # Remove from rear # Add current element at rear of both deque G.append(i) S.append(i) # Sum of minimum and maximum element of last window Sum += arr[S[0]] + arr[G[0]] return Sum # Driver program to test above functionsarr=[2, 5, -1, 7, -3, -1, -2]n = len(arr)k = 3print(SumOfKsubArray(arr, n, k)) # This code is contributed by mohit kumar", "e": 35897, "s": 33751, "text": null }, { "code": "// C# program to find sum of all minimum and maximum// elements Of Sub-array Size k.using System;using System.Collections.Generic;class Geeks{ // Returns sum of min and max element of all subarrays // of size k public static int SumOfKsubArray(int []arr , int k) { int sum = 0; // Initialize result // The queue will store indexes of useful elements // in every window // In deque 'G' we maintain decreasing order of // values from front to rear // In deque 'S' we maintain increasing order of // values from front to rear List<int> S = new List<int>(); List<int> G = new List<int>(); // Process first window of size K int i = 0; for (i = 0; i < k; i++) { // Remove all previous greater elements // that are useless. while ( S.Count != 0 && arr[S[S.Count - 1]] >= arr[i]) S.RemoveAt(S.Count - 1); // Remove from rear // Remove all previous smaller that are elements // are useless. while ( G.Count != 0 && arr[G[G.Count - 1]] <= arr[i]) G.RemoveAt(G.Count - 1); // Remove from rear // Add current element at rear of both deque G.Add(i); S.Add(i); } // Process rest of the Array elements for ( ; i < arr.Length; i++ ) { // Element at the front of the deque 'G' & 'S' // is the largest and smallest // element of previous window respectively sum += arr[S[0]] + arr[G[0]]; // Remove all elements which are out of this // window while ( S.Count != 0 && S[0] <= i - k) S.RemoveAt(0); while ( G.Count != 0 && G[0] <= i - k) G.RemoveAt(0); // remove all previous greater element that are // useless while ( S.Count != 0 && arr[S[S.Count-1]] >= arr[i]) S.RemoveAt(S.Count - 1 ); // Remove from rear // remove all previous smaller that are elements // are useless while ( G.Count != 0 && arr[G[G.Count - 1]] <= arr[i]) G.RemoveAt(G.Count - 1); // Remove from rear // Add current element at rear of both deque G.Add(i); S.Add(i); } // Sum of minimum and maximum element of last window sum += arr[S[0]] + arr[G[0]]; return sum; } // Driver code public static void Main(String []args) { int []arr = {2, 5, -1, 7, -3, -1, -2} ; int k = 3; Console.WriteLine(SumOfKsubArray(arr, k)); }} // This code is contributed by gauravrajput1", "e": 38286, "s": 35897, "text": null }, { "code": "<script> // JavaScript program to find sum of all minimum and maximum// elements Of Sub-array Size k. // Returns sum of min and max element of all subarrays// of size kfunction SumOfKsubArray(arr , k){ let sum = 0; // Initialize result // The queue will store indexes of useful elements // in every window // In deque 'G' we maintain decreasing order of // values from front to rear // In deque 'S' we maintain increasing order of // values from front to rear let S = []; let G = []; // Process first window of size K let i = 0; for (i = 0; i < k; i++) { // Remove all previous greater elements // that are useless. while ( S.length != 0 && arr[S[S.length - 1]] >= arr[i]) S.pop(); // Remove from rear // Remove all previous smaller that are elements // are useless. while ( G.length != 0 && arr[G[G.length - 1]] <= arr[i]) G.pop(); // Remove from rear // Add current element at rear of both deque G.push(i); S.push(i); } // Process rest of the Array elements for ( ; i < arr.length; i++ ) { // Element at the front of the deque 'G' & 'S' // is the largest and smallest // element of previous window respectively sum += arr[S[0]] + arr[G[0]]; // Remove all elements which are out of this // window while ( S.length != 0 && S[0] <= i - k) S.shift(0); while ( G.length != 0 && G[0] <= i - k) G.shift(0); // remove all previous greater element that are // useless while ( S.length != 0 && arr[S[S.length-1]] >= arr[i]) S.pop(); // Remove from rear // remove all previous smaller that are elements // are useless while ( G.length != 0 && arr[G[G.length - 1]] <= arr[i]) G.pop(); // Remove from rear // Add current element at rear of both deque G.push(i); S.push(i); } // Sum of minimum and maximum element of last window sum += arr[S[0]] + arr[G[0]]; return sum;} // Driver code let arr = [2, 5, -1, 7, -3, -1, -2]; let k = 3; document.write(SumOfKsubArray(arr, k)); // This code is contributed by _saurabh_jaiswal </script>", "e": 40413, "s": 38286, "text": null }, { "code": null, "e": 40423, "s": 40413, "text": "Output: " }, { "code": null, "e": 40426, "s": 40423, "text": "14" }, { "code": null, "e": 40448, "s": 40426, "text": "Time Complexity: O(n)" }, { "code": null, "e": 40470, "s": 40448, "text": "Auxiliary Space: O(k)" }, { "code": null, "e": 40900, "s": 40470, "text": "This article is contributed by Nishant_Singh (Pintu). If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. " }, { "code": null, "e": 40915, "s": 40900, "text": "_Gaurav_Tiwari" }, { "code": null, "e": 40930, "s": 40915, "text": "mohit kumar 29" }, { "code": null, "e": 40944, "s": 40930, "text": "GauravRajput1" }, { "code": null, "e": 40961, "s": 40944, "text": "_saurabh_jaiswal" }, { "code": null, "e": 40973, "s": 40961, "text": "prophet1999" }, { "code": null, "e": 40988, "s": 40973, "text": "sliding-window" }, { "code": null, "e": 40997, "s": 40988, "text": "subarray" }, { "code": null, "e": 41004, "s": 40997, "text": "Arrays" }, { "code": null, "e": 41010, "s": 41004, "text": "Queue" }, { "code": null, "e": 41025, "s": 41010, "text": "sliding-window" }, { "code": null, "e": 41032, "s": 41025, "text": "Arrays" }, { "code": null, "e": 41038, "s": 41032, "text": "Queue" }, { "code": null, "e": 41136, "s": 41038, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 41159, "s": 41136, "text": "Introduction to Arrays" }, { "code": null, "e": 41191, "s": 41159, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 41212, "s": 41191, "text": "Linked List vs Array" }, { "code": null, "e": 41297, "s": 41212, "text": "Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)" }, { "code": null, "e": 41342, "s": 41297, "text": "Python | Using 2D arrays/lists the right way" }, { "code": null, "e": 41382, "s": 41342, "text": "Breadth First Search or BFS for a Graph" }, { "code": null, "e": 41416, "s": 41382, "text": "Level Order Binary Tree Traversal" }, { "code": null, "e": 41440, "s": 41416, "text": "Queue Interface In Java" }, { "code": null, "e": 41456, "s": 41440, "text": "Queue in Python" } ]
Scroll Web Page Base On Pixel Method Using Selenium in Python - GeeksforGeeks
28 Apr, 2022 Selenium is a powerful tool for controlling web browsers through programs and performing browser automation. It is functional for all browsers, works on all major OS and its scripts are written in various languages i.e Python, Java, C#, etc, we will be working with Python. A Scrollbar is helped you to circulate round display in vertical route if the modern-day web page scroll does now no longer the seen place of the display. It is used to transport the window up and down. Selenium Webdriver does now no longer requires scroll to carry out moves because it manipulates DOM. But in positive internet pages, factors best emerge as seen as soon as the person has scrolled to them. In such instances, scrolling can be necessary. Requirements: selenium You need to install chromedriver and set the path. Click here to download. Step-by-step Approach: Step 1: Import required modules Python3 from selenium import webdriverimport timefrom webdriver_manager.chrome import ChromeDriverManager # create instance of Chrome webdriverdriver=webdriver.Chrome(ChromeDriverManager().install()) Step 2: Taking any URL. Python3 from selenium import webdriverimport timefrom webdriver_manager.chrome import ChromeDriverManager # create instance of Chrome webdriverdriver=webdriver.Chrome(ChromeDriverManager().install()) #urldriver.get("https://www.countries-ofthe-world.com/flags-of-the-world.html") Step 3: Maximize the window. Python3 driver.maximize_window() Step 4: Scrolling base on the pixel. Python3 driver.execute_script("window.scrollBy(0,2000)","") Below is the full Implementation: Python3 from selenium import webdriverimport timefrom webdriver_manager.chrome import ChromeDriverManager # create instance of Chrome webdriverdriver=webdriver.Chrome(ChromeDriverManager().install()) #urldriver.get("https://www.countries-ofthe-world.com/flags-of-the-world.html") #maximize windowdriver.maximize_window() #scroll by pixeldriver.execute_script("window.scrollBy(0,2000)","")time.sleep(4) Output: rkbhola5 Python Selenium-Exercises Python-selenium Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Check if element exists in list in Python How To Convert Python Dictionary To JSON? Python Classes and Objects How to drop one or multiple columns in Pandas Dataframe Python | Get unique values from a list Defaultdict in Python Python | os.path.join() method Create a directory in Python Python | Pandas dataframe.groupby()
[ { "code": null, "e": 25537, "s": 25509, "text": "\n28 Apr, 2022" }, { "code": null, "e": 25811, "s": 25537, "text": "Selenium is a powerful tool for controlling web browsers through programs and performing browser automation. It is functional for all browsers, works on all major OS and its scripts are written in various languages i.e Python, Java, C#, etc, we will be working with Python." }, { "code": null, "e": 26266, "s": 25811, "text": "A Scrollbar is helped you to circulate round display in vertical route if the modern-day web page scroll does now no longer the seen place of the display. It is used to transport the window up and down. Selenium Webdriver does now no longer requires scroll to carry out moves because it manipulates DOM. But in positive internet pages, factors best emerge as seen as soon as the person has scrolled to them. In such instances, scrolling can be necessary." }, { "code": null, "e": 26280, "s": 26266, "text": "Requirements:" }, { "code": null, "e": 26289, "s": 26280, "text": "selenium" }, { "code": null, "e": 26365, "s": 26289, "text": "You need to install chromedriver and set the path. Click here to download. " }, { "code": null, "e": 26388, "s": 26365, "text": "Step-by-step Approach:" }, { "code": null, "e": 26420, "s": 26388, "text": "Step 1: Import required modules" }, { "code": null, "e": 26428, "s": 26420, "text": "Python3" }, { "code": "from selenium import webdriverimport timefrom webdriver_manager.chrome import ChromeDriverManager # create instance of Chrome webdriverdriver=webdriver.Chrome(ChromeDriverManager().install())", "e": 26620, "s": 26428, "text": null }, { "code": null, "e": 26644, "s": 26620, "text": "Step 2: Taking any URL." }, { "code": null, "e": 26652, "s": 26644, "text": "Python3" }, { "code": "from selenium import webdriverimport timefrom webdriver_manager.chrome import ChromeDriverManager # create instance of Chrome webdriverdriver=webdriver.Chrome(ChromeDriverManager().install()) #urldriver.get(\"https://www.countries-ofthe-world.com/flags-of-the-world.html\")", "e": 26924, "s": 26652, "text": null }, { "code": null, "e": 26953, "s": 26924, "text": "Step 3: Maximize the window." }, { "code": null, "e": 26961, "s": 26953, "text": "Python3" }, { "code": "driver.maximize_window()", "e": 26986, "s": 26961, "text": null }, { "code": null, "e": 27023, "s": 26986, "text": "Step 4: Scrolling base on the pixel." }, { "code": null, "e": 27031, "s": 27023, "text": "Python3" }, { "code": "driver.execute_script(\"window.scrollBy(0,2000)\",\"\")", "e": 27083, "s": 27031, "text": null }, { "code": null, "e": 27117, "s": 27083, "text": "Below is the full Implementation:" }, { "code": null, "e": 27125, "s": 27117, "text": "Python3" }, { "code": "from selenium import webdriverimport timefrom webdriver_manager.chrome import ChromeDriverManager # create instance of Chrome webdriverdriver=webdriver.Chrome(ChromeDriverManager().install()) #urldriver.get(\"https://www.countries-ofthe-world.com/flags-of-the-world.html\") #maximize windowdriver.maximize_window() #scroll by pixeldriver.execute_script(\"window.scrollBy(0,2000)\",\"\")time.sleep(4)", "e": 27519, "s": 27125, "text": null }, { "code": null, "e": 27527, "s": 27519, "text": "Output:" }, { "code": null, "e": 27536, "s": 27527, "text": "rkbhola5" }, { "code": null, "e": 27562, "s": 27536, "text": "Python Selenium-Exercises" }, { "code": null, "e": 27578, "s": 27562, "text": "Python-selenium" }, { "code": null, "e": 27585, "s": 27578, "text": "Python" }, { "code": null, "e": 27683, "s": 27585, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27715, "s": 27683, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 27757, "s": 27715, "text": "Check if element exists in list in Python" }, { "code": null, "e": 27799, "s": 27757, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 27826, "s": 27799, "text": "Python Classes and Objects" }, { "code": null, "e": 27882, "s": 27826, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 27921, "s": 27882, "text": "Python | Get unique values from a list" }, { "code": null, "e": 27943, "s": 27921, "text": "Defaultdict in Python" }, { "code": null, "e": 27974, "s": 27943, "text": "Python | os.path.join() method" }, { "code": null, "e": 28003, "s": 27974, "text": "Create a directory in Python" } ]
Minimum element of each row and each column in a matrix - GeeksforGeeks
10 May, 2021 Given a matrix, the task is to find the minimum element of each row and each column.Examples: Input: [1, 2, 3] [1, 4, 9] [76, 34, 21] Output: Minimum element of each row is {1, 1, 21} Minimum element of each column is {1, 2, 3} Input: [1, 2, 3, 21] [12, 1, 65, 9] [11, 56, 34, 2] Output: Minimum element of each row is {1, 1, 21} Minimum element of each column is {1, 2, 3} Approach: The idea is to run the loop for no_of_rows. Check each element inside the row and find for the minimum element. Finally, print the element. Similarly, check each element inside the column and find for the minimum element. Finally, print the element.Below is the implementation of the above approach: C++ Java Python3 C# PHP Javascript // C++ program to find the minimum// element of each row and each column#include<bits/stdc++.h>using namespace std;const int MAX = 100; // function to find the minimum// element of each row.void smallestInRow(int mat[][MAX], int n, int m){ cout << " { "; for (int i = 0; i < n; i++) { // initialize the minimum element // as first element int minm = mat[i][0]; for (int j = 1; j < m; j++) { // check if any element is smaller // than the minimum element of the row // and replace it if (mat[i][j] < minm) minm = mat[i][j]; } // print the smallest element of the row cout << minm << ", "; } cout << "}";} // function to find the minimum// element of each column.void smallestInCol(int mat[][MAX], int n, int m){ cout << " { "; for (int i = 0; i < m; i++) { // initialize the minimum element // as first element int minm = mat[0][i]; // Run the inner loop for columns for (int j = 1; j < n; j++) { // check if any element is smaller // than the minimum element of the column // and replace it if (mat[j][i] < minm) minm = mat[j][i]; } // print the smallest element of the row cout << minm << ", "; } cout << "}";} // Driver codeint main(){ int n = 3, m = 3; int mat[][MAX] = { { 2, 1, 7 }, { 3, 7, 2 }, { 5, 4, 9 } }; cout << "Minimum element of each row is "; smallestInRow(mat, n, m); cout << "\nMinimum element of each column is "; smallestInCol(mat, n, m); return 0;} // Java program to find the minimum// element of each row and each column public class GFG { final static int MAX = 100; // function to find the minimum// element of each row. static void smallestInRow(int mat[][], int n, int m) { System.out.print(" { "); for (int i = 0; i < n; i++) { // initialize the minimum element // as first element int minm = mat[i][0]; for (int j = 1; j < m; j++) { // check if any element is smaller // than the minimum element of the row // and replace it if (mat[i][j] < minm) { minm = mat[i][j]; } } // print the smallest element of the row System.out.print(minm + ", "); } System.out.println("}"); } // function to find the minimum// element of each column. static void smallestInCol(int mat[][], int n, int m) { System.out.print(" { "); for (int i = 0; i < m; i++) { // initialize the minimum element // as first element int minm = mat[0][i]; // Run the inner loop for columns for (int j = 1; j < n; j++) { // check if any element is smaller // than the minimum element of the column // and replace it if (mat[j][i] < minm) { minm = mat[j][i]; } } // print the smallest element of the row System.out.print(minm + ", "); } System.out.print("}"); } // Driver code public static void main(String args[]) { int n = 3, m = 3; int mat[][] = {{2, 1, 7}, {3, 7, 2}, {5, 4, 9}}; System.out.print("Minimum element of each row is "); smallestInRow(mat, n, m); System.out.print("\nMinimum element of each column is "); smallestInCol(mat, n, m); }} /*This code is contributed by 29AjayKumar*/ # Python 3 program to find the minimum MAX = 100 # function to find the minimum# element of each row.def smallestInRow(mat, n, m): print("{", end = "") for i in range(n): # initialize the minimum element # as first element minm = mat[i][0] for j in range(1, m, 1): # check if any element is smaller # than the minimum element of the # row and replace it if (mat[i][j] < minm): minm = mat[i][j] # print the smallest element # of the row print(minm, end = ",") print("}") # function to find the minimum# element of each column.def smallestInCol(mat, n, m): print("{", end = "") for i in range(m): # initialize the minimum element # as first element minm = mat[0][i] # Run the inner loop for columns for j in range(1, n, 1): # check if any element is smaller # than the minimum element of the # column and replace it if (mat[j][i] < minm): minm = mat[j][i] # print the smallest element # of the row print(minm, end = ",") print("}") # Driver codeif __name__ == '__main__': n = 3 m = 3 mat = [[2, 1, 7], [3, 7, 2 ], [ 5, 4, 9 ]]; print("Minimum element of each row is", end = " ") smallestInRow(mat, n, m) print("Minimum element of each column is", end = " ") smallestInCol(mat, n, m) # This code is contributed by# Shashank_Sharma // C# program to find the minimum// element of each row and each columnusing System; class GFG{ readonly static int MAX = 100; // function to find the minimum// element of each row.static void smallestInRow(int [,]mat, int n, int m){ Console.Write(" { "); for (int i = 0; i < n; i++) { // initialize the minimum element // as first element int minm = mat[i, 0]; for (int j = 1; j < m; j++) { // check if any element is smaller // than the minimum element of the // row and replace it if (mat[i, j] < minm) { minm = mat[i, j]; } } // print the smallest element // of the row Console.Write(minm + ", "); } Console.WriteLine("}");} // function to find the minimum// element of each column.static void smallestInCol(int [,]mat, int n, int m){ Console.Write(" { "); for (int i = 0; i < m; i++) { // initialize the minimum element // as first element int minm = mat[0, i]; // Run the inner loop for columns for (int j = 1; j < n; j++) { // check if any element is smaller // than the minimum element of the // column and replace it if (mat[j, i] < minm) { minm = mat[j, i]; } } // print the smallest element // of the row Console.Write(minm + ", "); } Console.Write("}");} // Driver codepublic static void Main(){ int n = 3, m = 3; int [,]mat = {{2, 1, 7}, {3, 7, 2}, {5, 4, 9}}; Console.Write("Minimum element of " + "each row is "); smallestInRow(mat, n, m); Console.Write("\nMinimum element of " + "each column is "); smallestInCol(mat, n, m);}} // This code is contributed// by 29AjayKumar <?php// PHP program to find the minimum// element of each row and each column$MAX = 100; // function to find the minimum// element of each row.function smallestInRow(&$mat, $n, $m){ echo " { "; for ($i = 0; $i < $n; $i++) { // initialize the minimum element // as first element $minm = $mat[$i][0]; for ($j = 1; $j < $m; $j++) { // check if any element is smaller // than the minimum element of the // row and replace it if ($mat[$i][$j] < $minm) $minm = $mat[$i][$j]; } // print the smallest element // of the row echo $minm . ", "; } echo "}";} // function to find the minimum// element of each column.function smallestInCol(&$mat, $n, $m){ echo " { "; for ($i = 0; $i < $m; $i++) { // initialize the minimum element // as first element $minm = $mat[0][$i]; // Run the inner loop for columns for ($j = 1; $j < $n; $j++) { // check if any element is smaller // than the minimum element of the column // and replace it if ($mat[$j][$i] < $minm) $minm = $mat[$j][$i]; } // print the smallest element of the row echo $minm . ", "; } echo "}";} // Driver code$n = 3;$m = 3;$mat = array(array( 2, 1, 7 ), array( 3, 7, 2 ), array( 5, 4, 9 )); echo "Minimum element of each row is ";smallestInRow($mat, $n, $m); echo "\nMinimum element of each column is ";smallestInCol($mat, $n, $m); // This code is contributed by ita_c?> <script>// Java script program to find the minimum// element of each row and each column let MAX = 100; // function to find the minimum// element of each row. function smallestInRow(mat,n,m) { document.write(" { "); for (let i = 0; i < n; i++) { // initialize the minimum element // as first element let minm = mat[i][0]; for (let j = 1; j < m; j++) { // check if any element is smaller // than the minimum element of the row // and replace it if (mat[i][j] < minm) { minm = mat[i][j]; } } // print the smallest element of the row document.write(minm + ", "); } document.write("}"+"<br>"); } // function to find the minimum// element of each column. function smallestInCol(mat,n,m) { document.write(" { "); for (let i = 0; i < m; i++) { // initialize the minimum element // as first element let minm = mat[0][i]; // Run the inner loop for columns for (let j = 1; j < n; j++) { // check if any element is smaller // than the minimum element of the column // and replace it if (mat[j][i] < minm) { minm = mat[j][i]; } } // print the smallest element of the row document.write(minm + ", "); } document.write("}"); } // Driver code let n = 3, m = 3; let mat = [[2, 1, 7], [3, 7, 2], [5, 4, 9]]; document.write("Minimum element of each row is "); smallestInRow(mat, n, m); document.write("\nMinimum element of each column is "); smallestInCol(mat, n, m); // This code is contributed by Bobby</script> Minimum element of each row is { 1, 2, 4, } Minimum element of each column is { 2, 1, 2, } Time complexity: O(n*m) 29AjayKumar Shashank_Sharma ukasp gottumukkalabobby Technical Scripter 2018 Matrix Technical Scripter Matrix Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Efficiently compute sums of diagonals of a matrix Flood fill Algorithm - how to implement fill() in paint? Check for possible path in 2D matrix Zigzag (or diagonal) traversal of Matrix Mathematics | L U Decomposition of a System of Linear Equations Python program to add two Matrices Unique paths in a Grid with Obstacles A Boolean Matrix Question Shortest distance between two cells in a matrix or grid Program for Conway's Game Of Life
[ { "code": null, "e": 26165, "s": 26137, "text": "\n10 May, 2021" }, { "code": null, "e": 26261, "s": 26165, "text": "Given a matrix, the task is to find the minimum element of each row and each column.Examples: " }, { "code": null, "e": 26572, "s": 26261, "text": "Input: [1, 2, 3]\n [1, 4, 9]\n [76, 34, 21]\nOutput: Minimum element of each row is {1, 1, 21}\nMinimum element of each column is {1, 2, 3}\n\nInput: [1, 2, 3, 21]\n [12, 1, 65, 9]\n [11, 56, 34, 2]\nOutput: Minimum element of each row is {1, 1, 21}\nMinimum element of each column is {1, 2, 3}" }, { "code": null, "e": 26885, "s": 26574, "text": "Approach: The idea is to run the loop for no_of_rows. Check each element inside the row and find for the minimum element. Finally, print the element. Similarly, check each element inside the column and find for the minimum element. Finally, print the element.Below is the implementation of the above approach: " }, { "code": null, "e": 26889, "s": 26885, "text": "C++" }, { "code": null, "e": 26894, "s": 26889, "text": "Java" }, { "code": null, "e": 26902, "s": 26894, "text": "Python3" }, { "code": null, "e": 26905, "s": 26902, "text": "C#" }, { "code": null, "e": 26909, "s": 26905, "text": "PHP" }, { "code": null, "e": 26920, "s": 26909, "text": "Javascript" }, { "code": "// C++ program to find the minimum// element of each row and each column#include<bits/stdc++.h>using namespace std;const int MAX = 100; // function to find the minimum// element of each row.void smallestInRow(int mat[][MAX], int n, int m){ cout << \" { \"; for (int i = 0; i < n; i++) { // initialize the minimum element // as first element int minm = mat[i][0]; for (int j = 1; j < m; j++) { // check if any element is smaller // than the minimum element of the row // and replace it if (mat[i][j] < minm) minm = mat[i][j]; } // print the smallest element of the row cout << minm << \", \"; } cout << \"}\";} // function to find the minimum// element of each column.void smallestInCol(int mat[][MAX], int n, int m){ cout << \" { \"; for (int i = 0; i < m; i++) { // initialize the minimum element // as first element int minm = mat[0][i]; // Run the inner loop for columns for (int j = 1; j < n; j++) { // check if any element is smaller // than the minimum element of the column // and replace it if (mat[j][i] < minm) minm = mat[j][i]; } // print the smallest element of the row cout << minm << \", \"; } cout << \"}\";} // Driver codeint main(){ int n = 3, m = 3; int mat[][MAX] = { { 2, 1, 7 }, { 3, 7, 2 }, { 5, 4, 9 } }; cout << \"Minimum element of each row is \"; smallestInRow(mat, n, m); cout << \"\\nMinimum element of each column is \"; smallestInCol(mat, n, m); return 0;}", "e": 28616, "s": 26920, "text": null }, { "code": "// Java program to find the minimum// element of each row and each column public class GFG { final static int MAX = 100; // function to find the minimum// element of each row. static void smallestInRow(int mat[][], int n, int m) { System.out.print(\" { \"); for (int i = 0; i < n; i++) { // initialize the minimum element // as first element int minm = mat[i][0]; for (int j = 1; j < m; j++) { // check if any element is smaller // than the minimum element of the row // and replace it if (mat[i][j] < minm) { minm = mat[i][j]; } } // print the smallest element of the row System.out.print(minm + \", \"); } System.out.println(\"}\"); } // function to find the minimum// element of each column. static void smallestInCol(int mat[][], int n, int m) { System.out.print(\" { \"); for (int i = 0; i < m; i++) { // initialize the minimum element // as first element int minm = mat[0][i]; // Run the inner loop for columns for (int j = 1; j < n; j++) { // check if any element is smaller // than the minimum element of the column // and replace it if (mat[j][i] < minm) { minm = mat[j][i]; } } // print the smallest element of the row System.out.print(minm + \", \"); } System.out.print(\"}\"); } // Driver code public static void main(String args[]) { int n = 3, m = 3; int mat[][] = {{2, 1, 7}, {3, 7, 2}, {5, 4, 9}}; System.out.print(\"Minimum element of each row is \"); smallestInRow(mat, n, m); System.out.print(\"\\nMinimum element of each column is \"); smallestInCol(mat, n, m); }} /*This code is contributed by 29AjayKumar*/", "e": 30627, "s": 28616, "text": null }, { "code": "# Python 3 program to find the minimum MAX = 100 # function to find the minimum# element of each row.def smallestInRow(mat, n, m): print(\"{\", end = \"\") for i in range(n): # initialize the minimum element # as first element minm = mat[i][0] for j in range(1, m, 1): # check if any element is smaller # than the minimum element of the # row and replace it if (mat[i][j] < minm): minm = mat[i][j] # print the smallest element # of the row print(minm, end = \",\") print(\"}\") # function to find the minimum# element of each column.def smallestInCol(mat, n, m): print(\"{\", end = \"\") for i in range(m): # initialize the minimum element # as first element minm = mat[0][i] # Run the inner loop for columns for j in range(1, n, 1): # check if any element is smaller # than the minimum element of the # column and replace it if (mat[j][i] < minm): minm = mat[j][i] # print the smallest element # of the row print(minm, end = \",\") print(\"}\") # Driver codeif __name__ == '__main__': n = 3 m = 3 mat = [[2, 1, 7], [3, 7, 2 ], [ 5, 4, 9 ]]; print(\"Minimum element of each row is\", end = \" \") smallestInRow(mat, n, m) print(\"Minimum element of each column is\", end = \" \") smallestInCol(mat, n, m) # This code is contributed by# Shashank_Sharma", "e": 32264, "s": 30627, "text": null }, { "code": "// C# program to find the minimum// element of each row and each columnusing System; class GFG{ readonly static int MAX = 100; // function to find the minimum// element of each row.static void smallestInRow(int [,]mat, int n, int m){ Console.Write(\" { \"); for (int i = 0; i < n; i++) { // initialize the minimum element // as first element int minm = mat[i, 0]; for (int j = 1; j < m; j++) { // check if any element is smaller // than the minimum element of the // row and replace it if (mat[i, j] < minm) { minm = mat[i, j]; } } // print the smallest element // of the row Console.Write(minm + \", \"); } Console.WriteLine(\"}\");} // function to find the minimum// element of each column.static void smallestInCol(int [,]mat, int n, int m){ Console.Write(\" { \"); for (int i = 0; i < m; i++) { // initialize the minimum element // as first element int minm = mat[0, i]; // Run the inner loop for columns for (int j = 1; j < n; j++) { // check if any element is smaller // than the minimum element of the // column and replace it if (mat[j, i] < minm) { minm = mat[j, i]; } } // print the smallest element // of the row Console.Write(minm + \", \"); } Console.Write(\"}\");} // Driver codepublic static void Main(){ int n = 3, m = 3; int [,]mat = {{2, 1, 7}, {3, 7, 2}, {5, 4, 9}}; Console.Write(\"Minimum element of \" + \"each row is \"); smallestInRow(mat, n, m); Console.Write(\"\\nMinimum element of \" + \"each column is \"); smallestInCol(mat, n, m);}} // This code is contributed// by 29AjayKumar", "e": 34244, "s": 32264, "text": null }, { "code": "<?php// PHP program to find the minimum// element of each row and each column$MAX = 100; // function to find the minimum// element of each row.function smallestInRow(&$mat, $n, $m){ echo \" { \"; for ($i = 0; $i < $n; $i++) { // initialize the minimum element // as first element $minm = $mat[$i][0]; for ($j = 1; $j < $m; $j++) { // check if any element is smaller // than the minimum element of the // row and replace it if ($mat[$i][$j] < $minm) $minm = $mat[$i][$j]; } // print the smallest element // of the row echo $minm . \", \"; } echo \"}\";} // function to find the minimum// element of each column.function smallestInCol(&$mat, $n, $m){ echo \" { \"; for ($i = 0; $i < $m; $i++) { // initialize the minimum element // as first element $minm = $mat[0][$i]; // Run the inner loop for columns for ($j = 1; $j < $n; $j++) { // check if any element is smaller // than the minimum element of the column // and replace it if ($mat[$j][$i] < $minm) $minm = $mat[$j][$i]; } // print the smallest element of the row echo $minm . \", \"; } echo \"}\";} // Driver code$n = 3;$m = 3;$mat = array(array( 2, 1, 7 ), array( 3, 7, 2 ), array( 5, 4, 9 )); echo \"Minimum element of each row is \";smallestInRow($mat, $n, $m); echo \"\\nMinimum element of each column is \";smallestInCol($mat, $n, $m); // This code is contributed by ita_c?>", "e": 35869, "s": 34244, "text": null }, { "code": "<script>// Java script program to find the minimum// element of each row and each column let MAX = 100; // function to find the minimum// element of each row. function smallestInRow(mat,n,m) { document.write(\" { \"); for (let i = 0; i < n; i++) { // initialize the minimum element // as first element let minm = mat[i][0]; for (let j = 1; j < m; j++) { // check if any element is smaller // than the minimum element of the row // and replace it if (mat[i][j] < minm) { minm = mat[i][j]; } } // print the smallest element of the row document.write(minm + \", \"); } document.write(\"}\"+\"<br>\"); } // function to find the minimum// element of each column. function smallestInCol(mat,n,m) { document.write(\" { \"); for (let i = 0; i < m; i++) { // initialize the minimum element // as first element let minm = mat[0][i]; // Run the inner loop for columns for (let j = 1; j < n; j++) { // check if any element is smaller // than the minimum element of the column // and replace it if (mat[j][i] < minm) { minm = mat[j][i]; } } // print the smallest element of the row document.write(minm + \", \"); } document.write(\"}\"); } // Driver code let n = 3, m = 3; let mat = [[2, 1, 7], [3, 7, 2], [5, 4, 9]]; document.write(\"Minimum element of each row is \"); smallestInRow(mat, n, m); document.write(\"\\nMinimum element of each column is \"); smallestInCol(mat, n, m); // This code is contributed by Bobby</script>", "e": 37760, "s": 35869, "text": null }, { "code": null, "e": 37853, "s": 37760, "text": "Minimum element of each row is { 1, 2, 4, }\nMinimum element of each column is { 2, 1, 2, }" }, { "code": null, "e": 37880, "s": 37855, "text": "Time complexity: O(n*m) " }, { "code": null, "e": 37892, "s": 37880, "text": "29AjayKumar" }, { "code": null, "e": 37908, "s": 37892, "text": "Shashank_Sharma" }, { "code": null, "e": 37914, "s": 37908, "text": "ukasp" }, { "code": null, "e": 37932, "s": 37914, "text": "gottumukkalabobby" }, { "code": null, "e": 37956, "s": 37932, "text": "Technical Scripter 2018" }, { "code": null, "e": 37963, "s": 37956, "text": "Matrix" }, { "code": null, "e": 37982, "s": 37963, "text": "Technical Scripter" }, { "code": null, "e": 37989, "s": 37982, "text": "Matrix" }, { "code": null, "e": 38087, "s": 37989, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 38137, "s": 38087, "text": "Efficiently compute sums of diagonals of a matrix" }, { "code": null, "e": 38194, "s": 38137, "text": "Flood fill Algorithm - how to implement fill() in paint?" }, { "code": null, "e": 38231, "s": 38194, "text": "Check for possible path in 2D matrix" }, { "code": null, "e": 38272, "s": 38231, "text": "Zigzag (or diagonal) traversal of Matrix" }, { "code": null, "e": 38336, "s": 38272, "text": "Mathematics | L U Decomposition of a System of Linear Equations" }, { "code": null, "e": 38371, "s": 38336, "text": "Python program to add two Matrices" }, { "code": null, "e": 38409, "s": 38371, "text": "Unique paths in a Grid with Obstacles" }, { "code": null, "e": 38435, "s": 38409, "text": "A Boolean Matrix Question" }, { "code": null, "e": 38491, "s": 38435, "text": "Shortest distance between two cells in a matrix or grid" } ]
Unit Testing in R Programming - GeeksforGeeks
22 Jul, 2020 The unit test basically is small functions that test and help to write robust code. From a robust code we mean a code which will not break easily upon changes, can be refactored simply, can be extended without breaking the rest, and can be tested with ease. Unit tests are of great use when it comes to dynamically typed script languages as there is no assistance from a compiler showing you places where functions could be called with invalid arguments. What does a simple function do, it takes some input x and returns an output y. In unit testing, we verify the preciseness and correctness of the function is returning the expected value of y for a specific value of x when calling the function. Generally, different (x, y) pairs are tested. What if our code has side effects e.g reading/writing of files, access to some database, etc. then how does a unit test work. In such scenarios, the preparation of the test is more complex. It could comprise just a bunch of mock objects of functions for simulating access to a database. That is influencing the programming style for which abstraction layers might become necessary. In some cases, input files need to be generated before executing the test, and output files are to be checked after the test. The basic idea behind unit testing is simple, you write a script that automatically evaluates pieces of your code and checks it against expected behavior. Now let us see some examples for a better understanding of what actually unit testing means and how it works. In R programming testthat package helps us to implement unit testing in our codes. To install testthat package one just need to run the following code in his R console. if (!require(testthat)) install.packages('testthat') testthat uses test_that() function to create a test and uses expectations for unit testing of code. An expectation allows us to assert that the values returned by a function match the ones we should get. test_that("Message to be displayed", { expect_equal(function_f(input x), expected_output_y) expect_equivalent(function_f(input x), expected_output_y) expect_identical(function_f(input x), expected_output_y) . . . }) There are more than 20 expectations in the testthat package. expect_error(), expect_warning(), expect_message(), expect_condition() skip(), skip_if_not(), skip_if(), skip_if_not_installed(), skip_if_offline(), skip_on_cran(), skip_on_os(), skip_on_travis(), skip_on_appveyor(), skip_on_ci(), skip_on_covr(), skip_on_bioc(), skip_if_translated() expect_snapshot_output(), expect_snapshot_value(), expect_snapshot_error(), expect_snapshot_condition() Example: Define a function factorial that takes a numeric value n and returns its factorial. R # create a recursive program that # calculates the factorial of number nfactorial <- function(n){ if(n == 0) { return(1) } else { return(n * factorial(n - 2)) }} Now, let’s perform unit testing on our function factorial and test its accuracy and debug our program. R # import testthat packagelibrary(testthat) # use expect_that to create testsexpect_that( "Factorial of number $n", { expect_equal(factorial(5), 120) expect_identical(factorial(2), 2) expect_equal(factorial(8), 40320) }) Output: Error: Test failed: 'Factorial computed correctly' * factorial(5) not equal to 120. 1/1 mismatches [1] 15 - 120 == -105 * factorial(8) not equal to 40320. 1/1 mismatches [1] 384 - 40320 == -39936 The test gives an error, it means that our function does not return the desired results. We knowingly wrote our code wrong. In the factorial function, the recursive approach we used has an error. Let us eradicate that error and test our function one more time. R # create a recursive program that# calculates the factorial of number nfactorial <- function(n){ if(n == 0) { return(1) } else { # notice we used (n-2) instead # of (n-1) in our previous code return(n * factorial(n - 1)) }} # import testthat packagelibrary(testthat) # use expect_that to create testsexpect_that( "Factorial of number $n", { expect_equal(factorial(5), 120) expect_identical(factorial(2), 2) expect_equal(factorial(8), 40320) }) # no error Note: If your source code and packages are not in the same directory you have to run a line of code with function source( ) to run tests. source("your_file_path") # This is only needed if your project is not a package It is really important to organize your files and tests. We should have a folder named R with all the R code files, and one folder named tests/testthat, where all the test scripts will live. From the R console, you can run all tests in a file with test_file("./path/to/file") And all tests in a folder with test_dir("./path/to/folder") Both the above-mentioned function accept a special parameter reporter which has several options to offer which are progress it is the default value minimal for a minimal report location shows the file, line, and column of the test run (failed or otherwise), debug allows you to debug interactively a failing test and more. test_dir("./path/to/folder", reporter=c("minimal", "location")) Unit testing is necessary if you want a bug free, well-formed code. Picked R Error-handling R Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Change Color of Bars in Barchart using ggplot2 in R Group by function in R using Dplyr How to Change Axis Scales in R Plots? How to Split Column Into Multiple Columns in R DataFrame? Replace Specific Characters in String in R How to filter R DataFrame by values in a column? How to import an Excel File into R ? Time Series Analysis in R R - if statement How to filter R dataframe by multiple conditions?
[ { "code": null, "e": 26487, "s": 26459, "text": "\n22 Jul, 2020" }, { "code": null, "e": 26942, "s": 26487, "text": "The unit test basically is small functions that test and help to write robust code. From a robust code we mean a code which will not break easily upon changes, can be refactored simply, can be extended without breaking the rest, and can be tested with ease. Unit tests are of great use when it comes to dynamically typed script languages as there is no assistance from a compiler showing you places where functions could be called with invalid arguments." }, { "code": null, "e": 28005, "s": 26942, "text": "What does a simple function do, it takes some input x and returns an output y. In unit testing, we verify the preciseness and correctness of the function is returning the expected value of y for a specific value of x when calling the function. Generally, different (x, y) pairs are tested. What if our code has side effects e.g reading/writing of files, access to some database, etc. then how does a unit test work. In such scenarios, the preparation of the test is more complex. It could comprise just a bunch of mock objects of functions for simulating access to a database. That is influencing the programming style for which abstraction layers might become necessary. In some cases, input files need to be generated before executing the test, and output files are to be checked after the test. The basic idea behind unit testing is simple, you write a script that automatically evaluates pieces of your code and checks it against expected behavior. Now let us see some examples for a better understanding of what actually unit testing means and how it works." }, { "code": null, "e": 28174, "s": 28005, "text": "In R programming testthat package helps us to implement unit testing in our codes. To install testthat package one just need to run the following code in his R console." }, { "code": null, "e": 28228, "s": 28174, "text": "if (!require(testthat)) install.packages('testthat')\n" }, { "code": null, "e": 28433, "s": 28228, "text": "testthat uses test_that() function to create a test and uses expectations for unit testing of code. An expectation allows us to assert that the values returned by a function match the ones we should get. " }, { "code": null, "e": 28730, "s": 28433, "text": "test_that(\"Message to be displayed\",\n { expect_equal(function_f(input x), expected_output_y)\n expect_equivalent(function_f(input x), expected_output_y)\n expect_identical(function_f(input x), expected_output_y)\n .\n .\n .\n })\n" }, { "code": null, "e": 28791, "s": 28730, "text": "There are more than 20 expectations in the testthat package." }, { "code": null, "e": 28844, "s": 28791, "text": "expect_error(), expect_warning(), expect_message(), " }, { "code": null, "e": 28863, "s": 28844, "text": "expect_condition()" }, { "code": null, "e": 29010, "s": 28863, "text": "skip(), skip_if_not(), skip_if(), skip_if_not_installed(), skip_if_offline(), skip_on_cran(), skip_on_os(), skip_on_travis(), skip_on_appveyor(), " }, { "code": null, "e": 29077, "s": 29010, "text": "skip_on_ci(), skip_on_covr(), skip_on_bioc(), skip_if_translated()" }, { "code": null, "e": 29128, "s": 29077, "text": "expect_snapshot_output(), expect_snapshot_value()," }, { "code": null, "e": 29181, "s": 29128, "text": "expect_snapshot_error(), expect_snapshot_condition()" }, { "code": null, "e": 29274, "s": 29181, "text": "Example: Define a function factorial that takes a numeric value n and returns its factorial." }, { "code": null, "e": 29276, "s": 29274, "text": "R" }, { "code": "# create a recursive program that # calculates the factorial of number nfactorial <- function(n){ if(n == 0) { return(1) } else { return(n * factorial(n - 2)) }}", "e": 29450, "s": 29276, "text": null }, { "code": null, "e": 29553, "s": 29450, "text": "Now, let’s perform unit testing on our function factorial and test its accuracy and debug our program." }, { "code": null, "e": 29555, "s": 29553, "text": "R" }, { "code": "# import testthat packagelibrary(testthat) # use expect_that to create testsexpect_that( \"Factorial of number $n\", { expect_equal(factorial(5), 120) expect_identical(factorial(2), 2) expect_equal(factorial(8), 40320) })", "e": 29788, "s": 29555, "text": null }, { "code": null, "e": 29796, "s": 29788, "text": "Output:" }, { "code": null, "e": 29993, "s": 29796, "text": "Error: Test failed: 'Factorial computed correctly'\n* factorial(5) not equal to 120.\n1/1 mismatches\n[1] 15 - 120 == -105\n* factorial(8) not equal to 40320.\n1/1 mismatches\n[1] 384 - 40320 == -39936\n" }, { "code": null, "e": 30254, "s": 29993, "text": "The test gives an error, it means that our function does not return the desired results. We knowingly wrote our code wrong. In the factorial function, the recursive approach we used has an error. Let us eradicate that error and test our function one more time." }, { "code": null, "e": 30256, "s": 30254, "text": "R" }, { "code": "# create a recursive program that# calculates the factorial of number nfactorial <- function(n){ if(n == 0) { return(1) } else { # notice we used (n-2) instead # of (n-1) in our previous code return(n * factorial(n - 1)) }} # import testthat packagelibrary(testthat) # use expect_that to create testsexpect_that( \"Factorial of number $n\", { expect_equal(factorial(5), 120) expect_identical(factorial(2), 2) expect_equal(factorial(8), 40320) })", "e": 30732, "s": 30256, "text": null }, { "code": null, "e": 30744, "s": 30732, "text": "# no error\n" }, { "code": null, "e": 30882, "s": 30744, "text": "Note: If your source code and packages are not in the same directory you have to run a line of code with function source( ) to run tests." }, { "code": null, "e": 30964, "s": 30882, "text": "source(\"your_file_path\") # This is only needed if your project is not a package\n" }, { "code": null, "e": 31213, "s": 30964, "text": "It is really important to organize your files and tests. We should have a folder named R with all the R code files, and one folder named tests/testthat, where all the test scripts will live. From the R console, you can run all tests in a file with " }, { "code": null, "e": 31242, "s": 31213, "text": "test_file(\"./path/to/file\")\n" }, { "code": null, "e": 31273, "s": 31242, "text": "And all tests in a folder with" }, { "code": null, "e": 31303, "s": 31273, "text": "test_dir(\"./path/to/folder\")\n" }, { "code": null, "e": 31418, "s": 31303, "text": "Both the above-mentioned function accept a special parameter reporter which has several options to offer which are" }, { "code": null, "e": 31452, "s": 31418, "text": "progress it is the default value" }, { "code": null, "e": 31483, "s": 31452, "text": "minimal for a minimal report" }, { "code": null, "e": 31566, "s": 31483, "text": "location shows the file, line, and column of the test run (failed or otherwise)," }, { "code": null, "e": 31636, "s": 31566, "text": "debug allows you to debug interactively a failing test and more." }, { "code": null, "e": 31701, "s": 31636, "text": "test_dir(\"./path/to/folder\", reporter=c(\"minimal\", \"location\"))\n" }, { "code": null, "e": 31769, "s": 31701, "text": "Unit testing is necessary if you want a bug free, well-formed code." }, { "code": null, "e": 31776, "s": 31769, "text": "Picked" }, { "code": null, "e": 31793, "s": 31776, "text": "R Error-handling" }, { "code": null, "e": 31804, "s": 31793, "text": "R Language" }, { "code": null, "e": 31902, "s": 31804, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 31954, "s": 31902, "text": "Change Color of Bars in Barchart using ggplot2 in R" }, { "code": null, "e": 31989, "s": 31954, "text": "Group by function in R using Dplyr" }, { "code": null, "e": 32027, "s": 31989, "text": "How to Change Axis Scales in R Plots?" }, { "code": null, "e": 32085, "s": 32027, "text": "How to Split Column Into Multiple Columns in R DataFrame?" }, { "code": null, "e": 32128, "s": 32085, "text": "Replace Specific Characters in String in R" }, { "code": null, "e": 32177, "s": 32128, "text": "How to filter R DataFrame by values in a column?" }, { "code": null, "e": 32214, "s": 32177, "text": "How to import an Excel File into R ?" }, { "code": null, "e": 32240, "s": 32214, "text": "Time Series Analysis in R" }, { "code": null, "e": 32257, "s": 32240, "text": "R - if statement" } ]
HTML | DOM createTextNode() Method - GeeksforGeeks
19 Apr, 2021 The createTextNode() method is used to create a TextNode which contains element node and a text node. It is used to provide text to an element. This method contains the text values as parameter which is of string type.Syntax: document.createTextNode( text ) Parameters: This method accepts single parameter text which is mandatory. It is used to specify the text of text node.Example: html <!DOCTYPE html><html> <head> <title>DOM createTextNode() Method</title> <style> h1, h2 { color:green; font-weight:bold; } body { text-align:center; } </style> </head> <body> <h1>GeeksForGeels</h1> <h2>DOM createTextNode() Method</h2> <button onclick="geeks()">Submit</button> <script> function geeks() { var x = document.createTextNode("GeeksForGeeks"); document.body.appendChild(x); } </script> </body></html> Output: Before Clicking on Button: After Clicking on Button: Supported Browsers: The browser supported by DOM createTextNode() Method are listed below: Google Chrome Internet Explorer Firefox Opera Safari Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course. hritikbhatnagar2182 HTML-DOM CSS HTML Web Technologies HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to insert spaces/tabs in text using HTML/CSS? Top 10 Projects For Beginners To Practice HTML and CSS Skills How to update Node.js and NPM to next version ? How to create footer to stay at the bottom of a Web page? How to apply style to parent if it has child with CSS? How to insert spaces/tabs in text using HTML/CSS? Top 10 Projects For Beginners To Practice HTML and CSS Skills How to update Node.js and NPM to next version ? How to set the default value for an HTML <select> element ? Hide or show elements in HTML using display property
[ { "code": null, "e": 25096, "s": 25068, "text": "\n19 Apr, 2021" }, { "code": null, "e": 25324, "s": 25096, "text": "The createTextNode() method is used to create a TextNode which contains element node and a text node. It is used to provide text to an element. This method contains the text values as parameter which is of string type.Syntax: " }, { "code": null, "e": 25356, "s": 25324, "text": "document.createTextNode( text )" }, { "code": null, "e": 25485, "s": 25356, "text": "Parameters: This method accepts single parameter text which is mandatory. It is used to specify the text of text node.Example: " }, { "code": null, "e": 25490, "s": 25485, "text": "html" }, { "code": "<!DOCTYPE html><html> <head> <title>DOM createTextNode() Method</title> <style> h1, h2 { color:green; font-weight:bold; } body { text-align:center; } </style> </head> <body> <h1>GeeksForGeels</h1> <h2>DOM createTextNode() Method</h2> <button onclick=\"geeks()\">Submit</button> <script> function geeks() { var x = document.createTextNode(\"GeeksForGeeks\"); document.body.appendChild(x); } </script> </body></html> ", "e": 26148, "s": 25490, "text": null }, { "code": null, "e": 26157, "s": 26148, "text": "Output: " }, { "code": null, "e": 26184, "s": 26157, "text": "Before Clicking on Button:" }, { "code": null, "e": 26211, "s": 26184, "text": "After Clicking on Button: " }, { "code": null, "e": 26305, "s": 26211, "text": "Supported Browsers: The browser supported by DOM createTextNode() Method are listed below: " }, { "code": null, "e": 26319, "s": 26305, "text": "Google Chrome" }, { "code": null, "e": 26337, "s": 26319, "text": "Internet Explorer" }, { "code": null, "e": 26345, "s": 26337, "text": "Firefox" }, { "code": null, "e": 26351, "s": 26345, "text": "Opera" }, { "code": null, "e": 26358, "s": 26351, "text": "Safari" }, { "code": null, "e": 26497, "s": 26360, "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": 26517, "s": 26497, "text": "hritikbhatnagar2182" }, { "code": null, "e": 26526, "s": 26517, "text": "HTML-DOM" }, { "code": null, "e": 26530, "s": 26526, "text": "CSS" }, { "code": null, "e": 26535, "s": 26530, "text": "HTML" }, { "code": null, "e": 26552, "s": 26535, "text": "Web Technologies" }, { "code": null, "e": 26557, "s": 26552, "text": "HTML" }, { "code": null, "e": 26655, "s": 26557, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26705, "s": 26655, "text": "How to insert spaces/tabs in text using HTML/CSS?" }, { "code": null, "e": 26767, "s": 26705, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 26815, "s": 26767, "text": "How to update Node.js and NPM to next version ?" }, { "code": null, "e": 26873, "s": 26815, "text": "How to create footer to stay at the bottom of a Web page?" }, { "code": null, "e": 26928, "s": 26873, "text": "How to apply style to parent if it has child with CSS?" }, { "code": null, "e": 26978, "s": 26928, "text": "How to insert spaces/tabs in text using HTML/CSS?" }, { "code": null, "e": 27040, "s": 26978, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 27088, "s": 27040, "text": "How to update Node.js and NPM to next version ?" }, { "code": null, "e": 27148, "s": 27088, "text": "How to set the default value for an HTML <select> element ?" } ]
jQuery Slidebar.js Plugin - GeeksforGeeks
18 Jan, 2021 JQuery is a small, fast, rich JavaScript Library that is an optimized version of JavaScript. It provides us with a simple API that helps in HTML document traversal and manipulation, event handling, animation, and Ajax. jQuery provide us with a variety of plugins that can be implemented on the website, one of which is Slidebar.js. Slidebar.js: It is a jQuery Plugin that helps us to create a slidebar along with an animation. It helps in implementing mobile app-style revealing menus and sidebars into our website. There are four types of slidebars that can be created: Left SlidebarRight SlidebarTop SlidebarBottom Slidebar Left Slidebar Right Slidebar Top Slidebar Bottom Slidebar In this article, we will be learning about how to implement a left sidebar on our website. But before that, we need to add some CDNs in order to make the slidebar work. 1. Include jQuery CDN <script src=”https://code.jquery.com/jquery-3.5.1.min.js” type=”text/javascript”></script> 2. Include Slidebar.js CDNs(JS and CSS) <script src=”https://cdnjs.cloudflare.com/ajax/libs/slidebars/2.0.2/slidebars.min.js” type=”text/javascript”></script><link rel=”stylesheet” href=”https://cdnjs.cloudflare.com/ajax/libs/slidebars/2.0.2/slidebars.min.css”> Now, we have included all the necessary CDNs, let’s move to the Original Code. Example: HTML <!DOCTYPE html><html> <head> <title>Slidebar Demo</title> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/slidebars/2.0.2/slidebars.min.css"> <script src= "https://code.jquery.com/jquery-3.5.1.min.js" type="text/javascript"> </script> <script src="https://cdnjs.cloudflare.com/ajax/libs/slidebars/2.0.2/slidebars.min.js" type="text/javascript"> </script></head> <body> <div canvas="container" class="slidebar-button"> <!-- Creating a heading --> <h2>Slidebar Demo</h2> <!-- Creating a button, clicking on which the left slidebar will open --> <button class="js-toggle-left"> Left Slide Button </button> </div> <div class="slidebar-content"> <div off-canvas="left-slidebar left reveal"> <ol> <li>Computer Science</li><br> <li>Electronics </li><br> <li>IT</li><br> </ol> </div> </div> <script> (function ($) { "use strict"; // Creating an instance of Slidebars var controller = new slidebars(); // Initialize Slidebars controller.init(); // left Slidebar controls $('.js-toggle-left').on('click', function (event) { event.stopPropagation(); controller.toggle('left-slidebar'); }); $(controller.events).on('opened', function () { $('[canvas="container"]') .addClass('js-close-any-slidebar'); }); $(controller.events).on('closed', function () { $('[canvas="container"]') .removeClass('js-close-any-slidebar'); }); $('body').on('click', '.js-close-any-slidebar', function (event) { event.stopPropagation(); controller.close(); }); })(jQuery); </script></body> </html> Output: Before click the Button: After click the Button: jQuery-Plugin Picked JQuery Technical Scripter Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Show and Hide div elements using radio buttons? How to prevent Body from scrolling when a modal is opened using jQuery ? jQuery | ajax() Method jQuery | removeAttr() with Examples How to get the value in an input text box using jQuery ? 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": 26978, "s": 26950, "text": "\n18 Jan, 2021" }, { "code": null, "e": 27310, "s": 26978, "text": "JQuery is a small, fast, rich JavaScript Library that is an optimized version of JavaScript. It provides us with a simple API that helps in HTML document traversal and manipulation, event handling, animation, and Ajax. jQuery provide us with a variety of plugins that can be implemented on the website, one of which is Slidebar.js." }, { "code": null, "e": 27495, "s": 27310, "text": "Slidebar.js: It is a jQuery Plugin that helps us to create a slidebar along with an animation. It helps in implementing mobile app-style revealing menus and sidebars into our website. " }, { "code": null, "e": 27550, "s": 27495, "text": "There are four types of slidebars that can be created:" }, { "code": null, "e": 27605, "s": 27550, "text": "Left SlidebarRight SlidebarTop SlidebarBottom Slidebar" }, { "code": null, "e": 27619, "s": 27605, "text": "Left Slidebar" }, { "code": null, "e": 27634, "s": 27619, "text": "Right Slidebar" }, { "code": null, "e": 27647, "s": 27634, "text": "Top Slidebar" }, { "code": null, "e": 27663, "s": 27647, "text": "Bottom Slidebar" }, { "code": null, "e": 27832, "s": 27663, "text": "In this article, we will be learning about how to implement a left sidebar on our website. But before that, we need to add some CDNs in order to make the slidebar work." }, { "code": null, "e": 27854, "s": 27832, "text": "1. Include jQuery CDN" }, { "code": null, "e": 27945, "s": 27854, "text": "<script src=”https://code.jquery.com/jquery-3.5.1.min.js” type=”text/javascript”></script>" }, { "code": null, "e": 27985, "s": 27945, "text": "2. Include Slidebar.js CDNs(JS and CSS)" }, { "code": null, "e": 28207, "s": 27985, "text": "<script src=”https://cdnjs.cloudflare.com/ajax/libs/slidebars/2.0.2/slidebars.min.js” type=”text/javascript”></script><link rel=”stylesheet” href=”https://cdnjs.cloudflare.com/ajax/libs/slidebars/2.0.2/slidebars.min.css”>" }, { "code": null, "e": 28286, "s": 28207, "text": "Now, we have included all the necessary CDNs, let’s move to the Original Code." }, { "code": null, "e": 28295, "s": 28286, "text": "Example:" }, { "code": null, "e": 28300, "s": 28295, "text": "HTML" }, { "code": "<!DOCTYPE html><html> <head> <title>Slidebar Demo</title> <link rel=\"stylesheet\" href=\"https://cdnjs.cloudflare.com/ajax/libs/slidebars/2.0.2/slidebars.min.css\"> <script src= \"https://code.jquery.com/jquery-3.5.1.min.js\" type=\"text/javascript\"> </script> <script src=\"https://cdnjs.cloudflare.com/ajax/libs/slidebars/2.0.2/slidebars.min.js\" type=\"text/javascript\"> </script></head> <body> <div canvas=\"container\" class=\"slidebar-button\"> <!-- Creating a heading --> <h2>Slidebar Demo</h2> <!-- Creating a button, clicking on which the left slidebar will open --> <button class=\"js-toggle-left\"> Left Slide Button </button> </div> <div class=\"slidebar-content\"> <div off-canvas=\"left-slidebar left reveal\"> <ol> <li>Computer Science</li><br> <li>Electronics </li><br> <li>IT</li><br> </ol> </div> </div> <script> (function ($) { \"use strict\"; // Creating an instance of Slidebars var controller = new slidebars(); // Initialize Slidebars controller.init(); // left Slidebar controls $('.js-toggle-left').on('click', function (event) { event.stopPropagation(); controller.toggle('left-slidebar'); }); $(controller.events).on('opened', function () { $('[canvas=\"container\"]') .addClass('js-close-any-slidebar'); }); $(controller.events).on('closed', function () { $('[canvas=\"container\"]') .removeClass('js-close-any-slidebar'); }); $('body').on('click', '.js-close-any-slidebar', function (event) { event.stopPropagation(); controller.close(); }); })(jQuery); </script></body> </html>", "e": 30318, "s": 28300, "text": null }, { "code": null, "e": 30326, "s": 30318, "text": "Output:" }, { "code": null, "e": 30351, "s": 30326, "text": "Before click the Button:" }, { "code": null, "e": 30375, "s": 30351, "text": "After click the Button:" }, { "code": null, "e": 30389, "s": 30375, "text": "jQuery-Plugin" }, { "code": null, "e": 30396, "s": 30389, "text": "Picked" }, { "code": null, "e": 30403, "s": 30396, "text": "JQuery" }, { "code": null, "e": 30422, "s": 30403, "text": "Technical Scripter" }, { "code": null, "e": 30439, "s": 30422, "text": "Web Technologies" }, { "code": null, "e": 30537, "s": 30439, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30592, "s": 30537, "text": "How to Show and Hide div elements using radio buttons?" }, { "code": null, "e": 30665, "s": 30592, "text": "How to prevent Body from scrolling when a modal is opened using jQuery ?" }, { "code": null, "e": 30688, "s": 30665, "text": "jQuery | ajax() Method" }, { "code": null, "e": 30724, "s": 30688, "text": "jQuery | removeAttr() with Examples" }, { "code": null, "e": 30781, "s": 30724, "text": "How to get the value in an input text box using jQuery ?" }, { "code": null, "e": 30821, "s": 30781, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 30854, "s": 30821, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 30899, "s": 30854, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 30942, "s": 30899, "text": "How to fetch data from an API in ReactJS ?" } ]
User Defined Literals in C++ - GeeksforGeeks
07 Sep, 2018 User Defined Literals (UDL) are added in C++ from C++11. Although, C++ provides literals for a variety of built-in types but these are limited. Examples of literals for built-in types : // Examples of classical literals for built-in types. 42 // int 2.4 // double 3.2F // float 'w' // char 32ULL // Unsigned long long 0xD0 // Hexadecimal unsigned "cd" // C-style string(const char[3]") Why do we use UDLs?Let us consider below example to understand need of UDLs. long double Weight = 2.3; // pounds? kilograms? grams? // With UDL, we attach units to the values which has // following advantages // 1) The code becomes readable. // 2) Conversion computations are done at compile time. weight = 2.3kg; ratio = 2.3kg/1.2lb; To compute the above ratio it is necessary to convert them to same units. UDLs help us to overcome unit translation cost. We can define user-defined literals for user-defined types and new form of literals for built-in types. They help to make constants in code more readable. The value of UDLs is substituted with the actual value defined in the code by the compiler at compile time. UDL’s don’t save much of coding time but more and more calculations can be shifted to compile-time for faster execution. Examples of User Defined Literals: "hello"s // string 4.3i // imaginary 101000111101001b // binary 53h // hours 234093270497230409328432840923849 // extended-precision UDLs are treated as a call to a literal operator. Only suffix form is supported. The name of the literal operator is operator “” followed by the suffix. Example 1: // C++ code to demonstrate working of user defined// literals (UDLs)#include<iostream>#include<iomanip>using namespace std; // user defined literals // KiloGramlong double operator"" _kg( long double x ){ return x*1000;} // Gramlong double operator"" _g( long double x ){ return x;} // MiliGramlong double operator"" _mg( long double x ){ return x / 1000;} // Driver codeint main(){ long double weight = 3.6_kg; cout << weight << endl; cout << setprecision(8) << ( weight + 2.3_mg ) << endl; cout << ( 32.3_kg / 2.0_g ) << endl; cout << ( 32.3_mg *2.0_g ) << endl; return 0;} 3600 3600.0023 16150 0.0646 Example 2: #include <iostream>#include <complex>using namespace std; // imaginary literalconstexpr complex <double> operator"" _i( long double d ){ return complex <double> { 0.0 , static_cast <double> ( d ) };} int main(){ complex <double> z = 3.0 + 4.0_i; complex <double> y = 2.3 + 5.0_i; cout << "z + y = " << z+y << endl; cout << "z * y = " << z*y << endl; cout << "abs(z) = " << abs(z) << endl; return 0;} z + y = (5.3,9) z * y = (-13.1,24.2) abs(z) = 5 Here, constexpr is used to enable compile time evaluation. Restriction:UDL can only work with the following parameters: char const* unsigned long long long double char const*, std::size_t wchar_t const*, std::size_t char16_t const*, std::size_t char32_t const*, std::size_t But return value can be of any types. This article is contributed by Mahima Varshney. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. Aman_1198 cpp-advanced C++ CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Operator Overloading in C++ Polymorphism in C++ Friend class and function in C++ Sorting a vector in C++ std::string class in C++ Inline Functions in C++ Pair in C++ Standard Template Library (STL) Array of Strings in C++ (5 Different Ways to Create) Convert string to char array in C++ List in C++ Standard Template Library (STL)
[ { "code": null, "e": 25477, "s": 25449, "text": "\n07 Sep, 2018" }, { "code": null, "e": 25621, "s": 25477, "text": "User Defined Literals (UDL) are added in C++ from C++11. Although, C++ provides literals for a variety of built-in types but these are limited." }, { "code": null, "e": 25663, "s": 25621, "text": "Examples of literals for built-in types :" }, { "code": null, "e": 25884, "s": 25663, "text": "// Examples of classical literals for built-in types.\n42 // int\n2.4 // double\n3.2F // float\n'w' // char\n32ULL // Unsigned long long\n0xD0 // Hexadecimal unsigned\n\"cd\" // C-style string(const char[3]\")" }, { "code": null, "e": 25961, "s": 25884, "text": "Why do we use UDLs?Let us consider below example to understand need of UDLs." }, { "code": null, "e": 26222, "s": 25961, "text": "long double Weight = 2.3; // pounds? kilograms? grams?\n\n// With UDL, we attach units to the values which has\n// following advantages\n// 1) The code becomes readable.\n// 2) Conversion computations are done at compile time. \nweight = 2.3kg;\nratio = 2.3kg/1.2lb;" }, { "code": null, "e": 26728, "s": 26222, "text": "To compute the above ratio it is necessary to convert them to same units. UDLs help us to overcome unit translation cost. We can define user-defined literals for user-defined types and new form of literals for built-in types. They help to make constants in code more readable. The value of UDLs is substituted with the actual value defined in the code by the compiler at compile time. UDL’s don’t save much of coding time but more and more calculations can be shifted to compile-time for faster execution." }, { "code": null, "e": 26763, "s": 26728, "text": "Examples of User Defined Literals:" }, { "code": null, "e": 26940, "s": 26763, "text": "\"hello\"s // string\n4.3i // imaginary\n101000111101001b // binary\n53h // hours\n234093270497230409328432840923849 // extended-precision" }, { "code": null, "e": 27093, "s": 26940, "text": "UDLs are treated as a call to a literal operator. Only suffix form is supported. The name of the literal operator is operator “” followed by the suffix." }, { "code": null, "e": 27104, "s": 27093, "text": "Example 1:" }, { "code": "// C++ code to demonstrate working of user defined// literals (UDLs)#include<iostream>#include<iomanip>using namespace std; // user defined literals // KiloGramlong double operator\"\" _kg( long double x ){ return x*1000;} // Gramlong double operator\"\" _g( long double x ){ return x;} // MiliGramlong double operator\"\" _mg( long double x ){ return x / 1000;} // Driver codeint main(){ long double weight = 3.6_kg; cout << weight << endl; cout << setprecision(8) << ( weight + 2.3_mg ) << endl; cout << ( 32.3_kg / 2.0_g ) << endl; cout << ( 32.3_mg *2.0_g ) << endl; return 0;}", "e": 27712, "s": 27104, "text": null }, { "code": null, "e": 27741, "s": 27712, "text": "3600\n3600.0023\n16150\n0.0646\n" }, { "code": null, "e": 27752, "s": 27741, "text": "Example 2:" }, { "code": "#include <iostream>#include <complex>using namespace std; // imaginary literalconstexpr complex <double> operator\"\" _i( long double d ){ return complex <double> { 0.0 , static_cast <double> ( d ) };} int main(){ complex <double> z = 3.0 + 4.0_i; complex <double> y = 2.3 + 5.0_i; cout << \"z + y = \" << z+y << endl; cout << \"z * y = \" << z*y << endl; cout << \"abs(z) = \" << abs(z) << endl; return 0;}", "e": 28175, "s": 27752, "text": null }, { "code": null, "e": 28224, "s": 28175, "text": "z + y = (5.3,9)\nz * y = (-13.1,24.2)\nabs(z) = 5\n" }, { "code": null, "e": 28283, "s": 28224, "text": "Here, constexpr is used to enable compile time evaluation." }, { "code": null, "e": 28344, "s": 28283, "text": "Restriction:UDL can only work with the following parameters:" }, { "code": null, "e": 28498, "s": 28344, "text": "char const*\nunsigned long long\nlong double\nchar const*, std::size_t\nwchar_t const*, std::size_t\nchar16_t const*, std::size_t\nchar32_t const*, std::size_t" }, { "code": null, "e": 28536, "s": 28498, "text": "But return value can be of any types." }, { "code": null, "e": 28839, "s": 28536, "text": "This article is contributed by Mahima Varshney. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks." }, { "code": null, "e": 28964, "s": 28839, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 28974, "s": 28964, "text": "Aman_1198" }, { "code": null, "e": 28987, "s": 28974, "text": "cpp-advanced" }, { "code": null, "e": 28991, "s": 28987, "text": "C++" }, { "code": null, "e": 28995, "s": 28991, "text": "CPP" }, { "code": null, "e": 29093, "s": 28995, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29121, "s": 29093, "text": "Operator Overloading in C++" }, { "code": null, "e": 29141, "s": 29121, "text": "Polymorphism in C++" }, { "code": null, "e": 29174, "s": 29141, "text": "Friend class and function in C++" }, { "code": null, "e": 29198, "s": 29174, "text": "Sorting a vector in C++" }, { "code": null, "e": 29223, "s": 29198, "text": "std::string class in C++" }, { "code": null, "e": 29247, "s": 29223, "text": "Inline Functions in C++" }, { "code": null, "e": 29291, "s": 29247, "text": "Pair in C++ Standard Template Library (STL)" }, { "code": null, "e": 29344, "s": 29291, "text": "Array of Strings in C++ (5 Different Ways to Create)" }, { "code": null, "e": 29380, "s": 29344, "text": "Convert string to char array in C++" } ]
Dynamic Meta Embeddings in Keras. Learn a valuable combination of... | by Marco Cerliani | Towards Data Science
Many NLP solutions make use of pre-trained word embeddings. The choice of which one to use is often related to the final performances and is achieved after a lot of trials and manual tuning. At Facebook AI Lab agreed that the best way to make this kind of selection is to let neural networks to figure out by themselves. They introduced dynamic meta-embeddings, a simple yet effective method for the supervised learning of embedding ensembles, which leads to state of the art performance within the same model class on a variety of tasks. This simple, but extremely efficient, method permits to learn a linear combination of a set of selected word embeddings which outperforms the naive concatenation of various embeddings. As mentioned, the authors proved the validity of their solution on various tasks in NLP domain. We limited ourselves to adopt these techniques in a text classification problem, where we have 2 pre-trained embeddings and want to combine them intelligently to boost the final performances. I found a valuable dataset on Kaggle containing the full text of articles (2225 in total) from BBC archive. There are 5 thematic areas to which news belong to: Our aims is to classify them correctly, and to do this we want to train our different types of embeddings, combine them intelligently and build on this merge our classifier. In the beginning, a standard cleaning procedure is applied to the raw corpus. As embedding model, I’ve selected the most common types: Word2Vec and FastText. We can train them easily with Gensim to ‘drag and drop’ them into Keras architecture (remember to maintain the same embedding size for every selected embedding framework). I compute this procedure carefully by hand in order to control the process of padding if needed: the Tokenizer object and the pad_sequence function from Keras make all the things easy. When we end with multiple trained embedding (also pretrained form of model like Glove or similar are perfect) and a sequential corpus we are ready to combine our weights. In the original paper two different kinds of techniques are introduced: Dynamic Meta-Embeddings (DME): the original embeddings are projected in a new space adding extra learnable weights through an LSTM encoder, following an attention mechanism. Then they are linearly combined with their original format. In Keras language: def DME(maxlen): inp = Input(shape=(maxlen, 100, 2)) x = Reshape((maxlen, -1))(inp) x = LSTM(2, return_sequences=True)(x) x = Activation('sigmoid')(x) x = Reshape((maxlen, 1, 2))(x) x = multiply([inp, x]) out = Lambda(lambda t: K.sum(t, axis=-1))(x) return Model(inp, out) Contextual Dynamic Meta-Embeddings (CDME): as above, the original embeddings are projected in a new space adding extra learnable weights; but now a context-dependent system is applied through a BiLSTM-Max encoder. In the end, the self-attention mechanism and the weighted combination with the original format are pursued. In Keras language (the MaxPooling merge in Bidirectional Layer of Keras is not supplied so we have to code it by ourself): def CDME(maxlen, latent_dim=2): inp = Input(shape=(maxlen, 100, 2)) x = Reshape((maxlen, -1))(inp) x = Bidirectional(LSTM(latent_dim, return_sequences=True))(x) x = Lambda(lambda t: [t[:,:,:int(latent_dim/2+1)], t[:,:,int(latent_dim/2+1):]])(x) x = Maximum()(x) x = Activation('sigmoid')(x) x = Reshape((maxlen, 1, 2))(x) x = multiply([inp, x]) out = Lambda(lambda t: K.sum(t, axis=-1))(x) return Model(inp, out) We recreate two general code blocks which carry out the embeddings combination through a dynamic procedure. Both solutions can be placed at the beginning of a network, immediately after the reading and concatenation of our embeddings. On them, we can stack normal layers for different purposes. In our case, we add some recurrent layers to correctly classify our news articles. We ended with these two architectures: For DME: concat_inp = Concat_Emb([embedding_matrix_w2v, embedding_matrix_ft], maxlen=max_len)dme = DME(max_len)x = dme(concat_inp.output)x = GRU(128, dropout=0.2, return_sequences=True)(x)x = GRU(32, dropout=0.2)(x)out = Dense(y.shape[1], activation='softmax')(x)dme_model = Model(concat_inp.input, out)dme_model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy']) For CDME: concat_inp = Concat_Emb([embedding_matrix_w2v, embedding_matrix_ft], maxlen=max_len)cdme = CDME(max_len)x = cdme(concat_inp.output)x = GRU(128, dropout=0.2, return_sequences=True)(x)x = GRU(32, dropout=0.2)(x)out = Dense(y.shape[1], activation='softmax')(x)cdme_model = Model(concat_inp.input, out)cdme_model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy']) Now we are ready to execute the training and see some results. Both models are able to achieve an overall accuracy of around 93% on test data with a great recall score for every class. Giving access to multiple types of embeddings (it doesn’t matter if they are pre-trained or built ad hoc), we allow a NN to learn which embeddings it prefers by predicting a weight for each embedding type (DME), optionally depending on the context (CDME). We make this happen in an NLP task for text classification, simply combining this procedure with the normal approach for this kind of problem. CHECK MY GITHUB REPO Keep in touch: Linkedin REFERENCES Dynamic Meta-Embeddings for Improved Sentence Representations: Douwe Kiela, Changhan Wang and Kyunghyun Cho; Facebook AI Research; New York University; CIFAR Global Scholar.
[ { "code": null, "e": 493, "s": 172, "text": "Many NLP solutions make use of pre-trained word embeddings. The choice of which one to use is often related to the final performances and is achieved after a lot of trials and manual tuning. At Facebook AI Lab agreed that the best way to make this kind of selection is to let neural networks to figure out by themselves." }, { "code": null, "e": 896, "s": 493, "text": "They introduced dynamic meta-embeddings, a simple yet effective method for the supervised learning of embedding ensembles, which leads to state of the art performance within the same model class on a variety of tasks. This simple, but extremely efficient, method permits to learn a linear combination of a set of selected word embeddings which outperforms the naive concatenation of various embeddings." }, { "code": null, "e": 1184, "s": 896, "text": "As mentioned, the authors proved the validity of their solution on various tasks in NLP domain. We limited ourselves to adopt these techniques in a text classification problem, where we have 2 pre-trained embeddings and want to combine them intelligently to boost the final performances." }, { "code": null, "e": 1344, "s": 1184, "text": "I found a valuable dataset on Kaggle containing the full text of articles (2225 in total) from BBC archive. There are 5 thematic areas to which news belong to:" }, { "code": null, "e": 2033, "s": 1344, "text": "Our aims is to classify them correctly, and to do this we want to train our different types of embeddings, combine them intelligently and build on this merge our classifier. In the beginning, a standard cleaning procedure is applied to the raw corpus. As embedding model, I’ve selected the most common types: Word2Vec and FastText. We can train them easily with Gensim to ‘drag and drop’ them into Keras architecture (remember to maintain the same embedding size for every selected embedding framework). I compute this procedure carefully by hand in order to control the process of padding if needed: the Tokenizer object and the pad_sequence function from Keras make all the things easy." }, { "code": null, "e": 2204, "s": 2033, "text": "When we end with multiple trained embedding (also pretrained form of model like Glove or similar are perfect) and a sequential corpus we are ready to combine our weights." }, { "code": null, "e": 2276, "s": 2204, "text": "In the original paper two different kinds of techniques are introduced:" }, { "code": null, "e": 2529, "s": 2276, "text": "Dynamic Meta-Embeddings (DME): the original embeddings are projected in a new space adding extra learnable weights through an LSTM encoder, following an attention mechanism. Then they are linearly combined with their original format. In Keras language:" }, { "code": null, "e": 2826, "s": 2529, "text": "def DME(maxlen): inp = Input(shape=(maxlen, 100, 2)) x = Reshape((maxlen, -1))(inp) x = LSTM(2, return_sequences=True)(x) x = Activation('sigmoid')(x) x = Reshape((maxlen, 1, 2))(x) x = multiply([inp, x]) out = Lambda(lambda t: K.sum(t, axis=-1))(x) return Model(inp, out)" }, { "code": null, "e": 3271, "s": 2826, "text": "Contextual Dynamic Meta-Embeddings (CDME): as above, the original embeddings are projected in a new space adding extra learnable weights; but now a context-dependent system is applied through a BiLSTM-Max encoder. In the end, the self-attention mechanism and the weighted combination with the original format are pursued. In Keras language (the MaxPooling merge in Bidirectional Layer of Keras is not supplied so we have to code it by ourself):" }, { "code": null, "e": 3741, "s": 3271, "text": "def CDME(maxlen, latent_dim=2): inp = Input(shape=(maxlen, 100, 2)) x = Reshape((maxlen, -1))(inp) x = Bidirectional(LSTM(latent_dim, return_sequences=True))(x) x = Lambda(lambda t: [t[:,:,:int(latent_dim/2+1)], t[:,:,int(latent_dim/2+1):]])(x) x = Maximum()(x) x = Activation('sigmoid')(x) x = Reshape((maxlen, 1, 2))(x) x = multiply([inp, x]) out = Lambda(lambda t: K.sum(t, axis=-1))(x) return Model(inp, out)" }, { "code": null, "e": 4158, "s": 3741, "text": "We recreate two general code blocks which carry out the embeddings combination through a dynamic procedure. Both solutions can be placed at the beginning of a network, immediately after the reading and concatenation of our embeddings. On them, we can stack normal layers for different purposes. In our case, we add some recurrent layers to correctly classify our news articles. We ended with these two architectures:" }, { "code": null, "e": 4167, "s": 4158, "text": "For DME:" }, { "code": null, "e": 4552, "s": 4167, "text": "concat_inp = Concat_Emb([embedding_matrix_w2v, embedding_matrix_ft], maxlen=max_len)dme = DME(max_len)x = dme(concat_inp.output)x = GRU(128, dropout=0.2, return_sequences=True)(x)x = GRU(32, dropout=0.2)(x)out = Dense(y.shape[1], activation='softmax')(x)dme_model = Model(concat_inp.input, out)dme_model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])" }, { "code": null, "e": 4562, "s": 4552, "text": "For CDME:" }, { "code": null, "e": 4952, "s": 4562, "text": "concat_inp = Concat_Emb([embedding_matrix_w2v, embedding_matrix_ft], maxlen=max_len)cdme = CDME(max_len)x = cdme(concat_inp.output)x = GRU(128, dropout=0.2, return_sequences=True)(x)x = GRU(32, dropout=0.2)(x)out = Dense(y.shape[1], activation='softmax')(x)cdme_model = Model(concat_inp.input, out)cdme_model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])" }, { "code": null, "e": 5137, "s": 4952, "text": "Now we are ready to execute the training and see some results. Both models are able to achieve an overall accuracy of around 93% on test data with a great recall score for every class." }, { "code": null, "e": 5536, "s": 5137, "text": "Giving access to multiple types of embeddings (it doesn’t matter if they are pre-trained or built ad hoc), we allow a NN to learn which embeddings it prefers by predicting a weight for each embedding type (DME), optionally depending on the context (CDME). We make this happen in an NLP task for text classification, simply combining this procedure with the normal approach for this kind of problem." }, { "code": null, "e": 5557, "s": 5536, "text": "CHECK MY GITHUB REPO" }, { "code": null, "e": 5581, "s": 5557, "text": "Keep in touch: Linkedin" }, { "code": null, "e": 5592, "s": 5581, "text": "REFERENCES" } ]
Python - Measuring Variance
In statistics, variance is a measure of how far a value in a data set lies from the mean value. In other words, it indicates how dispersed the values are. It is measured by using standard deviation. The other method commonly used is skewness. Both of these are calculated by using functions available in pandas library. Standard deviation is square root of variance. variance is the average of squared difference of values in a data set from the mean value. In python we calculate this value by using the function std() from pandas library. import pandas as pd #Create a Dictionary of series d = {'Name':pd.Series(['Tom','James','Ricky','Vin','Steve','Smith','Jack', 'Lee','Chanchal','Gasper','Naviya','Andres']), 'Age':pd.Series([25,26,25,23,30,25,23,34,40,30,25,46]), 'Rating':pd.Series([4.23,3.24,3.98,2.56,3.20,4.6,3.8,3.78,2.98,4.80,4.10,3.65])} #Create a DataFrame df = pd.DataFrame(d) # Calculate the standard deviation print df.std() Its output is as follows − Age 7.265527 Rating 0.661628 dtype: float64 It used to determine whether the data is symmetric or skewed. If the index is between -1 and 1, then the distribution is symmetric. If the index is no more than -1 then it is skewed to the left and if it is at least 1, then it is skewed to the right import pandas as pd #Create a Dictionary of series d = {'Name':pd.Series(['Tom','James','Ricky','Vin','Steve','Smith','Jack', 'Lee','Chanchal','Gasper','Naviya','Andres']), 'Age':pd.Series([25,26,25,23,30,25,23,34,40,30,25,46]), 'Rating':pd.Series([4.23,3.24,3.98,2.56,3.20,4.6,3.8,3.78,2.98,4.80,4.10,3.65])} #Create a DataFrame df = pd.DataFrame(d) print df.skew() Its output is as follows − Age 1.443490 Rating -0.153629 dtype: float64 So the distribution of age rating is symmetric while the distribution of age is skewed to the right. 187 Lectures 17.5 hours Malhar Lathkar 55 Lectures 8 hours Arnab Chakraborty 136 Lectures 11 hours In28Minutes Official 75 Lectures 13 hours Eduonix Learning Solutions 70 Lectures 8.5 hours Lets Kode It 63 Lectures 6 hours Abhilash Nelson Print Add Notes Bookmark this page
[ { "code": null, "e": 2772, "s": 2529, "text": "In statistics, variance is a measure of how far a value in a data set lies from the mean value. In other words, it indicates how dispersed the values are.\nIt is measured by using standard deviation. The other method commonly used is skewness." }, { "code": null, "e": 2850, "s": 2772, "text": "Both of these are calculated by using functions available in pandas library. " }, { "code": null, "e": 3071, "s": 2850, "text": "Standard deviation is square root of variance. variance is the average of squared difference of values in a data set from the mean value. In python we calculate this value\nby using the function std() from pandas library." }, { "code": null, "e": 3484, "s": 3071, "text": "import pandas as pd\n\n#Create a Dictionary of series\nd = {'Name':pd.Series(['Tom','James','Ricky','Vin','Steve','Smith','Jack',\n 'Lee','Chanchal','Gasper','Naviya','Andres']),\n 'Age':pd.Series([25,26,25,23,30,25,23,34,40,30,25,46]),\n 'Rating':pd.Series([4.23,3.24,3.98,2.56,3.20,4.6,3.8,3.78,2.98,4.80,4.10,3.65])}\n\n#Create a DataFrame\ndf = pd.DataFrame(d)\n\n# Calculate the standard deviation\nprint df.std()" }, { "code": null, "e": 3511, "s": 3484, "text": "Its output is as follows −" }, { "code": null, "e": 3564, "s": 3511, "text": "Age 7.265527\nRating 0.661628\ndtype: float64" }, { "code": null, "e": 3815, "s": 3564, "text": "It used to determine whether the data is symmetric or skewed. If the index is between -1 and 1, then the distribution is symmetric. If the index is no more than -1 \nthen it is skewed to the left and if it is at least 1, then it is skewed to the right" }, { "code": null, "e": 4193, "s": 3815, "text": "import pandas as pd\n\n#Create a Dictionary of series\nd = {'Name':pd.Series(['Tom','James','Ricky','Vin','Steve','Smith','Jack',\n 'Lee','Chanchal','Gasper','Naviya','Andres']),\n 'Age':pd.Series([25,26,25,23,30,25,23,34,40,30,25,46]),\n 'Rating':pd.Series([4.23,3.24,3.98,2.56,3.20,4.6,3.8,3.78,2.98,4.80,4.10,3.65])}\n\n#Create a DataFrame\ndf = pd.DataFrame(d)\nprint df.skew()" }, { "code": null, "e": 4220, "s": 4193, "text": "Its output is as follows −" }, { "code": null, "e": 4273, "s": 4220, "text": "Age 1.443490\nRating -0.153629\ndtype: float64" }, { "code": null, "e": 4374, "s": 4273, "text": "So the distribution of age rating is symmetric while the distribution of age is skewed to the right." }, { "code": null, "e": 4411, "s": 4374, "text": "\n 187 Lectures \n 17.5 hours \n" }, { "code": null, "e": 4427, "s": 4411, "text": " Malhar Lathkar" }, { "code": null, "e": 4460, "s": 4427, "text": "\n 55 Lectures \n 8 hours \n" }, { "code": null, "e": 4479, "s": 4460, "text": " Arnab Chakraborty" }, { "code": null, "e": 4514, "s": 4479, "text": "\n 136 Lectures \n 11 hours \n" }, { "code": null, "e": 4536, "s": 4514, "text": " In28Minutes Official" }, { "code": null, "e": 4570, "s": 4536, "text": "\n 75 Lectures \n 13 hours \n" }, { "code": null, "e": 4598, "s": 4570, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 4633, "s": 4598, "text": "\n 70 Lectures \n 8.5 hours \n" }, { "code": null, "e": 4647, "s": 4633, "text": " Lets Kode It" }, { "code": null, "e": 4680, "s": 4647, "text": "\n 63 Lectures \n 6 hours \n" }, { "code": null, "e": 4697, "s": 4680, "text": " Abhilash Nelson" }, { "code": null, "e": 4704, "s": 4697, "text": " Print" }, { "code": null, "e": 4715, "s": 4704, "text": " Add Notes" } ]
Check if any large number is divisible by 19 or not - GeeksforGeeks
23 Mar, 2021 Given a number, the task is to quickly check if the number is divisible by 19 or not. Examples: Input : x = 38 Output : Yes Input : x = 47 Output : No A solution to the problem is to extract the last digit and add 2 times of last digit to remaining number and repeat this process until a two digit number is obtained. If the obtained two digit number is divisible by 19, then the given number is divisible by 19.Approach: Extract the last digit of the number/truncated number every time Add 2*(last digit of the previous number) to the truncated number Repeat the above three steps as long as necessary. Illustration: 101156-->10115+2*6 = 10127-->1012+2*7=1026-->102+2*6=114 and 114=6*19, So 101156 is divisible by 19. Mathematical Proof : Let be any number such that =100a+10b+c . Now assume that is divisible by 19. Then 0 (mod 19) 100a+10b+c0 (mod 19) 10(10a+b)+c0 (mod 19) 10+c0 (mod 19)Now that we have separated the last digit from the number, we have to find a way to use it. Make the coefficient of 1. In other words, we have to find an integer such that n such that 10n1 mod 19. It can be observed that the smallest n which satisfies this property is 2 as 201 mod 19. Now we can multiply the original equation 10+c0 (mod 19) by 2 and simplify it: 20+2c0 (mod 19) +2c0 (mod 19) We have found out that if 0 (mod 19) then, +2c0 (mod 19). In other words, to check if a 3-digit number is divisible by 19, we can just remove the last digit, multiply it by 2, and then add to the rest of the two digits. C++ Java C# PHP Javascript // CPP Program to validate the above logic#include <bits/stdc++.h>using namespace std; // Function to check if the number// is divisible by 19 or notbool isDivisible(long long int n){ while (n / 100) // { // Extracting the last digit int d = n % 10; // Truncating the number n /= 10; // Adding twice the last digit // to the remaining number n += d * 2; } // return true if number is divisible by 19 return (n % 19 == 0);} // Driver codeint main(){ long long int n = 101156; if (isDivisible(n)) cout << "Yes" << endl; else cout << "No" << endl; return 0;} // Java Program to validate the above logicimport java.io.*; class GFG { // Function to check if the// number is divisible by 19 or notstatic boolean isDivisible(long n){ while (n / 100>0) { // Extracting the last digit long d = n % 10; // Truncating the number n /= 10; // Subtracting the five times the // last digit from the remaining number n += d * 2; } // Return n is divisible by 19 return (n % 19 == 0);} // Driver code public static void main (String[] args) { long n = 101156; if (isDivisible(n)) System.out.println( "Yes"); else System.out.println( "No"); }}// This code is contributed by Raj. Python 3 # Python 3 Program to check # if the number is divisible # by 19 or not # Function to check if the number # is divisible by 19 or not def isDivisible(n) : while (n // 100) : # Extracting the last digit d = n % 10 # Truncating the number n //= 10 # Adding twice the last digit # to the remaining number n += d * 2 # return true if number # is divisible by 19 return (n % 19 == 0) # Driver Code if __name__ == "__main__" : n = 101156 if (isDivisible(n)) : print("Yes" ) else : print("No") # This code is contributed # by ANKITRAI1 // C# Program to validate the// above logicusing System; class GFG{ // Function to check if the// number is divisible by 19 or notstatic bool isDivisible(long n){ while (n / 100 > 0) { // Extracting the last digit long d = n % 10; // Truncating the number n /= 10; // Subtracting the five times // the last digit from the // remaining number n += d * 2; } // Return n is divisible by 19 return (n % 19 == 0);} // Driver codepublic static void Main(){ long n = 101156; if (isDivisible(n)) Console.WriteLine( "Yes"); else Console.WriteLine( "No");}} // This code is contributed by ajit <?php// PHP Program to validate// the above logic // Function to check if the number// is divisible by 19 or notfunction isDivisible( $n){ while (1) { // Extracting the last digit $d = $n % 10; // Truncating the number $n = $n / 10; // Adding twice the last digit // to the remaining number $n = $n + $d * 2; if($n < 100) break; } // return true if number is // divisible by 19 return ($n % 19 == 0);} // Driver code$n = 38; if (isDivisible($n)) echo "Yes" ;else echo "No" ; // This code is contributed by ash264?> <script> // javascript Program to validate the above logic // Function to check if the// number is divisible by 19 or notfunction isDivisible(n){ while (parseInt(n / 100)>0) { // Extracting the last digit var d = n % 10; // Truncating the number n = parseInt(n/ 10); // Subtracting the five times the // last digit from the remaining number n += d * 2; } // Return n is divisible by 19 return (n % 19 == 0);} // Driver codevar n = 101156;if (isDivisible(n)) document.write( "Yes");else document.write( "No"); // This code is contributed by 29AjayKumar </script> Yes Note that the above program may not make a lot of sense as could simply do n % 19 to check for divisibility. The idea of this program is to validate the concept. Also, this might be an efficient approach if input number is large and given as string. ankthon ash264 R_Raj Sach_Code 29AjayKumar Articles Mathematical Mathematical Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Analysis of Algorithms | Set 1 (Asymptotic Analysis) Mutex vs Semaphore Time Complexity and Space Complexity SQL | Views Understanding "extern" keyword in C Program for Fibonacci numbers Write a program to print all permutations of a given string C++ Data Types Set in C++ Standard Template Library (STL) Program to find GCD or HCF of two numbers
[ { "code": null, "e": 25510, "s": 25482, "text": "\n23 Mar, 2021" }, { "code": null, "e": 25608, "s": 25510, "text": "Given a number, the task is to quickly check if the number is divisible by 19 or not. Examples: " }, { "code": null, "e": 25664, "s": 25608, "text": "Input : x = 38\nOutput : Yes\n\nInput : x = 47\nOutput : No" }, { "code": null, "e": 25937, "s": 25664, "text": "A solution to the problem is to extract the last digit and add 2 times of last digit to remaining number and repeat this process until a two digit number is obtained. If the obtained two digit number is divisible by 19, then the given number is divisible by 19.Approach: " }, { "code": null, "e": 26002, "s": 25937, "text": "Extract the last digit of the number/truncated number every time" }, { "code": null, "e": 26068, "s": 26002, "text": "Add 2*(last digit of the previous number) to the truncated number" }, { "code": null, "e": 26119, "s": 26068, "text": "Repeat the above three steps as long as necessary." }, { "code": null, "e": 26135, "s": 26119, "text": "Illustration: " }, { "code": null, "e": 26236, "s": 26135, "text": "101156-->10115+2*6 = 10127-->1012+2*7=1026-->102+2*6=114 and 114=6*19,\nSo 101156 is divisible by 19." }, { "code": null, "e": 27027, "s": 26238, "text": "Mathematical Proof : Let be any number such that =100a+10b+c . Now assume that is divisible by 19. Then 0 (mod 19) 100a+10b+c0 (mod 19) 10(10a+b)+c0 (mod 19) 10+c0 (mod 19)Now that we have separated the last digit from the number, we have to find a way to use it. Make the coefficient of 1. In other words, we have to find an integer such that n such that 10n1 mod 19. It can be observed that the smallest n which satisfies this property is 2 as 201 mod 19. Now we can multiply the original equation 10+c0 (mod 19) by 2 and simplify it: 20+2c0 (mod 19) +2c0 (mod 19) We have found out that if 0 (mod 19) then, +2c0 (mod 19). In other words, to check if a 3-digit number is divisible by 19, we can just remove the last digit, multiply it by 2, and then add to the rest of the two digits. " }, { "code": null, "e": 27033, "s": 27029, "text": "C++" }, { "code": null, "e": 27038, "s": 27033, "text": "Java" }, { "code": null, "e": 27041, "s": 27038, "text": "C#" }, { "code": null, "e": 27045, "s": 27041, "text": "PHP" }, { "code": null, "e": 27056, "s": 27045, "text": "Javascript" }, { "code": "// CPP Program to validate the above logic#include <bits/stdc++.h>using namespace std; // Function to check if the number// is divisible by 19 or notbool isDivisible(long long int n){ while (n / 100) // { // Extracting the last digit int d = n % 10; // Truncating the number n /= 10; // Adding twice the last digit // to the remaining number n += d * 2; } // return true if number is divisible by 19 return (n % 19 == 0);} // Driver codeint main(){ long long int n = 101156; if (isDivisible(n)) cout << \"Yes\" << endl; else cout << \"No\" << endl; return 0;}", "e": 27706, "s": 27056, "text": null }, { "code": "// Java Program to validate the above logicimport java.io.*; class GFG { // Function to check if the// number is divisible by 19 or notstatic boolean isDivisible(long n){ while (n / 100>0) { // Extracting the last digit long d = n % 10; // Truncating the number n /= 10; // Subtracting the five times the // last digit from the remaining number n += d * 2; } // Return n is divisible by 19 return (n % 19 == 0);} // Driver code public static void main (String[] args) { long n = 101156; if (isDivisible(n)) System.out.println( \"Yes\"); else System.out.println( \"No\"); }}// This code is contributed by Raj.", "e": 28409, "s": 27706, "text": null }, { "code": null, "e": 28419, "s": 28409, "text": "Python 3 " }, { "code": null, "e": 29112, "s": 28419, "text": "\n# Python 3 Program to check \n# if the number is divisible\n# by 19 or not \n\n# Function to check if the number \n# is divisible by 19 or not \ndef isDivisible(n) :\n \n while (n // 100) :\n \n # Extracting the last digit \n d = n % 10\n\n # Truncating the number \n n //= 10\n\n # Adding twice the last digit \n # to the remaining number \n n += d * 2\n\n # return true if number \n # is divisible by 19 \n return (n % 19 == 0) \n\n# Driver Code\nif __name__ == \"__main__\" :\n\n n = 101156\n \n if (isDivisible(n)) : \n print(\"Yes\" )\n \n else :\n print(\"No\") \n \n# This code is contributed \n# by ANKITRAI1\n\n" }, { "code": "// C# Program to validate the// above logicusing System; class GFG{ // Function to check if the// number is divisible by 19 or notstatic bool isDivisible(long n){ while (n / 100 > 0) { // Extracting the last digit long d = n % 10; // Truncating the number n /= 10; // Subtracting the five times // the last digit from the // remaining number n += d * 2; } // Return n is divisible by 19 return (n % 19 == 0);} // Driver codepublic static void Main(){ long n = 101156; if (isDivisible(n)) Console.WriteLine( \"Yes\"); else Console.WriteLine( \"No\");}} // This code is contributed by ajit", "e": 29803, "s": 29112, "text": null }, { "code": "<?php// PHP Program to validate// the above logic // Function to check if the number// is divisible by 19 or notfunction isDivisible( $n){ while (1) { // Extracting the last digit $d = $n % 10; // Truncating the number $n = $n / 10; // Adding twice the last digit // to the remaining number $n = $n + $d * 2; if($n < 100) break; } // return true if number is // divisible by 19 return ($n % 19 == 0);} // Driver code$n = 38; if (isDivisible($n)) echo \"Yes\" ;else echo \"No\" ; // This code is contributed by ash264?>", "e": 30421, "s": 29803, "text": null }, { "code": "<script> // javascript Program to validate the above logic // Function to check if the// number is divisible by 19 or notfunction isDivisible(n){ while (parseInt(n / 100)>0) { // Extracting the last digit var d = n % 10; // Truncating the number n = parseInt(n/ 10); // Subtracting the five times the // last digit from the remaining number n += d * 2; } // Return n is divisible by 19 return (n % 19 == 0);} // Driver codevar n = 101156;if (isDivisible(n)) document.write( \"Yes\");else document.write( \"No\"); // This code is contributed by 29AjayKumar </script>", "e": 31057, "s": 30421, "text": null }, { "code": null, "e": 31061, "s": 31057, "text": "Yes" }, { "code": null, "e": 31314, "s": 31063, "text": "Note that the above program may not make a lot of sense as could simply do n % 19 to check for divisibility. The idea of this program is to validate the concept. Also, this might be an efficient approach if input number is large and given as string. " }, { "code": null, "e": 31322, "s": 31314, "text": "ankthon" }, { "code": null, "e": 31329, "s": 31322, "text": "ash264" }, { "code": null, "e": 31335, "s": 31329, "text": "R_Raj" }, { "code": null, "e": 31345, "s": 31335, "text": "Sach_Code" }, { "code": null, "e": 31357, "s": 31345, "text": "29AjayKumar" }, { "code": null, "e": 31366, "s": 31357, "text": "Articles" }, { "code": null, "e": 31379, "s": 31366, "text": "Mathematical" }, { "code": null, "e": 31392, "s": 31379, "text": "Mathematical" }, { "code": null, "e": 31490, "s": 31392, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 31499, "s": 31490, "text": "Comments" }, { "code": null, "e": 31512, "s": 31499, "text": "Old Comments" }, { "code": null, "e": 31565, "s": 31512, "text": "Analysis of Algorithms | Set 1 (Asymptotic Analysis)" }, { "code": null, "e": 31584, "s": 31565, "text": "Mutex vs Semaphore" }, { "code": null, "e": 31621, "s": 31584, "text": "Time Complexity and Space Complexity" }, { "code": null, "e": 31633, "s": 31621, "text": "SQL | Views" }, { "code": null, "e": 31669, "s": 31633, "text": "Understanding \"extern\" keyword in C" }, { "code": null, "e": 31699, "s": 31669, "text": "Program for Fibonacci numbers" }, { "code": null, "e": 31759, "s": 31699, "text": "Write a program to print all permutations of a given string" }, { "code": null, "e": 31774, "s": 31759, "text": "C++ Data Types" }, { "code": null, "e": 31817, "s": 31774, "text": "Set in C++ Standard Template Library (STL)" } ]
HTML | canvas getImageData() Method - GeeksforGeeks
19 Oct, 2021 The getImageData() method is used to copy the pixel data for the specified rectangle on a canvas.There are 4 pieces of information for every pixel in an ImageData object i.e. the RGBA values: R denotes the red color. It ranges from 0 to 255. G denotes the green color. It ranges from 0 to 255. B denotes the blue color. It ranges from 0 to 255. A denotes the alpha channel. It also ranges from 0 to 255 i.e. 0 is transparent and 255 is fully visible Syntax: context.getImageData(x, y, width, height); Parameter Values: x: It is used to specify the x coordinate (in pixels) of the upper-left corner from where the copy to be started. y: It is used to specify the x coordinate (in pixels) of the upper-left corner from where the copy to be started. width: It is the width of the rectangular area to be copied. height: It is the height of the rectangular area to be copied. Example: html <!DOCTYPE html><html> <body> <h3 style="color:green; "> GeeksforGeeks</h3> <h3 style="color:green; "> GetImageData() Method</h3> <canvas id="gfgCanvas" width="300" height="300" style="border:1px solid ;"> </canvas> <script> var gfg = document.getElementById("gfgCanvas"); var context = gfg.getContext("2d"); context.fillStyle = "green"; context.fillRect(55, 50, 200, 100); function putImage() { // getImageData is used to copy the pixels var imageData = context.getImageData(55, 50, 200, 100); context.putImageData(imageData, 55, 170); } </script> <br> <button onclick="putImage()">GetImageData</button> </body> </html> Output: Before click: After click: Supported Browsers: Chrome Mozilla Firefox Internet Explorer 9.0 Opera Safari Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course. surinderdawra388 HTML-Methods HTML Web Technologies HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. REST API (Introduction) HTML Cheat Sheet - A Basic Guide to HTML How to Insert Form Data into Database using PHP ? Types of CSS (Cascading Style Sheet) How to position a div at the bottom of its container using CSS? Remove elements from a JavaScript Array Installation of Node.js on Linux Convert a string to an integer in JavaScript How to fetch data from an API in ReactJS ? Difference between var, let and const keywords in JavaScript
[ { "code": null, "e": 26553, "s": 26525, "text": "\n19 Oct, 2021" }, { "code": null, "e": 26747, "s": 26553, "text": "The getImageData() method is used to copy the pixel data for the specified rectangle on a canvas.There are 4 pieces of information for every pixel in an ImageData object i.e. the RGBA values: " }, { "code": null, "e": 26797, "s": 26747, "text": "R denotes the red color. It ranges from 0 to 255." }, { "code": null, "e": 26849, "s": 26797, "text": "G denotes the green color. It ranges from 0 to 255." }, { "code": null, "e": 26900, "s": 26849, "text": "B denotes the blue color. It ranges from 0 to 255." }, { "code": null, "e": 27005, "s": 26900, "text": "A denotes the alpha channel. It also ranges from 0 to 255 i.e. 0 is transparent and 255 is fully visible" }, { "code": null, "e": 27015, "s": 27005, "text": "Syntax: " }, { "code": null, "e": 27058, "s": 27015, "text": "context.getImageData(x, y, width, height);" }, { "code": null, "e": 27078, "s": 27058, "text": "Parameter Values: " }, { "code": null, "e": 27192, "s": 27078, "text": "x: It is used to specify the x coordinate (in pixels) of the upper-left corner from where the copy to be started." }, { "code": null, "e": 27306, "s": 27192, "text": "y: It is used to specify the x coordinate (in pixels) of the upper-left corner from where the copy to be started." }, { "code": null, "e": 27367, "s": 27306, "text": "width: It is the width of the rectangular area to be copied." }, { "code": null, "e": 27430, "s": 27367, "text": "height: It is the height of the rectangular area to be copied." }, { "code": null, "e": 27441, "s": 27430, "text": "Example: " }, { "code": null, "e": 27446, "s": 27441, "text": "html" }, { "code": "<!DOCTYPE html><html> <body> <h3 style=\"color:green; \"> GeeksforGeeks</h3> <h3 style=\"color:green; \"> GetImageData() Method</h3> <canvas id=\"gfgCanvas\" width=\"300\" height=\"300\" style=\"border:1px solid ;\"> </canvas> <script> var gfg = document.getElementById(\"gfgCanvas\"); var context = gfg.getContext(\"2d\"); context.fillStyle = \"green\"; context.fillRect(55, 50, 200, 100); function putImage() { // getImageData is used to copy the pixels var imageData = context.getImageData(55, 50, 200, 100); context.putImageData(imageData, 55, 170); } </script> <br> <button onclick=\"putImage()\">GetImageData</button> </body> </html>", "e": 28201, "s": 27446, "text": null }, { "code": null, "e": 28225, "s": 28201, "text": "Output: Before click: " }, { "code": null, "e": 28240, "s": 28225, "text": "After click: " }, { "code": null, "e": 28262, "s": 28240, "text": "Supported Browsers: " }, { "code": null, "e": 28269, "s": 28262, "text": "Chrome" }, { "code": null, "e": 28285, "s": 28269, "text": "Mozilla Firefox" }, { "code": null, "e": 28307, "s": 28285, "text": "Internet Explorer 9.0" }, { "code": null, "e": 28313, "s": 28307, "text": "Opera" }, { "code": null, "e": 28320, "s": 28313, "text": "Safari" }, { "code": null, "e": 28459, "s": 28322, "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": 28476, "s": 28459, "text": "surinderdawra388" }, { "code": null, "e": 28489, "s": 28476, "text": "HTML-Methods" }, { "code": null, "e": 28494, "s": 28489, "text": "HTML" }, { "code": null, "e": 28511, "s": 28494, "text": "Web Technologies" }, { "code": null, "e": 28516, "s": 28511, "text": "HTML" }, { "code": null, "e": 28614, "s": 28516, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28638, "s": 28614, "text": "REST API (Introduction)" }, { "code": null, "e": 28679, "s": 28638, "text": "HTML Cheat Sheet - A Basic Guide to HTML" }, { "code": null, "e": 28729, "s": 28679, "text": "How to Insert Form Data into Database using PHP ?" }, { "code": null, "e": 28766, "s": 28729, "text": "Types of CSS (Cascading Style Sheet)" }, { "code": null, "e": 28830, "s": 28766, "text": "How to position a div at the bottom of its container using CSS?" }, { "code": null, "e": 28870, "s": 28830, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 28903, "s": 28870, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 28948, "s": 28903, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 28991, "s": 28948, "text": "How to fetch data from an API in ReactJS ?" } ]
Add the given digit to a number stored in a linked list - GeeksforGeeks
06 Jul, 2021 Given a linked list which represents an integer number where every node is a digit if the represented integer. The task is to add a given digit N to the represented integer. Examples: Input: 9 -> 9 -> 3 -> NULL, N = 7 Output: 9 -> 9 -> 3 -> NULL 1 -> 0 -> 0 -> 0 -> NULL Input: 2 -> 9 -> 9 -> NULL, N = 5 Output: 2 -> 9 -> 9 -> NULL 3 -> 0 -> 4 -> NULL Approach: We have already discussed the approach for adding 1 to a number stored in linked list int this article but the code requires reversal of the linked list. In this post, we have extended the problem to adding any digit to the number stored in a linked list and achieving the same without reversal or recursion. The idea is to traverse the list and while traversing maintain a pointer to the last node whose value is less than 9. This is because we are adding a single digit to the number stored in the linked list. So, the maximum value of carry (if present) can be 1. Suppose we start propagating the carry from the least significant digit towards most significant digit, then the propagation will stop as soon as it finds a number less than 9. After the complete traversal of the list in this manner, we have finally reached the last node of the linked list and also maintained a pointer to the latest node whose value is less than 9. Two cases can arise: There can be overflow after adding the number in the last digit i.e. value at the node is greater than 9.No overflow i.e. after adding the value at the node is less than 10. There can be overflow after adding the number in the last digit i.e. value at the node is greater than 9. No overflow i.e. after adding the value at the node is less than 10. In the first case, we have to propagate the carry from the latest node whose value is less than 9 to the last node.In the second case, we don’t have to do anything else. Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ implementation of the approach#include <iostream>using namespace std; // Node structure containing data// and pointer to the next Nodestruct node { int key; node* next; node(int n) { key = n; next = NULL; }}; // Linked list classclass LinkedList { node* head; public: // Default constructor for // creating empty list LinkedList(); // Insert a node in linked list void insert(node* n); // Adding a single digit to the list void addDigit(int n); // Print the linked list void printList();}; LinkedList::LinkedList(){ // Empty List head = NULL;} // Function to insert a node at the// head of the linked listvoid LinkedList::insert(node* n){ // Empty List if (head == NULL) head = n; // Insert in the beginning of the list else { n->next = head; head = n; }} // Function to print the linked listvoid LinkedList::printList(){ node* ptr = head; while (ptr) { cout << ptr->key << " -> "; ptr = ptr->next; } cout << "NULL" << endl;} // Function to add a digit to the integer// represented as a linked listvoid LinkedList::addDigit(int n){ // To keep track of the last node // whose value is less than 9 node* lastNode = NULL; node* curr = head; while (curr->next) { // If found a node with value // less than 9 if (curr->key < 9) lastNode = curr; // Otherwise keep traversing // the list till end curr = curr->next; } // Add the given digit to the last node curr->key = curr->key + n; // In case of overflow in the last node if (curr->key > 9) { curr->key = curr->key % 10; // If the list is of the // form 9 -> 9 -> 9 -> ... if (lastNode == NULL) { // Insert a node at the beginning as // there would be overflow in the // head in this case insert(new node(1)); // Adjust the lastNode pointer to // propagate the carry effect to // all the nodes of the list lastNode = head->next; } // Forward propagate carry effect while (lastNode != curr) { lastNode->key = (lastNode->key + 1) % 10; lastNode = lastNode->next; } }} // Driver codeint main(){ // Creating the linked list LinkedList* l1 = new LinkedList(); // Adding elements to the linked list l1->insert(new node(9)); l1->insert(new node(9)); l1->insert(new node(1)); // Printing the original list l1->printList(); // Adding the digit l1->addDigit(5); // Printing the modified list l1->printList(); return 0;} // Java implementation of the approach // Node structure containing data// and pointer to the next Nodeclass node{ int key; node next; node(int n) { key = n; next = null; }}; // Linked list classclass LinkedList{ static node head; // Default constructor for // creating empty list public LinkedList() { // Empty List head = null; } // Function to insert a node at the // head of the linked list void insert(node n) { // Empty List if (head == null) head = n; // Insert in the beginning of the list else { n.next = head; head = n; } } // Function to print the linked list void printList() { node ptr = head; while (ptr != null) { System.out.print(ptr.key + "->"); ptr = ptr.next; } System.out.print("null" + "\n"); } // Function to add a digit to the integer // represented as a linked list void addDigit(int n) { // To keep track of the last node // whose value is less than 9 node lastNode = null; node curr = head; while (curr.next != null) { // If found a node with value // less than 9 if (curr.key < 9) lastNode = curr; // Otherwise keep traversing // the list till end curr = curr.next; } // Add the given digit to the last node curr.key = curr.key + n; // In case of overflow in the last node if (curr.key > 9) { curr.key = curr.key % 10; // If the list is of the // form 9.9.9.... if (lastNode == null) { // Insert a node at the beginning as // there would be overflow in the // head in this case insert(new node(1)); // Adjust the lastNode pointer to // propagate the carry effect to // all the nodes of the list lastNode = head.next; } // Forward propagate carry effect while (lastNode != curr) { lastNode.key = (lastNode.key + 1) % 10; lastNode = lastNode.next; } } } // Driver code public static void main(String[] args) { // Creating the linked list LinkedList l1 = new LinkedList(); // Adding elements to the linked list l1.insert(new node(9)); l1.insert(new node(9)); l1.insert(new node(1)); // Printing the original list l1.printList(); // Adding the digit l1.addDigit(5); // Printing the modified list l1.printList(); }} // This code is contributed by Rajput-Ji # Python3 implementation of the approach # Node structure containing data# and pointer to the next Nodeclass node: def __init__(self, key): self.key = key self.next = None # Linked list classclass LinkedList: def __init__(self): self.head = None # Function to insert a node at the # head of the linked list def insert(self, n): # Empty List if (self.head == None): self.head = n # Insert in the beginning of the list else: n.next = self.head; self.head = n # Function to print the linked list def printList(self): ptr = self.head while (ptr != None): print(ptr.key, end = ' -> ') ptr = ptr.next print('NULL') # Function to add a digit to the integer # represented as a linked list def addDigit(self, n): # To keep track of the last node # whose value is less than 9 lastNode = None curr = self.head while (curr.next != None): # If found a node with value # less than 9 if (curr.key < 9): lastNode = curr # Otherwise keep traversing # the list till end curr = curr.next # Add the given digit to the last node curr.key = curr.key + n # In case of overflow in the last node if (curr.key > 9): curr.key = curr.key % 10 # If the list is of the # form 9 . 9 . 9 . ... if (lastNode == None): # Insert a node at the beginning as # there would be overflow in the # self.head in this case self.insert(node(1)) # Adjust the lastNode pointer to # propagate the carry effect to # all the nodes of the list lastNode = self.head.next # Forward propagate carry effect while (lastNode != curr): lastNode.key = (lastNode.key + 1) % 10 lastNode = lastNode.next # Driver codeif __name__=='__main__': # Creating the linked list l1 = LinkedList() # Adding elements to the linked list l1.insert(node(9)) l1.insert(node(9)) l1.insert(node(1)) # Printing the original list l1.printList() # Adding the digit l1.addDigit(5) # Printing the modified list l1.printList() # This code is contributed by rutvik_56 // C# implementation of the approachusing System; // Node structure containing data// and pointer to the next Nodepublic class node{ public int key; public node next; public node(int n) { key = n; next = null; }}; // Linked list classpublic class List{ static node head; // Default constructor for // creating empty list public List() { // Empty List head = null; } // Function to insert a node at the // head of the linked list void insert(node n) { // Empty List if (head == null) head = n; // Insert in the beginning of the list else { n.next = head; head = n; } } // Function to print the linked list void printList() { node ptr = head; while (ptr != null) { Console.Write(ptr.key + "->"); ptr = ptr.next; } Console.Write("null" + "\n"); } // Function to add a digit to the integer // represented as a linked list void addDigit(int n) { // To keep track of the last node // whose value is less than 9 node lastNode = null; node curr = head; while (curr.next != null) { // If found a node with value // less than 9 if (curr.key < 9) lastNode = curr; // Otherwise keep traversing // the list till end curr = curr.next; } // Add the given digit to the last node curr.key = curr.key + n; // In case of overflow in the last node if (curr.key > 9) { curr.key = curr.key % 10; // If the list is of the // form 9.9.9.... if (lastNode == null) { // Insert a node at the beginning as // there would be overflow in the // head in this case insert(new node(1)); // Adjust the lastNode pointer to // propagate the carry effect to // all the nodes of the list lastNode = head.next; } // Forward propagate carry effect while (lastNode != curr) { lastNode.key = (lastNode.key + 1) % 10; lastNode = lastNode.next; } } } // Driver code public static void Main(String[] args) { // Creating the linked list List l1 = new List(); // Adding elements to the linked list l1.insert(new node(9)); l1.insert(new node(9)); l1.insert(new node(1)); // Printing the original list l1.printList(); // Adding the digit l1.addDigit(5); // Printing the modified list l1.printList(); }} // This code is contributed by 29AjayKumar <script> // JavaScript implementation of the approach // Node structure containing data// and pointer to the next Nodeclass node{ constructor(n) { this.key = n; this.next = null }}; // Linked list classvar head = null; // Default constructor for// creating empty listfunction List(){ // Empty List head = null;}// Function to insert a node at the// head of the linked listfunction insert(n){ // Empty List if (head == null) head = n; // Insert in the beginning of the list else { n.next = head; head = n; }}// Function to print the linked listfunction printList(){ var ptr = head; while (ptr != null) { document.write(ptr.key + " -> "); ptr = ptr.next; } document.write("null" + "<br>");}// Function to add a digit to the integer// represented as a linked listfunction addDigit(n){ // To keep track of the last node // whose value is less than 9 var lastNode = null; var curr = head; while (curr.next != null) { // If found a node with value // less than 9 if (curr.key < 9) lastNode = curr; // Otherwise keep traversing // the list till end curr = curr.next; } // Add the given digit to the last node curr.key = curr.key + n; // In case of overflow in the last node if (curr.key > 9) { curr.key = curr.key % 10; // If the list is of the // form 9.9.9.... if (lastNode == null) { // Insert a node at the beginning as // there would be overflow in the // head in this case insert(new node(1)); // Adjust the lastNode pointer to // propagate the carry effect to // all the nodes of the list lastNode = head.next; } // Forward propagate carry effect while (lastNode != curr) { lastNode.key = (lastNode.key + 1) % 10; lastNode = lastNode.next; } }}// Driver code// Adding elements to the linked listinsert(new node(9));insert(new node(9));insert(new node(1));// Printing the original listprintList();// Adding the digitaddDigit(5);// Printing the modified listprintList(); </script> 1 -> 9 -> 9 -> NULL 2 -> 0 -> 4 -> NULL Rajput-Ji 29AjayKumar arorakashish0911 rutvik_56 itsok simmytarika5 Microsoft Linked List Microsoft Linked List Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Circular Linked List | Set 2 (Traversal) Swap nodes in a linked list without swapping data Circular Singly Linked List | Insertion Given a linked list which is sorted, how will you insert in sorted way Program to implement Singly Linked List in C++ using class Delete a node in a Doubly Linked List Real-time application of Data Structures Insert a node at a specific position in a linked list Linked List Implementation in C# Priority Queue using Linked List
[ { "code": null, "e": 25058, "s": 25030, "text": "\n06 Jul, 2021" }, { "code": null, "e": 25232, "s": 25058, "text": "Given a linked list which represents an integer number where every node is a digit if the represented integer. The task is to add a given digit N to the represented integer." }, { "code": null, "e": 25243, "s": 25232, "text": "Examples: " }, { "code": null, "e": 25330, "s": 25243, "text": "Input: 9 -> 9 -> 3 -> NULL, N = 7 Output: 9 -> 9 -> 3 -> NULL 1 -> 0 -> 0 -> 0 -> NULL" }, { "code": null, "e": 25413, "s": 25330, "text": "Input: 2 -> 9 -> 9 -> NULL, N = 5 Output: 2 -> 9 -> 9 -> NULL 3 -> 0 -> 4 -> NULL " }, { "code": null, "e": 25733, "s": 25413, "text": "Approach: We have already discussed the approach for adding 1 to a number stored in linked list int this article but the code requires reversal of the linked list. In this post, we have extended the problem to adding any digit to the number stored in a linked list and achieving the same without reversal or recursion. " }, { "code": null, "e": 26169, "s": 25733, "text": "The idea is to traverse the list and while traversing maintain a pointer to the last node whose value is less than 9. This is because we are adding a single digit to the number stored in the linked list. So, the maximum value of carry (if present) can be 1. Suppose we start propagating the carry from the least significant digit towards most significant digit, then the propagation will stop as soon as it finds a number less than 9. " }, { "code": null, "e": 26382, "s": 26169, "text": "After the complete traversal of the list in this manner, we have finally reached the last node of the linked list and also maintained a pointer to the latest node whose value is less than 9. Two cases can arise: " }, { "code": null, "e": 26556, "s": 26382, "text": "There can be overflow after adding the number in the last digit i.e. value at the node is greater than 9.No overflow i.e. after adding the value at the node is less than 10." }, { "code": null, "e": 26662, "s": 26556, "text": "There can be overflow after adding the number in the last digit i.e. value at the node is greater than 9." }, { "code": null, "e": 26731, "s": 26662, "text": "No overflow i.e. after adding the value at the node is less than 10." }, { "code": null, "e": 26902, "s": 26731, "text": "In the first case, we have to propagate the carry from the latest node whose value is less than 9 to the last node.In the second case, we don’t have to do anything else. " }, { "code": null, "e": 26954, "s": 26902, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 26958, "s": 26954, "text": "C++" }, { "code": null, "e": 26963, "s": 26958, "text": "Java" }, { "code": null, "e": 26971, "s": 26963, "text": "Python3" }, { "code": null, "e": 26974, "s": 26971, "text": "C#" }, { "code": null, "e": 26985, "s": 26974, "text": "Javascript" }, { "code": "// C++ implementation of the approach#include <iostream>using namespace std; // Node structure containing data// and pointer to the next Nodestruct node { int key; node* next; node(int n) { key = n; next = NULL; }}; // Linked list classclass LinkedList { node* head; public: // Default constructor for // creating empty list LinkedList(); // Insert a node in linked list void insert(node* n); // Adding a single digit to the list void addDigit(int n); // Print the linked list void printList();}; LinkedList::LinkedList(){ // Empty List head = NULL;} // Function to insert a node at the// head of the linked listvoid LinkedList::insert(node* n){ // Empty List if (head == NULL) head = n; // Insert in the beginning of the list else { n->next = head; head = n; }} // Function to print the linked listvoid LinkedList::printList(){ node* ptr = head; while (ptr) { cout << ptr->key << \" -> \"; ptr = ptr->next; } cout << \"NULL\" << endl;} // Function to add a digit to the integer// represented as a linked listvoid LinkedList::addDigit(int n){ // To keep track of the last node // whose value is less than 9 node* lastNode = NULL; node* curr = head; while (curr->next) { // If found a node with value // less than 9 if (curr->key < 9) lastNode = curr; // Otherwise keep traversing // the list till end curr = curr->next; } // Add the given digit to the last node curr->key = curr->key + n; // In case of overflow in the last node if (curr->key > 9) { curr->key = curr->key % 10; // If the list is of the // form 9 -> 9 -> 9 -> ... if (lastNode == NULL) { // Insert a node at the beginning as // there would be overflow in the // head in this case insert(new node(1)); // Adjust the lastNode pointer to // propagate the carry effect to // all the nodes of the list lastNode = head->next; } // Forward propagate carry effect while (lastNode != curr) { lastNode->key = (lastNode->key + 1) % 10; lastNode = lastNode->next; } }} // Driver codeint main(){ // Creating the linked list LinkedList* l1 = new LinkedList(); // Adding elements to the linked list l1->insert(new node(9)); l1->insert(new node(9)); l1->insert(new node(1)); // Printing the original list l1->printList(); // Adding the digit l1->addDigit(5); // Printing the modified list l1->printList(); return 0;}", "e": 29690, "s": 26985, "text": null }, { "code": "// Java implementation of the approach // Node structure containing data// and pointer to the next Nodeclass node{ int key; node next; node(int n) { key = n; next = null; }}; // Linked list classclass LinkedList{ static node head; // Default constructor for // creating empty list public LinkedList() { // Empty List head = null; } // Function to insert a node at the // head of the linked list void insert(node n) { // Empty List if (head == null) head = n; // Insert in the beginning of the list else { n.next = head; head = n; } } // Function to print the linked list void printList() { node ptr = head; while (ptr != null) { System.out.print(ptr.key + \"->\"); ptr = ptr.next; } System.out.print(\"null\" + \"\\n\"); } // Function to add a digit to the integer // represented as a linked list void addDigit(int n) { // To keep track of the last node // whose value is less than 9 node lastNode = null; node curr = head; while (curr.next != null) { // If found a node with value // less than 9 if (curr.key < 9) lastNode = curr; // Otherwise keep traversing // the list till end curr = curr.next; } // Add the given digit to the last node curr.key = curr.key + n; // In case of overflow in the last node if (curr.key > 9) { curr.key = curr.key % 10; // If the list is of the // form 9.9.9.... if (lastNode == null) { // Insert a node at the beginning as // there would be overflow in the // head in this case insert(new node(1)); // Adjust the lastNode pointer to // propagate the carry effect to // all the nodes of the list lastNode = head.next; } // Forward propagate carry effect while (lastNode != curr) { lastNode.key = (lastNode.key + 1) % 10; lastNode = lastNode.next; } } } // Driver code public static void main(String[] args) { // Creating the linked list LinkedList l1 = new LinkedList(); // Adding elements to the linked list l1.insert(new node(9)); l1.insert(new node(9)); l1.insert(new node(1)); // Printing the original list l1.printList(); // Adding the digit l1.addDigit(5); // Printing the modified list l1.printList(); }} // This code is contributed by Rajput-Ji", "e": 32572, "s": 29690, "text": null }, { "code": "# Python3 implementation of the approach # Node structure containing data# and pointer to the next Nodeclass node: def __init__(self, key): self.key = key self.next = None # Linked list classclass LinkedList: def __init__(self): self.head = None # Function to insert a node at the # head of the linked list def insert(self, n): # Empty List if (self.head == None): self.head = n # Insert in the beginning of the list else: n.next = self.head; self.head = n # Function to print the linked list def printList(self): ptr = self.head while (ptr != None): print(ptr.key, end = ' -> ') ptr = ptr.next print('NULL') # Function to add a digit to the integer # represented as a linked list def addDigit(self, n): # To keep track of the last node # whose value is less than 9 lastNode = None curr = self.head while (curr.next != None): # If found a node with value # less than 9 if (curr.key < 9): lastNode = curr # Otherwise keep traversing # the list till end curr = curr.next # Add the given digit to the last node curr.key = curr.key + n # In case of overflow in the last node if (curr.key > 9): curr.key = curr.key % 10 # If the list is of the # form 9 . 9 . 9 . ... if (lastNode == None): # Insert a node at the beginning as # there would be overflow in the # self.head in this case self.insert(node(1)) # Adjust the lastNode pointer to # propagate the carry effect to # all the nodes of the list lastNode = self.head.next # Forward propagate carry effect while (lastNode != curr): lastNode.key = (lastNode.key + 1) % 10 lastNode = lastNode.next # Driver codeif __name__=='__main__': # Creating the linked list l1 = LinkedList() # Adding elements to the linked list l1.insert(node(9)) l1.insert(node(9)) l1.insert(node(1)) # Printing the original list l1.printList() # Adding the digit l1.addDigit(5) # Printing the modified list l1.printList() # This code is contributed by rutvik_56", "e": 35131, "s": 32572, "text": null }, { "code": "// C# implementation of the approachusing System; // Node structure containing data// and pointer to the next Nodepublic class node{ public int key; public node next; public node(int n) { key = n; next = null; }}; // Linked list classpublic class List{ static node head; // Default constructor for // creating empty list public List() { // Empty List head = null; } // Function to insert a node at the // head of the linked list void insert(node n) { // Empty List if (head == null) head = n; // Insert in the beginning of the list else { n.next = head; head = n; } } // Function to print the linked list void printList() { node ptr = head; while (ptr != null) { Console.Write(ptr.key + \"->\"); ptr = ptr.next; } Console.Write(\"null\" + \"\\n\"); } // Function to add a digit to the integer // represented as a linked list void addDigit(int n) { // To keep track of the last node // whose value is less than 9 node lastNode = null; node curr = head; while (curr.next != null) { // If found a node with value // less than 9 if (curr.key < 9) lastNode = curr; // Otherwise keep traversing // the list till end curr = curr.next; } // Add the given digit to the last node curr.key = curr.key + n; // In case of overflow in the last node if (curr.key > 9) { curr.key = curr.key % 10; // If the list is of the // form 9.9.9.... if (lastNode == null) { // Insert a node at the beginning as // there would be overflow in the // head in this case insert(new node(1)); // Adjust the lastNode pointer to // propagate the carry effect to // all the nodes of the list lastNode = head.next; } // Forward propagate carry effect while (lastNode != curr) { lastNode.key = (lastNode.key + 1) % 10; lastNode = lastNode.next; } } } // Driver code public static void Main(String[] args) { // Creating the linked list List l1 = new List(); // Adding elements to the linked list l1.insert(new node(9)); l1.insert(new node(9)); l1.insert(new node(1)); // Printing the original list l1.printList(); // Adding the digit l1.addDigit(5); // Printing the modified list l1.printList(); }} // This code is contributed by 29AjayKumar", "e": 38031, "s": 35131, "text": null }, { "code": "<script> // JavaScript implementation of the approach // Node structure containing data// and pointer to the next Nodeclass node{ constructor(n) { this.key = n; this.next = null }}; // Linked list classvar head = null; // Default constructor for// creating empty listfunction List(){ // Empty List head = null;}// Function to insert a node at the// head of the linked listfunction insert(n){ // Empty List if (head == null) head = n; // Insert in the beginning of the list else { n.next = head; head = n; }}// Function to print the linked listfunction printList(){ var ptr = head; while (ptr != null) { document.write(ptr.key + \" -> \"); ptr = ptr.next; } document.write(\"null\" + \"<br>\");}// Function to add a digit to the integer// represented as a linked listfunction addDigit(n){ // To keep track of the last node // whose value is less than 9 var lastNode = null; var curr = head; while (curr.next != null) { // If found a node with value // less than 9 if (curr.key < 9) lastNode = curr; // Otherwise keep traversing // the list till end curr = curr.next; } // Add the given digit to the last node curr.key = curr.key + n; // In case of overflow in the last node if (curr.key > 9) { curr.key = curr.key % 10; // If the list is of the // form 9.9.9.... if (lastNode == null) { // Insert a node at the beginning as // there would be overflow in the // head in this case insert(new node(1)); // Adjust the lastNode pointer to // propagate the carry effect to // all the nodes of the list lastNode = head.next; } // Forward propagate carry effect while (lastNode != curr) { lastNode.key = (lastNode.key + 1) % 10; lastNode = lastNode.next; } }}// Driver code// Adding elements to the linked listinsert(new node(9));insert(new node(9));insert(new node(1));// Printing the original listprintList();// Adding the digitaddDigit(5);// Printing the modified listprintList(); </script>", "e": 40285, "s": 38031, "text": null }, { "code": null, "e": 40325, "s": 40285, "text": "1 -> 9 -> 9 -> NULL\n2 -> 0 -> 4 -> NULL" }, { "code": null, "e": 40337, "s": 40327, "text": "Rajput-Ji" }, { "code": null, "e": 40349, "s": 40337, "text": "29AjayKumar" }, { "code": null, "e": 40366, "s": 40349, "text": "arorakashish0911" }, { "code": null, "e": 40376, "s": 40366, "text": "rutvik_56" }, { "code": null, "e": 40382, "s": 40376, "text": "itsok" }, { "code": null, "e": 40395, "s": 40382, "text": "simmytarika5" }, { "code": null, "e": 40405, "s": 40395, "text": "Microsoft" }, { "code": null, "e": 40417, "s": 40405, "text": "Linked List" }, { "code": null, "e": 40427, "s": 40417, "text": "Microsoft" }, { "code": null, "e": 40439, "s": 40427, "text": "Linked List" }, { "code": null, "e": 40537, "s": 40439, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 40578, "s": 40537, "text": "Circular Linked List | Set 2 (Traversal)" }, { "code": null, "e": 40628, "s": 40578, "text": "Swap nodes in a linked list without swapping data" }, { "code": null, "e": 40668, "s": 40628, "text": "Circular Singly Linked List | Insertion" }, { "code": null, "e": 40739, "s": 40668, "text": "Given a linked list which is sorted, how will you insert in sorted way" }, { "code": null, "e": 40798, "s": 40739, "text": "Program to implement Singly Linked List in C++ using class" }, { "code": null, "e": 40836, "s": 40798, "text": "Delete a node in a Doubly Linked List" }, { "code": null, "e": 40877, "s": 40836, "text": "Real-time application of Data Structures" }, { "code": null, "e": 40931, "s": 40877, "text": "Insert a node at a specific position in a linked list" }, { "code": null, "e": 40964, "s": 40931, "text": "Linked List Implementation in C#" } ]
Java & MySQL - Exceptions Handling
Exception handling allows you to handle exceptional conditions such as program-defined errors in a controlled fashion. When an exception condition occurs, an exception is thrown. The term thrown means that current program execution stops, and the control is redirected to the nearest applicable catch clause. If no applicable catch clause exists, then the program's execution ends. JDBC Exception handling is very similar to the Java Exception handling but for JDBC, the most common exception you'll deal with is java.sql.SQLException. An SQLException can occur both in the driver and the database. When such an exception occurs, an object of type SQLException will be passed to the catch clause. The passed SQLException object has the following methods available for retrieving additional information about the exception − By utilizing the information available from the Exception object, you can catch an exception and continue your program appropriately. Here is the general form of a try block − try { // Your risky code goes between these curly braces!!! } catch(Exception ex) { // Your exception handling code goes between these // curly braces } finally { // Your must-always-be-executed code goes between these // curly braces. Like closing database connection. } Study the following example code to understand the usage of try....catch...finally blocks. This code has been written based on the environment and database setup done in the previous chapter. import java.sql.CallableStatement; import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; public class TestApplication { static final String DB_URL = "jdbc:mysql://localhost/TUTORIALSPOINT"; static final String USER = "guest"; static final String PASS = "guest123"; static final String QUERY = "{call getEmpName (?, ?)}"; public static void main(String[] args) { // Open a connection try(Connection conn = DriverManager.getConnection(DB_URL, USER, PASS); CallableStatement stmt = conn.prepareCall(QUERY); ) { // Bind values into the parameters. stmt.setInt(1, 1); // This would set ID // Because second parameter is OUT so register it stmt.registerOutParameter(2, java.sql.Types.VARCHAR); //Use execute method to run stored procedure. System.out.println("Executing stored procedure..." ); stmt.execute(); //Retrieve employee name with getXXX method String empName = stmt.getString(2); System.out.println("Emp Name with ID: 1 is " + empName); } catch (SQLException e) { e.printStackTrace(); } } } Now let us compile the above example as follows − C:\>javac TestApplication.java C:\> When you run TestApplication, it produces the following result if there is no problem, otherwise the corresponding error would be caught and error message would be displayed − C:\>java TestApplication Executing stored procedure... Emp Name with ID: 1 is Zara C:\> 16 Lectures 2 hours Malhar Lathkar 19 Lectures 5 hours Malhar Lathkar 25 Lectures 2.5 hours Anadi Sharma 126 Lectures 7 hours Tushar Kale 119 Lectures 17.5 hours Monica Mittal 76 Lectures 7 hours Arnab Chakraborty Print Add Notes Bookmark this page
[ { "code": null, "e": 2805, "s": 2686, "text": "Exception handling allows you to handle exceptional conditions such as program-defined errors in a controlled fashion." }, { "code": null, "e": 3068, "s": 2805, "text": "When an exception condition occurs, an exception is thrown. The term thrown means that current program execution stops, and the control is redirected to the nearest\napplicable catch clause. If no applicable catch clause exists, then the program's execution ends." }, { "code": null, "e": 3222, "s": 3068, "text": "JDBC Exception handling is very similar to the Java Exception handling but for JDBC, the most common exception you'll deal with is java.sql.SQLException." }, { "code": null, "e": 3383, "s": 3222, "text": "An SQLException can occur both in the driver and the database. When such an exception occurs, an object of type SQLException will be passed to the catch clause." }, { "code": null, "e": 3510, "s": 3383, "text": "The passed SQLException object has the following methods available for retrieving additional information about the exception −" }, { "code": null, "e": 3686, "s": 3510, "text": "By utilizing the information available from the Exception object, you can catch an exception and continue your program appropriately. Here is the general form of a try block −" }, { "code": null, "e": 3975, "s": 3686, "text": "try {\n // Your risky code goes between these curly braces!!!\n}\ncatch(Exception ex) {\n // Your exception handling code goes between these \n // curly braces\n}\nfinally {\n // Your must-always-be-executed code goes between these \n // curly braces. Like closing database connection.\n}" }, { "code": null, "e": 4066, "s": 3975, "text": "Study the following example code to understand the usage of try....catch...finally blocks." }, { "code": null, "e": 4167, "s": 4066, "text": "This code has been written based on the environment and database setup done in the previous chapter." }, { "code": null, "e": 5365, "s": 4167, "text": "import java.sql.CallableStatement;\nimport java.sql.Connection;\nimport java.sql.DriverManager;\nimport java.sql.SQLException;\n\npublic class TestApplication {\n static final String DB_URL = \"jdbc:mysql://localhost/TUTORIALSPOINT\";\n static final String USER = \"guest\";\n static final String PASS = \"guest123\";\n static final String QUERY = \"{call getEmpName (?, ?)}\";\n\n public static void main(String[] args) {\n // Open a connection\n try(Connection conn = DriverManager.getConnection(DB_URL, USER, PASS);\n CallableStatement stmt = conn.prepareCall(QUERY);\n ) {\t\t \n // Bind values into the parameters.\n stmt.setInt(1, 1); // This would set ID\n // Because second parameter is OUT so register it\n stmt.registerOutParameter(2, java.sql.Types.VARCHAR);\n //Use execute method to run stored procedure.\n System.out.println(\"Executing stored procedure...\" );\n stmt.execute();\n //Retrieve employee name with getXXX method\n String empName = stmt.getString(2);\n System.out.println(\"Emp Name with ID: 1 is \" + empName);\n } catch (SQLException e) {\n e.printStackTrace();\n } \n }\n}" }, { "code": null, "e": 5415, "s": 5365, "text": "Now let us compile the above example as follows −" }, { "code": null, "e": 5452, "s": 5415, "text": "C:\\>javac TestApplication.java\nC:\\>\n" }, { "code": null, "e": 5628, "s": 5452, "text": "When you run TestApplication, it produces the following result if there is no problem, otherwise the corresponding error would be caught and error message would be displayed −" }, { "code": null, "e": 5717, "s": 5628, "text": "C:\\>java TestApplication\nExecuting stored procedure...\nEmp Name with ID: 1 is Zara\nC:\\>\n" }, { "code": null, "e": 5750, "s": 5717, "text": "\n 16 Lectures \n 2 hours \n" }, { "code": null, "e": 5766, "s": 5750, "text": " Malhar Lathkar" }, { "code": null, "e": 5799, "s": 5766, "text": "\n 19 Lectures \n 5 hours \n" }, { "code": null, "e": 5815, "s": 5799, "text": " Malhar Lathkar" }, { "code": null, "e": 5850, "s": 5815, "text": "\n 25 Lectures \n 2.5 hours \n" }, { "code": null, "e": 5864, "s": 5850, "text": " Anadi Sharma" }, { "code": null, "e": 5898, "s": 5864, "text": "\n 126 Lectures \n 7 hours \n" }, { "code": null, "e": 5912, "s": 5898, "text": " Tushar Kale" }, { "code": null, "e": 5949, "s": 5912, "text": "\n 119 Lectures \n 17.5 hours \n" }, { "code": null, "e": 5964, "s": 5949, "text": " Monica Mittal" }, { "code": null, "e": 5997, "s": 5964, "text": "\n 76 Lectures \n 7 hours \n" }, { "code": null, "e": 6016, "s": 5997, "text": " Arnab Chakraborty" }, { "code": null, "e": 6023, "s": 6016, "text": " Print" }, { "code": null, "e": 6034, "s": 6023, "text": " Add Notes" } ]
HTML Course | Creating Navigation Menu - GeeksforGeeks
06 Sep, 2021 Course Navigation In the last article, we created the entire structure of our website using HTML elements and Tags. Let’s now start building the website in parts. The first part of the website is the header. So the first thing we will create is the navigation menu in the Header of the webpage. The navigation bar contains: A logo aligned to the left. A menu of five items aligned to the right. Let’s look at the part of the code of the header menu from our index.html file. Below is the portion of code of the Header menu where the highlighted part is the top navigation bar: HTML <!-- Header Menu of the Page --><header> <!-- Top header menu containing logo and Navigation bar --> <div id="top-header"> <!-- Logo --> <div id="logo"> </div> <!-- Navigation Menu --> <nav> </nav> </div> <!-- Image menu in Header to contain an Image and a sample text over that image --> <div id="header-image-menu"> </div></header> The first task is to add the image for the logo. Steps to include image and create logo: Download image by clicking here. Copy and Paste the image to the directory: root/images. Where root is the top directory of our project. In our case it is named as “sample project”. Include the image in the code using img tag. The second task is to create an unordered-list in HTML inside the navigation section of the header menu: Add an unordered list in the navigation menu section with 5 list-items named “Home”, “About Us”, “Our Products”, “Careers”, and “Contact Us”. The code of the Header section after adding the above two things will look like as shown below: HTML <!-- Header Menu of the Page --><header> <!-- Top header menu containing logo and Navigation bar --> <div id="top-header"> <!-- Logo --> <div id="logo"> <img src="images/logo.png" /> </div> <!-- Navigation Menu --> <nav> <div id="menu"> <ul> <li class="active"><a href="#">Home</a></li> <li><a href="#">About Us</a></li> <li><a href="#">Our Products</a></li> <li><a href="#">Careers</a></li> <li><a href="#">Contact Us</a></li> </ul> </div> </nav> </div> <!-- Image menu in Header to contain an Image and a sample text over that image --> <div id="header-image-menu"> </div></header> If you now open the index.html file in a browser, you will see the below output: This looks very different than what we saw in the screenshots of the final project. This is because our website is missing CSS for now. That is we have just created the structure of the navigation bar, to make it look beautiful, we will have to add styles using CSS. We will design the navigation bar later but first create a file named “style.css” and add it to the folder “sample project/css“. Also include the CSS file created to the “index.html” file by adding the below line in between head tags. HTML <link rel="stylesheet" href="css/style.css"> Before we begin styling the navigation menu, the first thing needed to do is to set the default CSS values for the HTML elements. Copy and Paste the below code in your “style.css” file: CSS html, body{ height: 100%;} body{ margin: 0px; padding: 0px; background: #FFFFFF; font-family: 'Roboto'; font-size: 12pt;} h1, h2, h3{ margin: 0; padding: 0; color: #404040;} p, ol, ul{ margin-top: 0;} p { line-height: 180%;} ol, ul{ padding: 0; list-style: none;} .container{ /* Set width of container to 1200px and align center */ margin: 0px auto; width: 1200px;} As you can see in the above CSS that we have set the default values for almost every useful HTML element required for the project. Also, we have created a CSS class named “container“. This basically defines a container with a width of 1200px and all of the text within it aligned to center. Add this class named container to the <header> tag.The next step is to assign some id’s to our HTML elements and then use those id’s in the CSS file to style them. Here, we already have assigned id’s to the HTML elements as you can see in the above code. Let’s just begin adding styles to them. Below is the step by step guide to style the navigation bar: Styling overall Header: There isn’t much styling needed for the header tag. The header tag is just needed to be set to “overflow: hidden” to prevent window from overflowing on browser resize. Add the below code to style.css: CSS header{ overflow: hidden;} Styling Navigation Bar(#top-header): Set a fixed height of 60px for the navigation bar and align the texts to center. Add the below code to style.css: CSS #top-header{ text-align: center; height: 60px;} Styling Logo(#logo): Remove padding from the parent div of logo. Make both parent and image floated towards left and assign widths to them. Add the below code to style.css: CSS #logo{ float: left; padding: none; margin: none; height: 60px; width: 30%;} #logo img{ width: 60%; float: left; padding: 10px 0px;} Styling Navigation Menu(#menu): Add below code to style.css: CSS #menu{ float: right; width: 70%; height: 100%; margin: none;} #menu ul{ text-align: center; float: right; margin: none; background: #0074D9;} #menu li{ display: inline-block; padding: none; margin: none;} #menu li a, #menu li span{ display: inline-block; padding: 0em 1.5em; text-decoration: none; font-weight: 600; text-transform: uppercase; line-height: 60px;} #menu li a{ color: #FFF;} #menu li:hover a, #menu li span{ background: #FFF; color: #0074D9; border-left: 1px solid #0074D9; text-decoration: none;} The overall CSS code combining all of the above class and id’s for the navigation bar is shown below: CSS /*************************//* Styling Header *//*************************/header{ overflow: hidden;} #top-header{ text-align: center; height: 60px;} /****************/ /* Styling Logo *//****************/#logo{ float: left; padding: none; margin: none; height: 60px; width: 30%;} #logo img{ width: 60%; float: left; padding: 10px 0px;} /***************************//* Styling Navigation Menu *//***************************/#menu{ float: right; width: 70%; height: 100%; margin: none;} #menu ul{ text-align: center; float: right; margin: none; background: #0074D9;} #menu li{ display: inline-block; padding: none; margin: none;} #menu li a, #menu li span{ display: inline-block; padding: 0em 1.5em; text-decoration: none; font-weight: 600; text-transform: uppercase; line-height: 60px;} #menu li a{ color: #FFF;} #menu li:hover a, #menu li span{ background: #FFF; color: #0074D9; border-left: 1px solid #0074D9; text-decoration: none;} Open the index.html file in browser now, can you see something as shown in the below image. If not, please tally and recheck your code with ours, you must have missed something: So, we have successfully created the navigation bar for the header of our Website. The next thing is to insert the image and a text over the image just below the navigation bar in the header. Supported Browser: Google Chrome Microsoft Edge Firefox Opera Safari Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course. maniacpshyco ysachin2314 chhabradhanvi HTML-course-basic CSS HTML Web Technologies HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Top 10 Projects For Beginners To Practice HTML and CSS Skills How to insert spaces/tabs in text using HTML/CSS? How to 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) Top 10 Projects For Beginners To Practice HTML and CSS Skills How to insert spaces/tabs in text using HTML/CSS? How to set the default value for an HTML <select> element ? How to update Node.js and NPM to next version ? How to set input type date in dd-mm-yyyy format using HTML ?
[ { "code": null, "e": 29988, "s": 29960, "text": "\n06 Sep, 2021" }, { "code": null, "e": 30007, "s": 29988, "text": "Course Navigation " }, { "code": null, "e": 30152, "s": 30007, "text": "In the last article, we created the entire structure of our website using HTML elements and Tags. Let’s now start building the website in parts." }, { "code": null, "e": 30284, "s": 30152, "text": "The first part of the website is the header. So the first thing we will create is the navigation menu in the Header of the webpage." }, { "code": null, "e": 30315, "s": 30284, "text": "The navigation bar contains: " }, { "code": null, "e": 30343, "s": 30315, "text": "A logo aligned to the left." }, { "code": null, "e": 30386, "s": 30343, "text": "A menu of five items aligned to the right." }, { "code": null, "e": 30570, "s": 30386, "text": "Let’s look at the part of the code of the header menu from our index.html file. Below is the portion of code of the Header menu where the highlighted part is the top navigation bar: " }, { "code": null, "e": 30575, "s": 30570, "text": "HTML" }, { "code": "<!-- Header Menu of the Page --><header> <!-- Top header menu containing logo and Navigation bar --> <div id=\"top-header\"> <!-- Logo --> <div id=\"logo\"> </div> <!-- Navigation Menu --> <nav> </nav> </div> <!-- Image menu in Header to contain an Image and a sample text over that image --> <div id=\"header-image-menu\"> </div></header>", "e": 31043, "s": 30575, "text": null }, { "code": null, "e": 31133, "s": 31043, "text": "The first task is to add the image for the logo. Steps to include image and create logo: " }, { "code": null, "e": 31166, "s": 31133, "text": "Download image by clicking here." }, { "code": null, "e": 31315, "s": 31166, "text": "Copy and Paste the image to the directory: root/images. Where root is the top directory of our project. In our case it is named as “sample project”." }, { "code": null, "e": 31360, "s": 31315, "text": "Include the image in the code using img tag." }, { "code": null, "e": 31467, "s": 31360, "text": "The second task is to create an unordered-list in HTML inside the navigation section of the header menu: " }, { "code": null, "e": 31609, "s": 31467, "text": "Add an unordered list in the navigation menu section with 5 list-items named “Home”, “About Us”, “Our Products”, “Careers”, and “Contact Us”." }, { "code": null, "e": 31707, "s": 31609, "text": "The code of the Header section after adding the above two things will look like as shown below: " }, { "code": null, "e": 31712, "s": 31707, "text": "HTML" }, { "code": "<!-- Header Menu of the Page --><header> <!-- Top header menu containing logo and Navigation bar --> <div id=\"top-header\"> <!-- Logo --> <div id=\"logo\"> <img src=\"images/logo.png\" /> </div> <!-- Navigation Menu --> <nav> <div id=\"menu\"> <ul> <li class=\"active\"><a href=\"#\">Home</a></li> <li><a href=\"#\">About Us</a></li> <li><a href=\"#\">Our Products</a></li> <li><a href=\"#\">Careers</a></li> <li><a href=\"#\">Contact Us</a></li> </ul> </div> </nav> </div> <!-- Image menu in Header to contain an Image and a sample text over that image --> <div id=\"header-image-menu\"> </div></header>", "e": 32545, "s": 31712, "text": null }, { "code": null, "e": 32627, "s": 32545, "text": "If you now open the index.html file in a browser, you will see the below output: " }, { "code": null, "e": 32894, "s": 32627, "text": "This looks very different than what we saw in the screenshots of the final project. This is because our website is missing CSS for now. That is we have just created the structure of the navigation bar, to make it look beautiful, we will have to add styles using CSS." }, { "code": null, "e": 33131, "s": 32894, "text": "We will design the navigation bar later but first create a file named “style.css” and add it to the folder “sample project/css“. Also include the CSS file created to the “index.html” file by adding the below line in between head tags. " }, { "code": null, "e": 33136, "s": 33131, "text": "HTML" }, { "code": "<link rel=\"stylesheet\" href=\"css/style.css\">", "e": 33181, "s": 33136, "text": null }, { "code": null, "e": 33368, "s": 33181, "text": "Before we begin styling the navigation menu, the first thing needed to do is to set the default CSS values for the HTML elements. Copy and Paste the below code in your “style.css” file: " }, { "code": null, "e": 33372, "s": 33368, "text": "CSS" }, { "code": "html, body{ height: 100%;} body{ margin: 0px; padding: 0px; background: #FFFFFF; font-family: 'Roboto'; font-size: 12pt;} h1, h2, h3{ margin: 0; padding: 0; color: #404040;} p, ol, ul{ margin-top: 0;} p { line-height: 180%;} ol, ul{ padding: 0; list-style: none;} .container{ /* Set width of container to 1200px and align center */ margin: 0px auto; width: 1200px;}", "e": 33816, "s": 33372, "text": null }, { "code": null, "e": 34402, "s": 33816, "text": "As you can see in the above CSS that we have set the default values for almost every useful HTML element required for the project. Also, we have created a CSS class named “container“. This basically defines a container with a width of 1200px and all of the text within it aligned to center. Add this class named container to the <header> tag.The next step is to assign some id’s to our HTML elements and then use those id’s in the CSS file to style them. Here, we already have assigned id’s to the HTML elements as you can see in the above code. Let’s just begin adding styles to them." }, { "code": null, "e": 34464, "s": 34402, "text": "Below is the step by step guide to style the navigation bar: " }, { "code": null, "e": 34690, "s": 34464, "text": "Styling overall Header: There isn’t much styling needed for the header tag. The header tag is just needed to be set to “overflow: hidden” to prevent window from overflowing on browser resize. Add the below code to style.css: " }, { "code": null, "e": 34694, "s": 34690, "text": "CSS" }, { "code": "header{ overflow: hidden;}", "e": 34729, "s": 34694, "text": null }, { "code": null, "e": 34881, "s": 34729, "text": "Styling Navigation Bar(#top-header): Set a fixed height of 60px for the navigation bar and align the texts to center. Add the below code to style.css: " }, { "code": null, "e": 34885, "s": 34881, "text": "CSS" }, { "code": "#top-header{ text-align: center; height: 60px;}", "e": 34948, "s": 34885, "text": null }, { "code": null, "e": 35122, "s": 34948, "text": "Styling Logo(#logo): Remove padding from the parent div of logo. Make both parent and image floated towards left and assign widths to them. Add the below code to style.css: " }, { "code": null, "e": 35126, "s": 35122, "text": "CSS" }, { "code": "#logo{ float: left; padding: none; margin: none; height: 60px; width: 30%;} #logo img{ width: 60%; float: left; padding: 10px 0px;} ", "e": 35285, "s": 35126, "text": null }, { "code": null, "e": 35347, "s": 35285, "text": "Styling Navigation Menu(#menu): Add below code to style.css: " }, { "code": null, "e": 35351, "s": 35347, "text": "CSS" }, { "code": "#menu{ float: right; width: 70%; height: 100%; margin: none;} #menu ul{ text-align: center; float: right; margin: none; background: #0074D9;} #menu li{ display: inline-block; padding: none; margin: none;} #menu li a, #menu li span{ display: inline-block; padding: 0em 1.5em; text-decoration: none; font-weight: 600; text-transform: uppercase; line-height: 60px;} #menu li a{ color: #FFF;} #menu li:hover a, #menu li span{ background: #FFF; color: #0074D9; border-left: 1px solid #0074D9; text-decoration: none;}", "e": 35958, "s": 35351, "text": null }, { "code": null, "e": 36062, "s": 35958, "text": "The overall CSS code combining all of the above class and id’s for the navigation bar is shown below: " }, { "code": null, "e": 36066, "s": 36062, "text": "CSS" }, { "code": "/*************************//* Styling Header *//*************************/header{ overflow: hidden;} #top-header{ text-align: center; height: 60px;} /****************/ /* Styling Logo *//****************/#logo{ float: left; padding: none; margin: none; height: 60px; width: 30%;} #logo img{ width: 60%; float: left; padding: 10px 0px;} /***************************//* Styling Navigation Menu *//***************************/#menu{ float: right; width: 70%; height: 100%; margin: none;} #menu ul{ text-align: center; float: right; margin: none; background: #0074D9;} #menu li{ display: inline-block; padding: none; margin: none;} #menu li a, #menu li span{ display: inline-block; padding: 0em 1.5em; text-decoration: none; font-weight: 600; text-transform: uppercase; line-height: 60px;} #menu li a{ color: #FFF;} #menu li:hover a, #menu li span{ background: #FFF; color: #0074D9; border-left: 1px solid #0074D9; text-decoration: none;}", "e": 37155, "s": 36066, "text": null }, { "code": null, "e": 37334, "s": 37155, "text": "Open the index.html file in browser now, can you see something as shown in the below image. If not, please tally and recheck your code with ours, you must have missed something: " }, { "code": null, "e": 37526, "s": 37334, "text": "So, we have successfully created the navigation bar for the header of our Website. The next thing is to insert the image and a text over the image just below the navigation bar in the header." }, { "code": null, "e": 37545, "s": 37526, "text": "Supported Browser:" }, { "code": null, "e": 37559, "s": 37545, "text": "Google Chrome" }, { "code": null, "e": 37574, "s": 37559, "text": "Microsoft Edge" }, { "code": null, "e": 37582, "s": 37574, "text": "Firefox" }, { "code": null, "e": 37588, "s": 37582, "text": "Opera" }, { "code": null, "e": 37595, "s": 37588, "text": "Safari" }, { "code": null, "e": 37734, "s": 37597, "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": 37747, "s": 37734, "text": "maniacpshyco" }, { "code": null, "e": 37759, "s": 37747, "text": "ysachin2314" }, { "code": null, "e": 37773, "s": 37759, "text": "chhabradhanvi" }, { "code": null, "e": 37791, "s": 37773, "text": "HTML-course-basic" }, { "code": null, "e": 37795, "s": 37791, "text": "CSS" }, { "code": null, "e": 37800, "s": 37795, "text": "HTML" }, { "code": null, "e": 37817, "s": 37800, "text": "Web Technologies" }, { "code": null, "e": 37822, "s": 37817, "text": "HTML" }, { "code": null, "e": 37920, "s": 37822, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 37929, "s": 37920, "text": "Comments" }, { "code": null, "e": 37942, "s": 37929, "text": "Old Comments" }, { "code": null, "e": 38004, "s": 37942, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 38054, "s": 38004, "text": "How to insert spaces/tabs in text using HTML/CSS?" }, { "code": null, "e": 38112, "s": 38054, "text": "How to create footer to stay at the bottom of a Web page?" }, { "code": null, "e": 38160, "s": 38112, "text": "How to update Node.js and NPM to next version ?" }, { "code": null, "e": 38197, "s": 38160, "text": "Types of CSS (Cascading Style Sheet)" }, { "code": null, "e": 38259, "s": 38197, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 38309, "s": 38259, "text": "How to insert spaces/tabs in text using HTML/CSS?" }, { "code": null, "e": 38369, "s": 38309, "text": "How to set the default value for an HTML <select> element ?" }, { "code": null, "e": 38417, "s": 38369, "text": "How to update Node.js and NPM to next version ?" } ]
AngularJS - Controllers
AngularJS application mainly relies on controllers to control the flow of data in the application. A controller is defined using ng-controller directive. A controller is a JavaScript object that contains attributes/properties, and functions. Each controller accepts $scope as a parameter, which refers to the application/module that the controller needs to handle. <div ng-app = "" ng-controller = "studentController"> ... </div> Here, we declare a controller named studentController, using the ng-controller directive. We define it as follows − <script> function studentController($scope) { $scope.student = { firstName: "Mahesh", lastName: "Parashar", fullName: function() { var studentObject; studentObject = $scope.student; return studentObject.firstName + " " + studentObject.lastName; } }; } </script> The studentController is defined as a JavaScript object with $scope as an argument. The studentController is defined as a JavaScript object with $scope as an argument. The $scope refers to application which uses the studentController object. The $scope refers to application which uses the studentController object. The $scope.student is a property of studentController object. The $scope.student is a property of studentController object. The firstName and the lastName are two properties of $scope.student object. We pass the default values to them. The firstName and the lastName are two properties of $scope.student object. We pass the default values to them. The property fullName is the function of $scope.student object, which returns the combined name. The property fullName is the function of $scope.student object, which returns the combined name. In the fullName function, we get the student object and then return the combined name. In the fullName function, we get the student object and then return the combined name. As a note, we can also define the controller object in a separate JS file and refer that file in the HTML page. As a note, we can also define the controller object in a separate JS file and refer that file in the HTML page. Now we can use studentController's student property using ng-model or using expressions as follows − Enter first name: <input type = "text" ng-model = "student.firstName"><br> Enter last name: <input type = "text" ng-model = "student.lastName"><br> <br> You are entering: {{student.fullName()}} We bound student.firstName and student.lastname to two input boxes. We bound student.firstName and student.lastname to two input boxes. We bound student.fullName() to HTML. We bound student.fullName() to HTML. Now whenever you type anything in first name and last name input boxes, you can see the full name getting updated automatically. Now whenever you type anything in first name and last name input boxes, you can see the full name getting updated automatically. The following example shows the use of controller − <html> <head> <title>Angular JS Controller</title> <script src = "https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"> </script> </head> <body> <h2>AngularJS Sample Application</h2> <div ng-app = "mainApp" ng-controller = "studentController"> Enter first name: <input type = "text" ng-model = "student.firstName"><br> <br> Enter last name: <input type = "text" ng-model = "student.lastName"><br> <br> You are entering: {{student.fullName()}} </div> <script> var mainApp = angular.module("mainApp", []); mainApp.controller('studentController', function($scope) { $scope.student = { firstName: "Mahesh", lastName: "Parashar", fullName: function() { var studentObject; studentObject = $scope.student; return studentObject.firstName + " " + studentObject.lastName; } }; }); </script> </body> </html> Open the file testAngularJS.htm in a web browser and see the result. 16 Lectures 1.5 hours Anadi Sharma 40 Lectures 2.5 hours Skillbakerystudios Print Add Notes Bookmark this page
[ { "code": null, "e": 3064, "s": 2699, "text": "AngularJS application mainly relies on controllers to control the flow of data in the application. A controller is defined using ng-controller directive. A controller is a JavaScript object that contains attributes/properties, and functions. Each controller accepts $scope as a parameter, which refers to the application/module that the controller needs to handle." }, { "code": null, "e": 3133, "s": 3064, "text": "<div ng-app = \"\" ng-controller = \"studentController\">\n ...\n</div>\n" }, { "code": null, "e": 3249, "s": 3133, "text": "Here, we declare a controller named studentController, using the ng-controller directive. We define it as follows −" }, { "code": null, "e": 3611, "s": 3249, "text": "<script>\n function studentController($scope) {\n $scope.student = {\n firstName: \"Mahesh\",\n lastName: \"Parashar\",\n \n fullName: function() {\n var studentObject;\n studentObject = $scope.student;\n return studentObject.firstName + \" \" + studentObject.lastName;\n }\n };\n }\n</script>" }, { "code": null, "e": 3695, "s": 3611, "text": "The studentController is defined as a JavaScript object with $scope as an argument." }, { "code": null, "e": 3779, "s": 3695, "text": "The studentController is defined as a JavaScript object with $scope as an argument." }, { "code": null, "e": 3853, "s": 3779, "text": "The $scope refers to application which uses the studentController object." }, { "code": null, "e": 3927, "s": 3853, "text": "The $scope refers to application which uses the studentController object." }, { "code": null, "e": 3989, "s": 3927, "text": "The $scope.student is a property of studentController object." }, { "code": null, "e": 4051, "s": 3989, "text": "The $scope.student is a property of studentController object." }, { "code": null, "e": 4163, "s": 4051, "text": "The firstName and the lastName are two properties of $scope.student object. We pass the default values to them." }, { "code": null, "e": 4275, "s": 4163, "text": "The firstName and the lastName are two properties of $scope.student object. We pass the default values to them." }, { "code": null, "e": 4372, "s": 4275, "text": "The property fullName is the function of $scope.student object, which returns the combined name." }, { "code": null, "e": 4469, "s": 4372, "text": "The property fullName is the function of $scope.student object, which returns the combined name." }, { "code": null, "e": 4556, "s": 4469, "text": "In the fullName function, we get the student object and then return the combined name." }, { "code": null, "e": 4643, "s": 4556, "text": "In the fullName function, we get the student object and then return the combined name." }, { "code": null, "e": 4755, "s": 4643, "text": "As a note, we can also define the controller object in a separate JS file and refer that file in the HTML page." }, { "code": null, "e": 4867, "s": 4755, "text": "As a note, we can also define the controller object in a separate JS file and refer that file in the HTML page." }, { "code": null, "e": 4968, "s": 4867, "text": "Now we can use studentController's student property using ng-model or using expressions as follows −" }, { "code": null, "e": 5163, "s": 4968, "text": "Enter first name: <input type = \"text\" ng-model = \"student.firstName\"><br>\nEnter last name: <input type = \"text\" ng-model = \"student.lastName\"><br>\n<br>\nYou are entering: {{student.fullName()}}\n" }, { "code": null, "e": 5231, "s": 5163, "text": "We bound student.firstName and student.lastname to two input boxes." }, { "code": null, "e": 5299, "s": 5231, "text": "We bound student.firstName and student.lastname to two input boxes." }, { "code": null, "e": 5336, "s": 5299, "text": "We bound student.fullName() to HTML." }, { "code": null, "e": 5373, "s": 5336, "text": "We bound student.fullName() to HTML." }, { "code": null, "e": 5502, "s": 5373, "text": "Now whenever you type anything in first name and last name input boxes, you can see the full name getting updated automatically." }, { "code": null, "e": 5631, "s": 5502, "text": "Now whenever you type anything in first name and last name input boxes, you can see the full name getting updated automatically." }, { "code": null, "e": 5683, "s": 5631, "text": "The following example shows the use of controller −" }, { "code": null, "e": 6819, "s": 5683, "text": "<html>\n <head>\n <title>Angular JS Controller</title>\n <script src = \"https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js\">\n </script>\n </head>\n \n <body>\n <h2>AngularJS Sample Application</h2>\n \n <div ng-app = \"mainApp\" ng-controller = \"studentController\">\n Enter first name: <input type = \"text\" ng-model = \"student.firstName\"><br>\n <br>\n Enter last name: <input type = \"text\" ng-model = \"student.lastName\"><br>\n <br>\n You are entering: {{student.fullName()}}\n </div>\n \n <script>\n var mainApp = angular.module(\"mainApp\", []);\n \n mainApp.controller('studentController', function($scope) {\n $scope.student = {\n firstName: \"Mahesh\",\n lastName: \"Parashar\",\n \n fullName: function() {\n var studentObject;\n studentObject = $scope.student;\n return studentObject.firstName + \" \" + studentObject.lastName;\n }\n };\n });\n </script>\n \n </body>\n</html>" }, { "code": null, "e": 6888, "s": 6819, "text": "Open the file testAngularJS.htm in a web browser and see the result." }, { "code": null, "e": 6923, "s": 6888, "text": "\n 16 Lectures \n 1.5 hours \n" }, { "code": null, "e": 6937, "s": 6923, "text": " Anadi Sharma" }, { "code": null, "e": 6972, "s": 6937, "text": "\n 40 Lectures \n 2.5 hours \n" }, { "code": null, "e": 6992, "s": 6972, "text": " Skillbakerystudios" }, { "code": null, "e": 6999, "s": 6992, "text": " Print" }, { "code": null, "e": 7010, "s": 6999, "text": " Add Notes" } ]
Can an interface extend multiple interfaces in Java?
Yes, we can do it. An interface can extend multiple interfaces in Java. interface A { public void test(); public void test1(); } interface B { public void test(); public void test2(); } interface C extends A,B { public void test3(); } class D implements C { public void test() { System.out.println("Testing\n"); } public void test1() { System.out.println("Testing1\n"); } public void test2() { System.out.println("Testing2\n"); } public void test3() { System.out.println("Testing3"); } } public class Main { public static void main(String[] args) { D d=new D(); d.test(); d.test1(); d.test2(); d.test3(); } } Testing Testing1 Testing2 Testing3
[ { "code": null, "e": 1134, "s": 1062, "text": "Yes, we can do it. An interface can extend multiple interfaces in Java." }, { "code": null, "e": 1771, "s": 1134, "text": "interface A {\n public void test();\n public void test1();\n}\ninterface B {\n public void test();\n public void test2();\n}\ninterface C extends A,B {\n public void test3();\n}\nclass D implements C {\n public void test() {\n System.out.println(\"Testing\\n\");\n }\n public void test1() {\n System.out.println(\"Testing1\\n\");\n }\n public void test2() {\n System.out.println(\"Testing2\\n\");\n }\n public void test3() {\n System.out.println(\"Testing3\");\n }\n}\npublic class Main {\n public static void main(String[] args) {\n D d=new D();\n d.test();\n d.test1();\n d.test2();\n d.test3();\n }\n }" }, { "code": null, "e": 1809, "s": 1771, "text": "Testing\n\nTesting1\n\nTesting2\n\nTesting3" } ]
Which methods are supported by Get-ChildItem in PowerShell?
There are methods or functions which are useful for directories and file operations. Methods for the directory. TypeName: System.IO.DirectoryInfo Name MemberType ---- ---------- Create Method CreateObjRef Method CreateSubdirectory Method Delete Method EnumerateDirectories Method EnumerateFiles Method EnumerateFileSystemInfos Method Equals Method GetAccessControl Method GetDirectories Method GetFiles Method GetFileSystemInfos Method GetHashCode Method GetLifetimeService Method GetObjectData Method GetType Method InitializeLifetimeService Method MoveTo Method Refresh Method SetAccessControl Method ToString Method Methods for Files. TypeName: System.IO.FileInfo Name MemberType ---- ---------- AppendText Method CopyTo Method Create Method CreateObjRef Method CreateText Method Decrypt Method Delete Method Encrypt Method Equals Method GetAccessControl Method GetHashCode Method GetLifetimeService Method GetObjectData Method GetType Method InitializeLifetimeService Method MoveTo Method Open Method OpenRead Method OpenText Method OpenWrite Method Refresh Method Replace Method SetAccessControl Method ToString Method
[ { "code": null, "e": 1147, "s": 1062, "text": "There are methods or functions which are useful for directories and file operations." }, { "code": null, "e": 1174, "s": 1147, "text": "Methods for the directory." }, { "code": null, "e": 1976, "s": 1174, "text": "TypeName: System.IO.DirectoryInfo\n\nName MemberType\n---- ----------\nCreate Method\nCreateObjRef Method\nCreateSubdirectory Method\nDelete Method\nEnumerateDirectories Method\nEnumerateFiles Method\nEnumerateFileSystemInfos Method\nEquals Method\nGetAccessControl Method\nGetDirectories Method\nGetFiles Method\nGetFileSystemInfos Method\nGetHashCode Method\nGetLifetimeService Method\nGetObjectData Method\nGetType Method\nInitializeLifetimeService Method\nMoveTo Method\nRefresh Method\nSetAccessControl Method\nToString Method" }, { "code": null, "e": 1995, "s": 1976, "text": "Methods for Files." }, { "code": null, "e": 2891, "s": 1995, "text": "TypeName: System.IO.FileInfo\n\nName MemberType\n---- ----------\nAppendText Method\nCopyTo Method\nCreate Method\nCreateObjRef Method\nCreateText Method\nDecrypt Method\nDelete Method\nEncrypt Method\nEquals Method\nGetAccessControl Method\nGetHashCode Method\nGetLifetimeService Method\nGetObjectData Method\nGetType Method\nInitializeLifetimeService Method\nMoveTo Method\nOpen Method\nOpenRead Method\nOpenText Method\nOpenWrite Method\nRefresh Method\nReplace Method\nSetAccessControl Method\nToString Method" } ]
How To Setup Julia For Data Science | by Emmett Boudreau | Towards Data Science
The Julia programming language is a relatively young language that has taken the world of Data Science by storm in recent years. This is because the Julia language’s features facilitate scientific computing and machine-learning very well. This is because of a rigid combination of numerical accuracy, calculation speed, and scientific syntax. Considering all of these attributes of the language, it is easy to see why any Data Scientist might be considering picking up the programming language. However, when picking up the language it is likely that you will encounter the largest problem with the Julia programming language, its popularity. Compared to most other programming languages, Julia has a very low adoption rate and a lot smaller user-base and package ecosystem than most of the other statistical languages that it is competing with. This can make the language a lot more difficult to learn just because there are far fewer resources available. Furthermore, if it is too difficult for some users to even get the language operating properly on their machine, it is unlikely that these users are going to be getting very familiar with the language beyond what is on the website. Of course, in this regard, the first step towards getting Julia set up is going to be actually installing the programming language. Of course, this process is going to be dramatically different depending on what operating system you might be running. On most unix-like operating systems like MacOS, Linux, and FreeBSD the package is going to be available in your package manager. However, I would like to point out that this is probably not the way that you should install the Julia language on these systems. This is because these package manager versions are often very outdated, and in some instances, you might end up with an ancient and essentially useless version of Julia. Even in scenarios where the version is above the 1.0 breaking release, you might find that there are many features that are left out and documentation that might not be accurate. Furthermore, compatibility is always a large concern when it comes to working with packages in the ecosystem. On these Unix-like systems, I certainly recommend downloading the language directly from the Julia website. In this regard, the first step is going to likely be downloading the file and placing it in a desired directory. I typically do this with wget in bash, but there is essentially no difference at all between doing this in the web-browser or the terminal. After the package is downloaded and extracted, the next step is going to be to add the path to your system so that your system knows where your Julia installation is actually located. On Linux, we can do this by editing our ~/.bashrc or ~/.bash_profile file. wget https://julialang-s3.julialang.org/bin/linux/x64/1.6/julia-1.6.0-linux-x86_64.tar.gztar zxvf julia-1.6.0-linux-x86_64.tar.gz Now we will add this line into our ~/.bashrc export PATH="$PATH:/julia/directory" I typically place this along with my net-wide assembler in /opt, but you could essentially place it anywhere under your root file system. As for installation on MacOS, the process starts with a Julia dmg file provided on the website. Optionally, you can add the call to PATH using ln: ln -s /Applications/Julia-1.6.app/Contents/Resources/julia/bin/julia /usr/local/bin/juli For Windows, we will of course run an executable .exe file as you might typically do with any application on this operating system. After that, you might want to add the PATH just as before. Of course, this is a little different with the MSDOS-based NT command terminal thing that you get on Windows. The process for adding this to PATH goes a little something like this in Windows: Open Run (Windows Key + R), type in rundll32 sysdm.cpl,EditEnvironmentVariables and hit enter.Under either the “User Variables” or “System Variables” section, find the row with “Path”, and click edit.The “Edit environment variable” UI will appear. Here, click “New”, and paste in the directory noted from the installation stage. This should look something like C:\Users\JohnDoe\AppData\Local\Programs\Julia 1.6.0\bin.Click OK. You can now run Julia from the command line, by typing julia! Open Run (Windows Key + R), type in rundll32 sysdm.cpl,EditEnvironmentVariables and hit enter. Under either the “User Variables” or “System Variables” section, find the row with “Path”, and click edit. The “Edit environment variable” UI will appear. Here, click “New”, and paste in the directory noted from the installation stage. This should look something like C:\Users\JohnDoe\AppData\Local\Programs\Julia 1.6.0\bin. Click OK. You can now run Julia from the command line, by typing julia! When it comes to development environments with Julia, there are a lot of different options that I personally think are all awesome. Firstly, in the world of notebooks we have three options: IJulia.jl Pluto.jl Neptune.jl All of these are Julia packages that we will need to add, so in order to get a notebook server up we might want to first figure out which notebook server is going to be the most apt for our work. Personally, I prefer good-ole Jupyter to both Pluto and Neptune, which I believe can be a bit of a headache and have a decent way to go when it comes to actually being stable and working really well. I wrote an opinionated article on this exact topic that you could check out here in order to find out if Pluto.jl might be for you: towardsdatascience.com That being said, an advantage to using a solution like Pluto or Neptune is that both of these notebook servers are written in the Julia programming language. In other words, we can cut out the middle man with the IPython kernels and run the Julia directly through itself, which can certainly present some performance benefits. Furthermore, Pluto and Neptune files are stored in .jl Julia files, rather than IPython notebook files — which is pretty cool, because then you can write your code one time and have it work from both the REPL and the notebook. To elaborate, Neptune.jl is a rather recently released modification of Pluto.jl. The Neptune.jl implementation actually gets rid of a lot of the problems I had with Pluto.jl. These examples include the interactivity, which can sometimes even be a little invasive and get in between you and writing the code. IJulia is just a Jupyter kernel for Julia, which for me has been the most effective solution for my personal preferences. That being said, there is no harm in trying this out. With that in mind, all we really need to do in order to work with these packages is add them through Julia’s package manager, Pkg. This is of course with the exception of IJulia, which is going to require a Jupyter installation in order to properly work. In order to add these packages, we first need to get into the Julia REPL. You can do this universally on all the operating systems by typing “ julia” into your terminal or command window. Once you are in the Julia REPL, you can press ] to enter the Pkg REPL. Although Pkg itself is a package that you can always call from Julia, I certainly prefer to use this method. Now we can use the add command with a package as an argument in order to add our packages: julia > ]pkg > add IJuliapkg > add Plutopkg > add Neptune With IJulia, the Julia kernel should now appear in your kernel list in Jupyter, and that is really all there is to it. With Neptune and Pluto, you will need to import the package and use the run() function in order to start your server. using Neptune; Neptune.run()using Pluto; Pluto.run() In addition to having a notebook server, you might also want a development environment for regular text. For that, my favorite solution is Atom with Juno. However, there is also a VSCode development environment available that I have never used. Juno is actually technically deprecated — well, not deprecated, but the only updates it receives are security and bug fixes, no new features are planned to be added to the Juno package. As with most instances of Atom packages, you can install it by first going into your menu bar and selecting edit>preferences. This will bring up a preference menu. Along the left side of this menu you should see a little plus sign that says “ install,” there you can install Juno. This will also install the Juno.jl package, and boom! You can now edit Julia text! The last thing that one might want in order to work with the Julia language is the ability to work with virtual environments. In Julia, this process is incredibly easy and done completely through the Pkg package manager. We can call the activate command or method from Pkg in order to create a new virtual environment. This will create a folder with a Project.toml file inside of it. This project file will contain all of the dependencies for your project, and is shaped like a typical configuration file. julia > ]pkg > activate env The Julia language has certainly jumped in popularity over the past year or two. This is because of all the Data Science-centric features available in the language, as Data Science has become a rather popular topic in the world of computing as of lately. I think that with this new set of users, many are bound to be lost on the installation process alone. With that in mind, I hope this article was successful at solving that problem — and if that problem was never had, perhaps it might have sparked a little interest in the language! What is great about that is now you also know how to install it!
[ { "code": null, "e": 814, "s": 171, "text": "The Julia programming language is a relatively young language that has taken the world of Data Science by storm in recent years. This is because the Julia language’s features facilitate scientific computing and machine-learning very well. This is because of a rigid combination of numerical accuracy, calculation speed, and scientific syntax. Considering all of these attributes of the language, it is easy to see why any Data Scientist might be considering picking up the programming language. However, when picking up the language it is likely that you will encounter the largest problem with the Julia programming language, its popularity." }, { "code": null, "e": 1360, "s": 814, "text": "Compared to most other programming languages, Julia has a very low adoption rate and a lot smaller user-base and package ecosystem than most of the other statistical languages that it is competing with. This can make the language a lot more difficult to learn just because there are far fewer resources available. Furthermore, if it is too difficult for some users to even get the language operating properly on their machine, it is unlikely that these users are going to be getting very familiar with the language beyond what is on the website." }, { "code": null, "e": 2329, "s": 1360, "text": "Of course, in this regard, the first step towards getting Julia set up is going to be actually installing the programming language. Of course, this process is going to be dramatically different depending on what operating system you might be running. On most unix-like operating systems like MacOS, Linux, and FreeBSD the package is going to be available in your package manager. However, I would like to point out that this is probably not the way that you should install the Julia language on these systems. This is because these package manager versions are often very outdated, and in some instances, you might end up with an ancient and essentially useless version of Julia. Even in scenarios where the version is above the 1.0 breaking release, you might find that there are many features that are left out and documentation that might not be accurate. Furthermore, compatibility is always a large concern when it comes to working with packages in the ecosystem." }, { "code": null, "e": 2949, "s": 2329, "text": "On these Unix-like systems, I certainly recommend downloading the language directly from the Julia website. In this regard, the first step is going to likely be downloading the file and placing it in a desired directory. I typically do this with wget in bash, but there is essentially no difference at all between doing this in the web-browser or the terminal. After the package is downloaded and extracted, the next step is going to be to add the path to your system so that your system knows where your Julia installation is actually located. On Linux, we can do this by editing our ~/.bashrc or ~/.bash_profile file." }, { "code": null, "e": 3079, "s": 2949, "text": "wget https://julialang-s3.julialang.org/bin/linux/x64/1.6/julia-1.6.0-linux-x86_64.tar.gztar zxvf julia-1.6.0-linux-x86_64.tar.gz" }, { "code": null, "e": 3124, "s": 3079, "text": "Now we will add this line into our ~/.bashrc" }, { "code": null, "e": 3161, "s": 3124, "text": "export PATH=\"$PATH:/julia/directory\"" }, { "code": null, "e": 3299, "s": 3161, "text": "I typically place this along with my net-wide assembler in /opt, but you could essentially place it anywhere under your root file system." }, { "code": null, "e": 3446, "s": 3299, "text": "As for installation on MacOS, the process starts with a Julia dmg file provided on the website. Optionally, you can add the call to PATH using ln:" }, { "code": null, "e": 3535, "s": 3446, "text": "ln -s /Applications/Julia-1.6.app/Contents/Resources/julia/bin/julia /usr/local/bin/juli" }, { "code": null, "e": 3918, "s": 3535, "text": "For Windows, we will of course run an executable .exe file as you might typically do with any application on this operating system. After that, you might want to add the PATH just as before. Of course, this is a little different with the MSDOS-based NT command terminal thing that you get on Windows. The process for adding this to PATH goes a little something like this in Windows:" }, { "code": null, "e": 4407, "s": 3918, "text": "Open Run (Windows Key + R), type in rundll32 sysdm.cpl,EditEnvironmentVariables and hit enter.Under either the “User Variables” or “System Variables” section, find the row with “Path”, and click edit.The “Edit environment variable” UI will appear. Here, click “New”, and paste in the directory noted from the installation stage. This should look something like C:\\Users\\JohnDoe\\AppData\\Local\\Programs\\Julia 1.6.0\\bin.Click OK. You can now run Julia from the command line, by typing julia!" }, { "code": null, "e": 4502, "s": 4407, "text": "Open Run (Windows Key + R), type in rundll32 sysdm.cpl,EditEnvironmentVariables and hit enter." }, { "code": null, "e": 4609, "s": 4502, "text": "Under either the “User Variables” or “System Variables” section, find the row with “Path”, and click edit." }, { "code": null, "e": 4827, "s": 4609, "text": "The “Edit environment variable” UI will appear. Here, click “New”, and paste in the directory noted from the installation stage. This should look something like C:\\Users\\JohnDoe\\AppData\\Local\\Programs\\Julia 1.6.0\\bin." }, { "code": null, "e": 4899, "s": 4827, "text": "Click OK. You can now run Julia from the command line, by typing julia!" }, { "code": null, "e": 5031, "s": 4899, "text": "When it comes to development environments with Julia, there are a lot of different options that I personally think are all awesome." }, { "code": null, "e": 5089, "s": 5031, "text": "Firstly, in the world of notebooks we have three options:" }, { "code": null, "e": 5099, "s": 5089, "text": "IJulia.jl" }, { "code": null, "e": 5108, "s": 5099, "text": "Pluto.jl" }, { "code": null, "e": 5119, "s": 5108, "text": "Neptune.jl" }, { "code": null, "e": 5647, "s": 5119, "text": "All of these are Julia packages that we will need to add, so in order to get a notebook server up we might want to first figure out which notebook server is going to be the most apt for our work. Personally, I prefer good-ole Jupyter to both Pluto and Neptune, which I believe can be a bit of a headache and have a decent way to go when it comes to actually being stable and working really well. I wrote an opinionated article on this exact topic that you could check out here in order to find out if Pluto.jl might be for you:" }, { "code": null, "e": 5670, "s": 5647, "text": "towardsdatascience.com" }, { "code": null, "e": 6224, "s": 5670, "text": "That being said, an advantage to using a solution like Pluto or Neptune is that both of these notebook servers are written in the Julia programming language. In other words, we can cut out the middle man with the IPython kernels and run the Julia directly through itself, which can certainly present some performance benefits. Furthermore, Pluto and Neptune files are stored in .jl Julia files, rather than IPython notebook files — which is pretty cool, because then you can write your code one time and have it work from both the REPL and the notebook." }, { "code": null, "e": 6708, "s": 6224, "text": "To elaborate, Neptune.jl is a rather recently released modification of Pluto.jl. The Neptune.jl implementation actually gets rid of a lot of the problems I had with Pluto.jl. These examples include the interactivity, which can sometimes even be a little invasive and get in between you and writing the code. IJulia is just a Jupyter kernel for Julia, which for me has been the most effective solution for my personal preferences. That being said, there is no harm in trying this out." }, { "code": null, "e": 7422, "s": 6708, "text": "With that in mind, all we really need to do in order to work with these packages is add them through Julia’s package manager, Pkg. This is of course with the exception of IJulia, which is going to require a Jupyter installation in order to properly work. In order to add these packages, we first need to get into the Julia REPL. You can do this universally on all the operating systems by typing “ julia” into your terminal or command window. Once you are in the Julia REPL, you can press ] to enter the Pkg REPL. Although Pkg itself is a package that you can always call from Julia, I certainly prefer to use this method. Now we can use the add command with a package as an argument in order to add our packages:" }, { "code": null, "e": 7480, "s": 7422, "text": "julia > ]pkg > add IJuliapkg > add Plutopkg > add Neptune" }, { "code": null, "e": 7717, "s": 7480, "text": "With IJulia, the Julia kernel should now appear in your kernel list in Jupyter, and that is really all there is to it. With Neptune and Pluto, you will need to import the package and use the run() function in order to start your server." }, { "code": null, "e": 7770, "s": 7717, "text": "using Neptune; Neptune.run()using Pluto; Pluto.run()" }, { "code": null, "e": 8327, "s": 7770, "text": "In addition to having a notebook server, you might also want a development environment for regular text. For that, my favorite solution is Atom with Juno. However, there is also a VSCode development environment available that I have never used. Juno is actually technically deprecated — well, not deprecated, but the only updates it receives are security and bug fixes, no new features are planned to be added to the Juno package. As with most instances of Atom packages, you can install it by first going into your menu bar and selecting edit>preferences." }, { "code": null, "e": 8565, "s": 8327, "text": "This will bring up a preference menu. Along the left side of this menu you should see a little plus sign that says “ install,” there you can install Juno. This will also install the Juno.jl package, and boom! You can now edit Julia text!" }, { "code": null, "e": 9071, "s": 8565, "text": "The last thing that one might want in order to work with the Julia language is the ability to work with virtual environments. In Julia, this process is incredibly easy and done completely through the Pkg package manager. We can call the activate command or method from Pkg in order to create a new virtual environment. This will create a folder with a Project.toml file inside of it. This project file will contain all of the dependencies for your project, and is shaped like a typical configuration file." }, { "code": null, "e": 9099, "s": 9071, "text": "julia > ]pkg > activate env" } ]
How to check whether a checkbox is checked in JavaScript?
To check whether a checkbox is checked, try to run the following code. It returns true if the checkbox is checked, else false − Live Demo <html> <head> <script> function myFunction(){ var result = document.getElementById("check").checked; alert(result); } </script> </head> <body> <label><input id="check" type="checkbox" >One</label><br> <button onclick="myFunction()">Check value</button> </body> </html>
[ { "code": null, "e": 1190, "s": 1062, "text": "To check whether a checkbox is checked, try to run the following code. It returns true if the checkbox is checked, else false −" }, { "code": null, "e": 1200, "s": 1190, "text": "Live Demo" }, { "code": null, "e": 1547, "s": 1200, "text": "<html>\n <head>\n <script>\n function myFunction(){\n var result = document.getElementById(\"check\").checked;\n alert(result);\n }\n </script>\n </head>\n <body>\n <label><input id=\"check\" type=\"checkbox\" >One</label><br>\n <button onclick=\"myFunction()\">Check value</button>\n </body>\n</html>" } ]
Count all sub-strings with weight of characters atmost K - GeeksforGeeks
07 Dec, 2021 Given a string P consisting of small English letters and a string Q consisting of weight of all characters of English alphabet such that for all ‘i’, 0 ≤ Q[i] ≤ 9. The task is to find the total numbers of unique substring with sum of weights atmost K.Examples: Input: P = “ababab”, Q = “12345678912345678912345678”, K = 5 Output: 7 Explanation: The substrings with the sum of weights of individual characters ≤ 5 are: “a”, “ab”, “b”, “bc”, “c”, “d”, “e”Input: P = “acbacbacaa”, Q = “12300045600078900012345000”, K = 2 Output: 3 Explanation: The substrings with the sum of weights of individual characters ≤ 2 are: “a”, “b”, “aa” Approach: The idea is to use an unordered set to store the unique values. The following steps are followed to compute the answer: Iterate over all the substrings using the nested loops and maintain the sum of the weight of all the characters encountered so far. If the sum of characters is not greater than K, then insert it in a hashmap. Finally, output the size of the hashmap. Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ program to find the count of// all the sub-strings with weight of// characters atmost K#include <bits/stdc++.h>using namespace std; // Function to find the count of// all the substrings with weight// of characters atmost Kint distinctSubstring(string& P, string& Q, int K, int N){ // Hashmap to store all substrings unordered_set<string> S; // Iterate over all substrings for (int i = 0; i < N; ++i) { // Maintain the sum of all characters // encountered so far int sum = 0; // Maintain the substring till the // current position string s; for (int j = i; j < N; ++j) { // Get the position of the // character in string Q int pos = P[j] - 'a'; // Add weight to current sum sum += Q[pos] - '0'; // Add current character to substring s += P[j]; // If sum of characters is <=K // then insert into the set if (sum <= K) { S.insert(s); } else { break; } } } // Finding the size of the set return S.size();} // Driver codeint main(){ string P = "abcde"; string Q = "12345678912345678912345678"; int K = 5; int N = P.length(); cout << distinctSubstring(P, Q, K, N); return 0;} // Java program to find the count of// all the sub-Strings with weight of// characters atmost Kimport java.util.*; class GFG{ // Function to find the count of// all the subStrings with weight// of characters atmost Kstatic int distinctSubString(String P, String Q, int K, int N){ // Hashmap to store all subStrings HashSet<String> S = new HashSet<String>(); // Iterate over all subStrings for (int i = 0; i < N; ++i) { // Maintain the sum of all characters // encountered so far int sum = 0; // Maintain the subString till the // current position String s = ""; for (int j = i; j < N; ++j) { // Get the position of the // character in String Q int pos = P.charAt(j) - 'a'; // Add weight to current sum sum += Q.charAt(pos) - '0'; // Add current character to subString s += P.charAt(j); // If sum of characters is <=K // then insert into the set if (sum <= K) { S.add(s); } else { break; } } } // Finding the size of the set return S.size();} // Driver codepublic static void main(String[] args){ String P = "abcde"; String Q = "12345678912345678912345678"; int K = 5; int N = P.length(); System.out.print(distinctSubString(P, Q, K, N));}} // This code is contributed by Rajput-Ji # Python program to find the count of# all the sub-strings with weight of# characters atmost K # Function to find the count of# all the substrings with weight# of characters atmost Kdef distinctSubstring(P, Q, K, N): # Hashmap to store all substrings S = set() # Iterate over all substrings for i in range(0,N): # Maintain the sum of all characters # encountered so far sum = 0; # Maintain the substring till the # current position s = '' for j in range(i,N): # Get the position of the # character in string Q pos = ord(P[j]) - 97 # Add weight to current sum sum = sum + ord(Q[pos]) - 48 # Add current character to substring s += P[j] # If sum of characters is <=K # then insert into the set if (sum <= K): S.add(s) else: break # Finding the size of the set return len(S) # Driver codeP = "abcde"Q = "12345678912345678912345678"K = 5N = len(P) print(distinctSubstring(P, Q, K, N)) # This code is contributed by Sanjit_Prasad // C# program to find the count of// all the sub-Strings with weight of// characters atmost Kusing System;using System.Collections.Generic; class GFG{ // Function to find the count of// all the subStrings with weight// of characters atmost Kstatic int distinctSubString(String P, String Q, int K, int N){ // Hashmap to store all subStrings HashSet<String> S = new HashSet<String>(); // Iterate over all subStrings for (int i = 0; i < N; ++i) { // c the sum of all characters // encountered so far int sum = 0; // Maintain the subString till the // current position String s = ""; for (int j = i; j < N; ++j) { // Get the position of the // character in String Q int pos = P[j] - 'a'; // Add weight to current sum sum += Q[pos] - '0'; // Add current character to subString s += P[j]; // If sum of characters is <=K // then insert into the set if (sum <= K) { S.Add(s); } else { break; } } } // Finding the size of the set return S.Count;} // Driver codepublic static void Main(String[] args){ String P = "abcde"; String Q = "12345678912345678912345678"; int K = 5; int N = P.Length; Console.Write(distinctSubString(P, Q, K, N));}} // This code is contributed by 29AjayKumar <script> // Javascript program to find the count of// all the sub-Strings with weight of// characters atmost K // Function to find the count of// all the subStrings with weight// of characters atmost Kfunction distinctSubString(P, Q, K, N){ // Hashmap to store all subStrings let S = new Set(); // Iterate over all subStrings for (let i = 0; i < N; ++i) { // Maintain the sum of all characters // encountered so far let sum = 0; // Maintain the subString till the // current position let s = ""; for (let j = i; j < N; ++j) { // Get the position of the // character in String Q let pos = P[j].charCodeAt() - 'a'.charCodeAt(); // Add weight to current sum sum += Q[pos].charCodeAt() - '0'.charCodeAt(); // Add current character to subString s += P[j]; // If sum of characters is <=K // then insert into the set if (sum <= K) { S.add(s); } else { break; } } } // Finding the size of the set return S.size;} // Driver code let P = "abcde"; let Q = "12345678912345678912345678"; let K = 5; let N = P.length; document.write(distinctSubString(P, Q, K, N)); </script> 7 Time Complexity: O(N2) Sanjit_Prasad Rajput-Ji 29AjayKumar splevel62 khushboogoyal499 arorakashish0911 Hash Advanced Data Structure Hash Pattern Searching Hash Pattern Searching Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. 2-3 Trees | (Search, Insert and Deletion) Extendible Hashing (Dynamic approach to DBMS) Count of strings whose prefix match with the given string to a given length k Quad Tree Proof that Dominant Set of a Graph is NP-Complete Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum) Internal Working of HashMap in Java Hashing | Set 1 (Introduction) Hashing | Set 3 (Open Addressing) Count pairs with given sum
[ { "code": null, "e": 24462, "s": 24434, "text": "\n07 Dec, 2021" }, { "code": null, "e": 24723, "s": 24462, "text": "Given a string P consisting of small English letters and a string Q consisting of weight of all characters of English alphabet such that for all ‘i’, 0 ≤ Q[i] ≤ 9. The task is to find the total numbers of unique substring with sum of weights atmost K.Examples:" }, { "code": null, "e": 25093, "s": 24723, "text": "Input: P = “ababab”, Q = “12345678912345678912345678”, K = 5 Output: 7 Explanation: The substrings with the sum of weights of individual characters ≤ 5 are: “a”, “ab”, “b”, “bc”, “c”, “d”, “e”Input: P = “acbacbacaa”, Q = “12300045600078900012345000”, K = 2 Output: 3 Explanation: The substrings with the sum of weights of individual characters ≤ 2 are: “a”, “b”, “aa” " }, { "code": null, "e": 25225, "s": 25093, "text": "Approach: The idea is to use an unordered set to store the unique values. The following steps are followed to compute the answer: " }, { "code": null, "e": 25357, "s": 25225, "text": "Iterate over all the substrings using the nested loops and maintain the sum of the weight of all the characters encountered so far." }, { "code": null, "e": 25434, "s": 25357, "text": "If the sum of characters is not greater than K, then insert it in a hashmap." }, { "code": null, "e": 25475, "s": 25434, "text": "Finally, output the size of the hashmap." }, { "code": null, "e": 25528, "s": 25475, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 25532, "s": 25528, "text": "C++" }, { "code": null, "e": 25537, "s": 25532, "text": "Java" }, { "code": null, "e": 25545, "s": 25537, "text": "Python3" }, { "code": null, "e": 25548, "s": 25545, "text": "C#" }, { "code": null, "e": 25559, "s": 25548, "text": "Javascript" }, { "code": "// C++ program to find the count of// all the sub-strings with weight of// characters atmost K#include <bits/stdc++.h>using namespace std; // Function to find the count of// all the substrings with weight// of characters atmost Kint distinctSubstring(string& P, string& Q, int K, int N){ // Hashmap to store all substrings unordered_set<string> S; // Iterate over all substrings for (int i = 0; i < N; ++i) { // Maintain the sum of all characters // encountered so far int sum = 0; // Maintain the substring till the // current position string s; for (int j = i; j < N; ++j) { // Get the position of the // character in string Q int pos = P[j] - 'a'; // Add weight to current sum sum += Q[pos] - '0'; // Add current character to substring s += P[j]; // If sum of characters is <=K // then insert into the set if (sum <= K) { S.insert(s); } else { break; } } } // Finding the size of the set return S.size();} // Driver codeint main(){ string P = \"abcde\"; string Q = \"12345678912345678912345678\"; int K = 5; int N = P.length(); cout << distinctSubstring(P, Q, K, N); return 0;}", "e": 26939, "s": 25559, "text": null }, { "code": "// Java program to find the count of// all the sub-Strings with weight of// characters atmost Kimport java.util.*; class GFG{ // Function to find the count of// all the subStrings with weight// of characters atmost Kstatic int distinctSubString(String P, String Q, int K, int N){ // Hashmap to store all subStrings HashSet<String> S = new HashSet<String>(); // Iterate over all subStrings for (int i = 0; i < N; ++i) { // Maintain the sum of all characters // encountered so far int sum = 0; // Maintain the subString till the // current position String s = \"\"; for (int j = i; j < N; ++j) { // Get the position of the // character in String Q int pos = P.charAt(j) - 'a'; // Add weight to current sum sum += Q.charAt(pos) - '0'; // Add current character to subString s += P.charAt(j); // If sum of characters is <=K // then insert into the set if (sum <= K) { S.add(s); } else { break; } } } // Finding the size of the set return S.size();} // Driver codepublic static void main(String[] args){ String P = \"abcde\"; String Q = \"12345678912345678912345678\"; int K = 5; int N = P.length(); System.out.print(distinctSubString(P, Q, K, N));}} // This code is contributed by Rajput-Ji", "e": 28432, "s": 26939, "text": null }, { "code": "# Python program to find the count of# all the sub-strings with weight of# characters atmost K # Function to find the count of# all the substrings with weight# of characters atmost Kdef distinctSubstring(P, Q, K, N): # Hashmap to store all substrings S = set() # Iterate over all substrings for i in range(0,N): # Maintain the sum of all characters # encountered so far sum = 0; # Maintain the substring till the # current position s = '' for j in range(i,N): # Get the position of the # character in string Q pos = ord(P[j]) - 97 # Add weight to current sum sum = sum + ord(Q[pos]) - 48 # Add current character to substring s += P[j] # If sum of characters is <=K # then insert into the set if (sum <= K): S.add(s) else: break # Finding the size of the set return len(S) # Driver codeP = \"abcde\"Q = \"12345678912345678912345678\"K = 5N = len(P) print(distinctSubstring(P, Q, K, N)) # This code is contributed by Sanjit_Prasad", "e": 29598, "s": 28432, "text": null }, { "code": "// C# program to find the count of// all the sub-Strings with weight of// characters atmost Kusing System;using System.Collections.Generic; class GFG{ // Function to find the count of// all the subStrings with weight// of characters atmost Kstatic int distinctSubString(String P, String Q, int K, int N){ // Hashmap to store all subStrings HashSet<String> S = new HashSet<String>(); // Iterate over all subStrings for (int i = 0; i < N; ++i) { // c the sum of all characters // encountered so far int sum = 0; // Maintain the subString till the // current position String s = \"\"; for (int j = i; j < N; ++j) { // Get the position of the // character in String Q int pos = P[j] - 'a'; // Add weight to current sum sum += Q[pos] - '0'; // Add current character to subString s += P[j]; // If sum of characters is <=K // then insert into the set if (sum <= K) { S.Add(s); } else { break; } } } // Finding the size of the set return S.Count;} // Driver codepublic static void Main(String[] args){ String P = \"abcde\"; String Q = \"12345678912345678912345678\"; int K = 5; int N = P.Length; Console.Write(distinctSubString(P, Q, K, N));}} // This code is contributed by 29AjayKumar", "e": 31098, "s": 29598, "text": null }, { "code": "<script> // Javascript program to find the count of// all the sub-Strings with weight of// characters atmost K // Function to find the count of// all the subStrings with weight// of characters atmost Kfunction distinctSubString(P, Q, K, N){ // Hashmap to store all subStrings let S = new Set(); // Iterate over all subStrings for (let i = 0; i < N; ++i) { // Maintain the sum of all characters // encountered so far let sum = 0; // Maintain the subString till the // current position let s = \"\"; for (let j = i; j < N; ++j) { // Get the position of the // character in String Q let pos = P[j].charCodeAt() - 'a'.charCodeAt(); // Add weight to current sum sum += Q[pos].charCodeAt() - '0'.charCodeAt(); // Add current character to subString s += P[j]; // If sum of characters is <=K // then insert into the set if (sum <= K) { S.add(s); } else { break; } } } // Finding the size of the set return S.size;} // Driver code let P = \"abcde\"; let Q = \"12345678912345678912345678\"; let K = 5; let N = P.length; document.write(distinctSubString(P, Q, K, N)); </script>", "e": 32570, "s": 31098, "text": null }, { "code": null, "e": 32572, "s": 32570, "text": "7" }, { "code": null, "e": 32597, "s": 32574, "text": "Time Complexity: O(N2)" }, { "code": null, "e": 32611, "s": 32597, "text": "Sanjit_Prasad" }, { "code": null, "e": 32621, "s": 32611, "text": "Rajput-Ji" }, { "code": null, "e": 32633, "s": 32621, "text": "29AjayKumar" }, { "code": null, "e": 32643, "s": 32633, "text": "splevel62" }, { "code": null, "e": 32660, "s": 32643, "text": "khushboogoyal499" }, { "code": null, "e": 32677, "s": 32660, "text": "arorakashish0911" }, { "code": null, "e": 32682, "s": 32677, "text": "Hash" }, { "code": null, "e": 32706, "s": 32682, "text": "Advanced Data Structure" }, { "code": null, "e": 32711, "s": 32706, "text": "Hash" }, { "code": null, "e": 32729, "s": 32711, "text": "Pattern Searching" }, { "code": null, "e": 32734, "s": 32729, "text": "Hash" }, { "code": null, "e": 32752, "s": 32734, "text": "Pattern Searching" }, { "code": null, "e": 32850, "s": 32752, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 32892, "s": 32850, "text": "2-3 Trees | (Search, Insert and Deletion)" }, { "code": null, "e": 32938, "s": 32892, "text": "Extendible Hashing (Dynamic approach to DBMS)" }, { "code": null, "e": 33016, "s": 32938, "text": "Count of strings whose prefix match with the given string to a given length k" }, { "code": null, "e": 33026, "s": 33016, "text": "Quad Tree" }, { "code": null, "e": 33076, "s": 33026, "text": "Proof that Dominant Set of a Graph is NP-Complete" }, { "code": null, "e": 33161, "s": 33076, "text": "Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)" }, { "code": null, "e": 33197, "s": 33161, "text": "Internal Working of HashMap in Java" }, { "code": null, "e": 33228, "s": 33197, "text": "Hashing | Set 1 (Introduction)" }, { "code": null, "e": 33262, "s": 33228, "text": "Hashing | Set 3 (Open Addressing)" } ]
Convert decimal fraction to binary number in C++
In this tutorial, we will be discussing a program to convert decimal fraction to a binary number. For this we will be provided with a decimal fraction and integer ‘k’. Our task is to convert the given decimal fraction into its binary equivalent upto the given ‘k’ digits of decimal precision. Live Demo #include<bits/stdc++.h> using namespace std; //converting decimal to binary number string convert_tobinary(double num, int k_prec) { string binary = ""; //getting the integer part int Integral = num; //getting the fractional part double fractional = num - Integral; //converting integer to binary while (Integral) { int rem = Integral % 2; binary.push_back(rem +'0'); Integral /= 2; } //reversing the string to get the //required binary number reverse(binary.begin(),binary.end()); binary.push_back('.'); //converting fraction to binary while (k_prec--) { fractional *= 2; int fract_bit = fractional; if (fract_bit == 1) { fractional -= fract_bit; binary.push_back(1 + '0'); } else binary.push_back(0 + '0'); } return binary; } int main() { double n = 4.47; int k = 3; cout << convert_tobinary(n, k) << "\n"; n = 6.986 , k = 5; cout << convert_tobinary(n, k); return 0; } 100.011 110.11111
[ { "code": null, "e": 1160, "s": 1062, "text": "In this tutorial, we will be discussing a program to convert decimal fraction to a binary number." }, { "code": null, "e": 1355, "s": 1160, "text": "For this we will be provided with a decimal fraction and integer ‘k’. Our task is to convert the given decimal fraction into its binary equivalent upto the given ‘k’ digits of decimal precision." }, { "code": null, "e": 1366, "s": 1355, "text": " Live Demo" }, { "code": null, "e": 2370, "s": 1366, "text": "#include<bits/stdc++.h>\nusing namespace std;\n//converting decimal to binary number\nstring convert_tobinary(double num, int k_prec) {\n string binary = \"\";\n //getting the integer part\n int Integral = num;\n //getting the fractional part\n double fractional = num - Integral;\n //converting integer to binary\n while (Integral) {\n int rem = Integral % 2;\n binary.push_back(rem +'0');\n Integral /= 2;\n }\n //reversing the string to get the\n //required binary number\n reverse(binary.begin(),binary.end());\n binary.push_back('.');\n //converting fraction to binary\n while (k_prec--) {\n fractional *= 2;\n int fract_bit = fractional;\n if (fract_bit == 1) {\n fractional -= fract_bit;\n binary.push_back(1 + '0');\n } else\n binary.push_back(0 + '0');\n }\n return binary;\n}\nint main() {\n double n = 4.47;\n int k = 3;\n cout << convert_tobinary(n, k) << \"\\n\";\n n = 6.986 , k = 5;\n cout << convert_tobinary(n, k);\n return 0;\n}" }, { "code": null, "e": 2388, "s": 2370, "text": "100.011\n110.11111" } ]
Live CNN Training Dashboard: Hyperparameters Tuning | Towards Data Science
Why we need to build a Live CNN Training Dashboard?IntroductionPrerequisitesSystem descriptionHow to create an environment and start training?ConclusionReferences Why we need to build a Live CNN Training Dashboard? Introduction Prerequisites System description How to create an environment and start training? Conclusion References When I studied in mathematical lyceum, my teacher taught me that the best way to understand something is to visualize it. For example, we had a wooden board, plasticine, and metal wire to be able to visualize stereometry problems. It helped a lot to develop visual thinking and skills in solving challenging tasks. I truly believe that real data scientists should understand algorithms and have a feeling on how to improve it if something works not fine. Especially in the area of deep learning. In my mind, the best way to develop these skills is to see how the model is trained, what happens when you change hyperparameters. This is the reason why I want to share how to build a simple dashboard for CNN live training with the opportunity to tune a few hyperparameters online. There is common knowledge that if we choose too big learning rate, we will see how our loss function explodes (our model will not converge); if we choose too small learning rate, the training process can last too long. What about dropout? There is an opinion that dropout reduces overfitting. I get to check everything myself even if I believe, because to know and to believe are different things. Below is the short demo of my dashboard. Red dots on loss function & accuracy plots represent the training dataset, blue dots represent the test dataset. Dashboard displays the following statistics: loss function value in time; accuracy in time; distribution of activation maps values for the last step; history of hyperparameters changes (table); For this task, I am using AlexNet architecture to classify images on 10 classes: Alaskan malamute, baboon, echidna, giant panda, hippo, king penguin, llama, otter, red panda, and wombat. Images are downloaded from the ImageNet. I will not go into details in this post, but you can explore file get_dataset.py. During training, the following parameters can be tweaked: optimizer;This parameter determines the algorithm we use to optimize our model. I use only Adam and SGD with Nesterov momentum. If you want to understand the optimization technique more, I encourage you to watch a video from Stanford here. There are many fantastic details about optimization. learning rate;This parameter determines how fast we are moving down the slope when we are updating weights. For basic gradient descent formula for weights updates look like this: w := w — lr * dw. weight decay;For our case it is simply L2 regularization: R(W) = SUM(W * W). It is considered that weight decay does not make a lot of sense in the context of CNN, but you can see it yourself how it works live. You can read some description of L1 and L2 regularization techniques here. dropout;Common regularization strategy for neural network. The idea is randomly set some neurons to zero on each training step. The hyperparameter is the probability to drop each neuron. Common value is 0.5 (50%). We can choose any integer value from 20 to 80. (in %) More details can be watched in the same video that I shared for optimizer. Script can be easily changed to add additional functionality. I assume that you understand what is CNN and have basic knowledge of the following: PostgreSQL (to store real-time data); Dash (to build dashboard, https://plotly.com/dash/); PyTorch (to build CNN models); There are four main parts of the system: dataset, model, database, and dashboard/UI. These parts interact with each other to successfully run the system. Firstly I will describe each of these parts and after that, I will give a short description of how they interact with each other. For this exercise, I use a dataset from the ImageNet that contains the following ten classes: Alaskan malamute, baboon, echidna, giant panda, hippo, king penguin, llama, otter, red panda, and wombat. To download all images from ImageNet, I can run python board.py from the following location: ../cnn_live_training. Firstly, I have to find classes ids and save them to some variable: The ImageNet stores URLs to images. Some URLs/images might not exist anymore. To get these URLs based on class id, I use the following function: To download all images I use a loop where I download image by image. Below is the function to download image by URL: The full version of the code can be seen in the file get_dataset.py. You can easily change these classes to other classes or you can even change the ImageNet to your custom dataset. For the training, I am using by default the AlexNet architecture with Adam or SGD with Nesterov momentum optimizer. Optionally, the VGG16 can be chosen. Models can be imported either from the file models.py or from torchvision.models. The second option has the opportunity to use pre-trained weights. Dataset preparation happens in the file data_preparation.py. The training process happens in the file train.py. I don’t have the goal to explain in this article how to build a pipeline for training CNN that is why I am not going into detail in this part. But I am happy to recommend the amazing course CS231n from Stanford and particularly HW2(Q4), where you can learn step by step how to build this pipeline. This homework can be found here. Before running the system, we have to create dl_playground DB in PostgreSQL with the schema cnn_live_training that contains three following tables: parameters, statistics, activations. parametersThis table contains only one row with current parameters for the training CNN model. When we change any parameters in our dashboard (file board.py), this data will be updated in the parameters SQL table. The table contains the following columns: optimizer;Text data type. Can have two values: ‘Adam’ and ‘SGD+Nesterov’. learning_rate;Double data type. The values are between 0 and 1 with the 0.00005 step. weight_decay;Double data type. The values are between 0 and 1 with the 0.05 step. dropout;Integer data type. The values are between 20 and 80. (It is assumed that the values are in %.) dt_updates;Timestamp data type. Indicates date and time when data was modified. stop_train;Boolean data type. Indicates if we have to stop training. statistics This table contains statistics of the training process. Data is updated every --n-print step. The table contains the following columns: dt_started;Timestamp data type. Indicates when current training was started. model_name;Text data type. In this case, it can be only ‘MyAlexNet’. epoch;Integer data type. Indicates the number of training epochs. step;Integer data type. Indicates the number of training steps. optimizer;Text data type. Can have two values: ‘Adam’ and ‘SGD+Nesterov’. learning_rate;Double data type. The values are between 0 and 1 with the 0.00005 step. weight_decay;Double data type. The values are between 0 and 1 with the 0.05 step. dropout;Integer data type. The values are between 20 and 80. dt;Timestamp data type. Indicates date and time when data was modified. train_loss;Double data type. The value of loss function for the training dataset on the last step. train_accuracy;Double data type. The value of accuracy for the training dataset on the last step. validate_loss;Double data type. The value of loss function for the validation dataset on the last step. validate_accuracy;Double data type. The value of accuracy for the validation dataset on the last step. activationsThis table contains the current distribution of weights in activation maps for all convolutional and fully connected layers. The table contains the following columns: nn_part;Text data type. Can be either ‘features’ or ‘classifier’. layer_type;Text data type. Can be either ‘conv’ or ‘fc’. number;Integer data type. Indicates the layer number in a ‘nn’ part. weights;Double[] data type. Indicates average values of weights in bins. num_weights;Integer[] data type. Indicates numbers of values in bins. The dashboard consists of three main blocks: control panel, loss function & accuracy, and activation maps (distribution). These blocks are built using dash containers. Control panel contains filters of parameters and “submit parameters” button that can be used to send chosen parameters to described above table “parameters”.There are four filters: optimizer, learning rate, weight decay, and dropout. Below is the script, how to create an optimizer filter (other filters are similar): After that I create a container that contains all four filters: How to create other parts of the control panel can be found in the file board.py. Loss function & Accuracy contains a table with the history of used parameters and two plots with train/test loss function and accuracy values in time. Data is updated every one second (time interval can be changed) automatically. Below is the script on how to create a table and button to stop training in the dashboard (I replaced real styles with short names for reading convenience): Script to create plot template can be seen below: Values are uploaded dynamically from PostgreSQL using callbacks (I provide only template for reading convenience): I need to use a callback here because I want to update the plot and the table every 1 second. So, I have to use this variable as an input. Activation maps (distribution) contains plots with distribution of activation map for each layer for the last step. Data is updated every one second (time interval can be changed) automatically. The activations of the first two layers look similar to a normal distribution with the mean value in 0. The reason for this is for the first two layers we apply normalization. To understand more, I encourage you to watch a lecture from Stanford here. Below is the script to create a container with the plots. It is similar to the previous container with loss function and accuracy plots: The callback for the activation maps is similar to the “loss function & accuracy”: It’s time to wrap everything up. To recall back, my goal is to train CNN live and being able to control this process by changing hyperparameters. So how does it happen? I have a dashboard where we can see the progress of the CNN training and where we have some filters that we can choose and activate by pushing the button “Submit parameters”. What happens after that? All these parameters are sent to the table parameters in my database in PostgreSQL, using callback in the file board.py and function update_params: At the same time, the script train.py connects to a database at the end of each training step, seeking to update the optimizer if parameters get updated: Every n_step step data from training is saved to statistics and activations tables in database in PostgreSQL: And this data simultaneously displayed in the dashboard because the script board.py every 1 sec. connects to the same tables: All parameters are displayed in the table by extracting this information from the table : If we want to stop training beforehand, we can push the button “Stop Training” below the table. After pushing the button, the callback will change the variable stop_train from False to True in the parameters table in my database: At the same time, the script train.py check this parameter every training step and if it is True, training will be interrupted. Without practical recommendations on what parameters to use to start training, this post will not be complete. If you want to see that everything works, but don’t have time for experiments, you can start from the following parameters: optimizer: Adam; learning rate: 0.0003; weight decay: 0; dropout: 50%; If you want to see how the model explodes, just increase the learning rate to 0.01. Good luck with your experiments. I will give a short description for Ubuntu, using a virtual environment (venv). Install Python 3.8: sudo apt install python3.8-minimalInstall virtual environment with Python 3.8: sudo apt-get install python3.8-venvCreate virtual environment: run from cnn_live_training folder: python3.8 -m venv venvActivate environment: source venv/bin/activateInstall required packages in the virtual environment: pip install -r requirements.txt Install Python 3.8: sudo apt install python3.8-minimal Install virtual environment with Python 3.8: sudo apt-get install python3.8-venv Create virtual environment: run from cnn_live_training folder: python3.8 -m venv venv Activate environment: source venv/bin/activate Install required packages in the virtual environment: pip install -r requirements.txt Run from the ../cnn_live_training command python get_dataset.py Run from the ../cnn_live_training folder two following commands python board.pypython train.py In this story, I wanted to share my idea on how to nurture the feeling of training CNN. From one side, the idea is simple: build a training pipeline, create a dashboard and connect them using a database. But there are many annoying details that not possible to put in one small story. All script and additional details can be found in my git repository. If this post makes someone interested and give additional knowledge, I will become slightly happier because it means that I reached my goal. I will appreciate any comments, constructive criticism, or questions, feel free to leave your feedback below or you can reach me via LinkedIn. [1] L. Fei-Fei, R. Krishna and D. Xu, CS231n: Convolutional Neural Networks for Visual Recognition (2020), Stanford University [2] A. Krizhevsky, I. Sutskever and G. E. Hinton, ImageNet Classification with Deep Convolutional Neural Networks (2012), NeurIPS 2012 [3] A. Nagpal, L1 and L2 Regularization Methods (2017), Towards Data Science
[ { "code": null, "e": 335, "s": 172, "text": "Why we need to build a Live CNN Training Dashboard?IntroductionPrerequisitesSystem descriptionHow to create an environment and start training?ConclusionReferences" }, { "code": null, "e": 387, "s": 335, "text": "Why we need to build a Live CNN Training Dashboard?" }, { "code": null, "e": 400, "s": 387, "text": "Introduction" }, { "code": null, "e": 414, "s": 400, "text": "Prerequisites" }, { "code": null, "e": 433, "s": 414, "text": "System description" }, { "code": null, "e": 482, "s": 433, "text": "How to create an environment and start training?" }, { "code": null, "e": 493, "s": 482, "text": "Conclusion" }, { "code": null, "e": 504, "s": 493, "text": "References" }, { "code": null, "e": 819, "s": 504, "text": "When I studied in mathematical lyceum, my teacher taught me that the best way to understand something is to visualize it. For example, we had a wooden board, plasticine, and metal wire to be able to visualize stereometry problems. It helped a lot to develop visual thinking and skills in solving challenging tasks." }, { "code": null, "e": 1283, "s": 819, "text": "I truly believe that real data scientists should understand algorithms and have a feeling on how to improve it if something works not fine. Especially in the area of deep learning. In my mind, the best way to develop these skills is to see how the model is trained, what happens when you change hyperparameters. This is the reason why I want to share how to build a simple dashboard for CNN live training with the opportunity to tune a few hyperparameters online." }, { "code": null, "e": 1681, "s": 1283, "text": "There is common knowledge that if we choose too big learning rate, we will see how our loss function explodes (our model will not converge); if we choose too small learning rate, the training process can last too long. What about dropout? There is an opinion that dropout reduces overfitting. I get to check everything myself even if I believe, because to know and to believe are different things." }, { "code": null, "e": 1835, "s": 1681, "text": "Below is the short demo of my dashboard. Red dots on loss function & accuracy plots represent the training dataset, blue dots represent the test dataset." }, { "code": null, "e": 1880, "s": 1835, "text": "Dashboard displays the following statistics:" }, { "code": null, "e": 1909, "s": 1880, "text": "loss function value in time;" }, { "code": null, "e": 1927, "s": 1909, "text": "accuracy in time;" }, { "code": null, "e": 1985, "s": 1927, "text": "distribution of activation maps values for the last step;" }, { "code": null, "e": 2029, "s": 1985, "text": "history of hyperparameters changes (table);" }, { "code": null, "e": 2397, "s": 2029, "text": "For this task, I am using AlexNet architecture to classify images on 10 classes: Alaskan malamute, baboon, echidna, giant panda, hippo, king penguin, llama, otter, red panda, and wombat. Images are downloaded from the ImageNet. I will not go into details in this post, but you can explore file get_dataset.py. During training, the following parameters can be tweaked:" }, { "code": null, "e": 2690, "s": 2397, "text": "optimizer;This parameter determines the algorithm we use to optimize our model. I use only Adam and SGD with Nesterov momentum. If you want to understand the optimization technique more, I encourage you to watch a video from Stanford here. There are many fantastic details about optimization." }, { "code": null, "e": 2887, "s": 2690, "text": "learning rate;This parameter determines how fast we are moving down the slope when we are updating weights. For basic gradient descent formula for weights updates look like this: w := w — lr * dw." }, { "code": null, "e": 3173, "s": 2887, "text": "weight decay;For our case it is simply L2 regularization: R(W) = SUM(W * W). It is considered that weight decay does not make a lot of sense in the context of CNN, but you can see it yourself how it works live. You can read some description of L1 and L2 regularization techniques here." }, { "code": null, "e": 3516, "s": 3173, "text": "dropout;Common regularization strategy for neural network. The idea is randomly set some neurons to zero on each training step. The hyperparameter is the probability to drop each neuron. Common value is 0.5 (50%). We can choose any integer value from 20 to 80. (in %) More details can be watched in the same video that I shared for optimizer." }, { "code": null, "e": 3578, "s": 3516, "text": "Script can be easily changed to add additional functionality." }, { "code": null, "e": 3662, "s": 3578, "text": "I assume that you understand what is CNN and have basic knowledge of the following:" }, { "code": null, "e": 3700, "s": 3662, "text": "PostgreSQL (to store real-time data);" }, { "code": null, "e": 3753, "s": 3700, "text": "Dash (to build dashboard, https://plotly.com/dash/);" }, { "code": null, "e": 3784, "s": 3753, "text": "PyTorch (to build CNN models);" }, { "code": null, "e": 4068, "s": 3784, "text": "There are four main parts of the system: dataset, model, database, and dashboard/UI. These parts interact with each other to successfully run the system. Firstly I will describe each of these parts and after that, I will give a short description of how they interact with each other." }, { "code": null, "e": 4383, "s": 4068, "text": "For this exercise, I use a dataset from the ImageNet that contains the following ten classes: Alaskan malamute, baboon, echidna, giant panda, hippo, king penguin, llama, otter, red panda, and wombat. To download all images from ImageNet, I can run python board.py from the following location: ../cnn_live_training." }, { "code": null, "e": 4451, "s": 4383, "text": "Firstly, I have to find classes ids and save them to some variable:" }, { "code": null, "e": 4596, "s": 4451, "text": "The ImageNet stores URLs to images. Some URLs/images might not exist anymore. To get these URLs based on class id, I use the following function:" }, { "code": null, "e": 4713, "s": 4596, "text": "To download all images I use a loop where I download image by image. Below is the function to download image by URL:" }, { "code": null, "e": 4895, "s": 4713, "text": "The full version of the code can be seen in the file get_dataset.py. You can easily change these classes to other classes or you can even change the ImageNet to your custom dataset." }, { "code": null, "e": 5308, "s": 4895, "text": "For the training, I am using by default the AlexNet architecture with Adam or SGD with Nesterov momentum optimizer. Optionally, the VGG16 can be chosen. Models can be imported either from the file models.py or from torchvision.models. The second option has the opportunity to use pre-trained weights. Dataset preparation happens in the file data_preparation.py. The training process happens in the file train.py." }, { "code": null, "e": 5639, "s": 5308, "text": "I don’t have the goal to explain in this article how to build a pipeline for training CNN that is why I am not going into detail in this part. But I am happy to recommend the amazing course CS231n from Stanford and particularly HW2(Q4), where you can learn step by step how to build this pipeline. This homework can be found here." }, { "code": null, "e": 5824, "s": 5639, "text": "Before running the system, we have to create dl_playground DB in PostgreSQL with the schema cnn_live_training that contains three following tables: parameters, statistics, activations." }, { "code": null, "e": 6080, "s": 5824, "text": "parametersThis table contains only one row with current parameters for the training CNN model. When we change any parameters in our dashboard (file board.py), this data will be updated in the parameters SQL table. The table contains the following columns:" }, { "code": null, "e": 6154, "s": 6080, "text": "optimizer;Text data type. Can have two values: ‘Adam’ and ‘SGD+Nesterov’." }, { "code": null, "e": 6240, "s": 6154, "text": "learning_rate;Double data type. The values are between 0 and 1 with the 0.00005 step." }, { "code": null, "e": 6322, "s": 6240, "text": "weight_decay;Double data type. The values are between 0 and 1 with the 0.05 step." }, { "code": null, "e": 6425, "s": 6322, "text": "dropout;Integer data type. The values are between 20 and 80. (It is assumed that the values are in %.)" }, { "code": null, "e": 6505, "s": 6425, "text": "dt_updates;Timestamp data type. Indicates date and time when data was modified." }, { "code": null, "e": 6574, "s": 6505, "text": "stop_train;Boolean data type. Indicates if we have to stop training." }, { "code": null, "e": 6721, "s": 6574, "text": "statistics This table contains statistics of the training process. Data is updated every --n-print step. The table contains the following columns:" }, { "code": null, "e": 6798, "s": 6721, "text": "dt_started;Timestamp data type. Indicates when current training was started." }, { "code": null, "e": 6867, "s": 6798, "text": "model_name;Text data type. In this case, it can be only ‘MyAlexNet’." }, { "code": null, "e": 6933, "s": 6867, "text": "epoch;Integer data type. Indicates the number of training epochs." }, { "code": null, "e": 6997, "s": 6933, "text": "step;Integer data type. Indicates the number of training steps." }, { "code": null, "e": 7071, "s": 6997, "text": "optimizer;Text data type. Can have two values: ‘Adam’ and ‘SGD+Nesterov’." }, { "code": null, "e": 7157, "s": 7071, "text": "learning_rate;Double data type. The values are between 0 and 1 with the 0.00005 step." }, { "code": null, "e": 7239, "s": 7157, "text": "weight_decay;Double data type. The values are between 0 and 1 with the 0.05 step." }, { "code": null, "e": 7300, "s": 7239, "text": "dropout;Integer data type. The values are between 20 and 80." }, { "code": null, "e": 7372, "s": 7300, "text": "dt;Timestamp data type. Indicates date and time when data was modified." }, { "code": null, "e": 7471, "s": 7372, "text": "train_loss;Double data type. The value of loss function for the training dataset on the last step." }, { "code": null, "e": 7569, "s": 7471, "text": "train_accuracy;Double data type. The value of accuracy for the training dataset on the last step." }, { "code": null, "e": 7673, "s": 7569, "text": "validate_loss;Double data type. The value of loss function for the validation dataset on the last step." }, { "code": null, "e": 7776, "s": 7673, "text": "validate_accuracy;Double data type. The value of accuracy for the validation dataset on the last step." }, { "code": null, "e": 7954, "s": 7776, "text": "activationsThis table contains the current distribution of weights in activation maps for all convolutional and fully connected layers. The table contains the following columns:" }, { "code": null, "e": 8020, "s": 7954, "text": "nn_part;Text data type. Can be either ‘features’ or ‘classifier’." }, { "code": null, "e": 8077, "s": 8020, "text": "layer_type;Text data type. Can be either ‘conv’ or ‘fc’." }, { "code": null, "e": 8146, "s": 8077, "text": "number;Integer data type. Indicates the layer number in a ‘nn’ part." }, { "code": null, "e": 8219, "s": 8146, "text": "weights;Double[] data type. Indicates average values of weights in bins." }, { "code": null, "e": 8289, "s": 8219, "text": "num_weights;Integer[] data type. Indicates numbers of values in bins." }, { "code": null, "e": 8457, "s": 8289, "text": "The dashboard consists of three main blocks: control panel, loss function & accuracy, and activation maps (distribution). These blocks are built using dash containers." }, { "code": null, "e": 8691, "s": 8457, "text": "Control panel contains filters of parameters and “submit parameters” button that can be used to send chosen parameters to described above table “parameters”.There are four filters: optimizer, learning rate, weight decay, and dropout." }, { "code": null, "e": 8775, "s": 8691, "text": "Below is the script, how to create an optimizer filter (other filters are similar):" }, { "code": null, "e": 8839, "s": 8775, "text": "After that I create a container that contains all four filters:" }, { "code": null, "e": 8921, "s": 8839, "text": "How to create other parts of the control panel can be found in the file board.py." }, { "code": null, "e": 9151, "s": 8921, "text": "Loss function & Accuracy contains a table with the history of used parameters and two plots with train/test loss function and accuracy values in time. Data is updated every one second (time interval can be changed) automatically." }, { "code": null, "e": 9308, "s": 9151, "text": "Below is the script on how to create a table and button to stop training in the dashboard (I replaced real styles with short names for reading convenience):" }, { "code": null, "e": 9358, "s": 9308, "text": "Script to create plot template can be seen below:" }, { "code": null, "e": 9473, "s": 9358, "text": "Values are uploaded dynamically from PostgreSQL using callbacks (I provide only template for reading convenience):" }, { "code": null, "e": 9612, "s": 9473, "text": "I need to use a callback here because I want to update the plot and the table every 1 second. So, I have to use this variable as an input." }, { "code": null, "e": 9807, "s": 9612, "text": "Activation maps (distribution) contains plots with distribution of activation map for each layer for the last step. Data is updated every one second (time interval can be changed) automatically." }, { "code": null, "e": 10058, "s": 9807, "text": "The activations of the first two layers look similar to a normal distribution with the mean value in 0. The reason for this is for the first two layers we apply normalization. To understand more, I encourage you to watch a lecture from Stanford here." }, { "code": null, "e": 10195, "s": 10058, "text": "Below is the script to create a container with the plots. It is similar to the previous container with loss function and accuracy plots:" }, { "code": null, "e": 10278, "s": 10195, "text": "The callback for the activation maps is similar to the “loss function & accuracy”:" }, { "code": null, "e": 10622, "s": 10278, "text": "It’s time to wrap everything up. To recall back, my goal is to train CNN live and being able to control this process by changing hyperparameters. So how does it happen? I have a dashboard where we can see the progress of the CNN training and where we have some filters that we can choose and activate by pushing the button “Submit parameters”." }, { "code": null, "e": 10795, "s": 10622, "text": "What happens after that? All these parameters are sent to the table parameters in my database in PostgreSQL, using callback in the file board.py and function update_params:" }, { "code": null, "e": 10949, "s": 10795, "text": "At the same time, the script train.py connects to a database at the end of each training step, seeking to update the optimizer if parameters get updated:" }, { "code": null, "e": 11059, "s": 10949, "text": "Every n_step step data from training is saved to statistics and activations tables in database in PostgreSQL:" }, { "code": null, "e": 11185, "s": 11059, "text": "And this data simultaneously displayed in the dashboard because the script board.py every 1 sec. connects to the same tables:" }, { "code": null, "e": 11275, "s": 11185, "text": "All parameters are displayed in the table by extracting this information from the table :" }, { "code": null, "e": 11505, "s": 11275, "text": "If we want to stop training beforehand, we can push the button “Stop Training” below the table. After pushing the button, the callback will change the variable stop_train from False to True in the parameters table in my database:" }, { "code": null, "e": 11633, "s": 11505, "text": "At the same time, the script train.py check this parameter every training step and if it is True, training will be interrupted." }, { "code": null, "e": 11868, "s": 11633, "text": "Without practical recommendations on what parameters to use to start training, this post will not be complete. If you want to see that everything works, but don’t have time for experiments, you can start from the following parameters:" }, { "code": null, "e": 11885, "s": 11868, "text": "optimizer: Adam;" }, { "code": null, "e": 11908, "s": 11885, "text": "learning rate: 0.0003;" }, { "code": null, "e": 11925, "s": 11908, "text": "weight decay: 0;" }, { "code": null, "e": 11939, "s": 11925, "text": "dropout: 50%;" }, { "code": null, "e": 12056, "s": 11939, "text": "If you want to see how the model explodes, just increase the learning rate to 0.01. Good luck with your experiments." }, { "code": null, "e": 12136, "s": 12056, "text": "I will give a short description for Ubuntu, using a virtual environment (venv)." }, { "code": null, "e": 12487, "s": 12136, "text": "Install Python 3.8: sudo apt install python3.8-minimalInstall virtual environment with Python 3.8: sudo apt-get install python3.8-venvCreate virtual environment: run from cnn_live_training folder: python3.8 -m venv venvActivate environment: source venv/bin/activateInstall required packages in the virtual environment: pip install -r requirements.txt" }, { "code": null, "e": 12542, "s": 12487, "text": "Install Python 3.8: sudo apt install python3.8-minimal" }, { "code": null, "e": 12623, "s": 12542, "text": "Install virtual environment with Python 3.8: sudo apt-get install python3.8-venv" }, { "code": null, "e": 12709, "s": 12623, "text": "Create virtual environment: run from cnn_live_training folder: python3.8 -m venv venv" }, { "code": null, "e": 12756, "s": 12709, "text": "Activate environment: source venv/bin/activate" }, { "code": null, "e": 12842, "s": 12756, "text": "Install required packages in the virtual environment: pip install -r requirements.txt" }, { "code": null, "e": 12906, "s": 12842, "text": "Run from the ../cnn_live_training command python get_dataset.py" }, { "code": null, "e": 12970, "s": 12906, "text": "Run from the ../cnn_live_training folder two following commands" }, { "code": null, "e": 13001, "s": 12970, "text": "python board.pypython train.py" }, { "code": null, "e": 13355, "s": 13001, "text": "In this story, I wanted to share my idea on how to nurture the feeling of training CNN. From one side, the idea is simple: build a training pipeline, create a dashboard and connect them using a database. But there are many annoying details that not possible to put in one small story. All script and additional details can be found in my git repository." }, { "code": null, "e": 13639, "s": 13355, "text": "If this post makes someone interested and give additional knowledge, I will become slightly happier because it means that I reached my goal. I will appreciate any comments, constructive criticism, or questions, feel free to leave your feedback below or you can reach me via LinkedIn." }, { "code": null, "e": 13766, "s": 13639, "text": "[1] L. Fei-Fei, R. Krishna and D. Xu, CS231n: Convolutional Neural Networks for Visual Recognition (2020), Stanford University" }, { "code": null, "e": 13901, "s": 13766, "text": "[2] A. Krizhevsky, I. Sutskever and G. E. Hinton, ImageNet Classification with Deep Convolutional Neural Networks (2012), NeurIPS 2012" } ]
Building predictive models with MyAnimeList and Sklearn (Part 1) | by Frank Hopkins | Towards Data Science
MyAnimeList is one of the largest online data repositories for anime on the internet with listings ranging from TV series to Manga comics and data dating back to ~1905 (for anyone interested, this is 活動写真/Katsudou Shashin). Luckily this data is all available on Kaggle and comes split into different components/data-frames: user ratings and anime listing information. Given my mutual love for anime and all things data, I thought it would be cool to combine data and to build some predictive models and basic recommendation systems in Python. I will discuss the intricacies of such in more detail below. The first section of my work with the MyAnimeList will focus on some machine learning techniques used to predict user rating scores using a variety of features that were computed for analysis using Sklearn. The second section will follow this post and will hone in on some simple techniques used to recommend anime content, based on both user rating correlations and feature variables. Prior to performing any analysis, install the necessary packages: import numpy as npimport pandas as pdimport sklearnimport matplotlib.pyplot as pltimport seaborn as sbfrom sklearn.preprocessing import LabelEncoderfrom sklearn.model_selection import train_test_splitfrom sklearn.ensemble import RandomForestClassifier, RandomForestRegressorfrom sklearn.model_selection import GridSearchCVfrom sklearn.metrics import accuracy_scorefrom sklearn.neural_network import MLPRegressor, MLPClassifierfrom sklearn import metricsfrom matplotlib import rcParamsimport joblibfrom sklearn.tree import export_graphvizimport pydotfrom IPython.display import Image Import both data-frames from your local: local_1 = '/Users/hopkif05/Desktop/rating.csv'ratings = pd.read_csv(local_1)local_2 = '/Users/hopkif05/Desktop/AnimeList.csv'anime_list = pd.read_csv(local_2) And concatenate them on a unique identifier, which in this case is their anime_id: anime = pd.merge(ratings, anime_list, on=’anime_id’)anime.head() You can see from the above data-frame that we now have every single user rating in the database, which has be merged with all of the metadata associated with that piece of content. There are ~ 8 million user ratings here, with 33 rows, which each represent a potential feature variable for our models. For subsequent analysis I have chosen user_id, anime_id, rating_x, title_english, type, source, scored_by, score, favorites, members, popularity and studio to be variables included in the model; and stored these in a new data-frame: anime_df = anime[[‘user_id’,’anime_id’,’rating_x’,’title_english’,’type’,’source’,’scored_by’,’score’,’favorites’,’members’,’popularity’,’studio’]].copy()anime_df.head(100) You may notice that some of the variables are categorical and are currently not in the correct format to include in any subsequent modelling. In order to prep these features we can one-hot encode certain columns in our data. I will use our source feature as an example: enconder = LabelEncoder()source_labels = enconder.fit_transform(anime_df[‘source’])source_mappings = {index: label for index, label in enumerate(enconder.classes_)}source_mappings>>>>>> {0: '4-koma manga', 1: 'Book', 2: 'Card game', 3: 'Digital manga', 4: 'Game', 5: 'Light novel', 6: 'Manga', 7: 'Music', 8: 'Novel', 9: 'Original', 10: 'Other', 11: 'Picture book', 12: 'Radio', 13: 'Unknown', 14: 'Visual novel', 15: 'Web manga'} As you can see from our source variable, every source type has been allocated a numeric variable which can be used as feature variables for our predictive models. Repeat this for the variables you wish to use in your modelling and merge them back to your original data-frame: anime_df[‘source_label’] = source_labelsanime_df[‘type_label’] = type_labelsanime_df[‘title_label’] = title_labels Now we have prepped our feature variables, we are ready to start modelling the data. Prior to this, it is important to visualise the relationship between the variables in our data-frame. As we are looking to predict user ratings, we want to see how correlated our variables are to rating_x: plt.figure(figsize=(12,10))cor = anime_df.corr()sb.heatmap(cor, annot=True, cmap=plt.cm.Dark2)plt.show() It is useful to also look at the distribution of overall scores in our data: sb.distplot(anime_df[‘score’], color=”orchid”) Due to the fact that our outcome variable (rating_x) yielded little correlation to any of the feature variables that were computed or otherwise, I created a binary outcome measure, which uses the mean user rating score as the threshold of an above or below average score: anime_df.rating_x.mean()anime_df[‘rating_bracket’] = np.where(anime_df[‘rating_x’] >= 6.14, ‘1’, ‘0’) We now want to separate this data into train, test and validation components, splitting our outcome measure and feature variables accordingly. As there are ~8 million rows of data in our current frame, running models will be potentially time-consuming; for this reason I took a random sample of 250k from the anime_df data-frame: ## Take a random sampleanime_sample = anime_df.sample(n=250000, random_state=1)features = anime_sample[[‘favorites’,’members’, ‘popularity’,’scored_by’,’source_label’, ‘type_label’,’title_label’]].copy()labels = anime_sample[‘rating_bracket’]## Train — testX_train, X_test, y_train, y_test = train_test_split(features, labels, test_size=0.4, random_state=42)## ValidationX_val, X_test, y_val, y_test = train_test_split(X_test, y_test, test_size=0.5, random_state=42) The first model we are going to train is a random forest; you can read more about training a random forest model in an earlier blog post I composed. Prior to running our random forest model, we are going to first optimise two input parameters, which are n_estimators and max_depth, which represent the number of decision trees and depth of each tree, respectively: def print_results(results): print(‘BEST PARAMS: {}\n’.format(results.best_params_))means = results.cv_results_[‘mean_test_score’] stds = results.cv_results_[‘std_test_score’] for mean, std, params in zip(means, stds, results.cv_results_[‘params’]): print(‘{} (+/-{}) for {}’.format(round(mean, 3), round(std * 2, 3), params))rf = RandomForestClassifier()parameters = { ‘n_estimators’: [50,100], ‘max_depth’: [10,20,None]}rf_cv = GridSearchCV(rf, parameters, cv=5)rf_cv.fit(X_train, y_train.values.ravel())print_results(rf_cv) We can store our best parameter settings to our local machine to use for model validation at the end of this assessment: joblib.dump(rf_cv.best_estimator_, ‘/.../.../.../AnimeRecs/RF_model.pkl’) We can now run our random forest using our optimised parameters and print the accuracy of our model: rf_model = RandomForestClassifier(n_estimators=100, max_depth=20)rf_model.fit(X_train, y_train)rf_predicted_values = rf_model.predict(X_test)score = accuracy_score(y_test,rf_predicted_values)print(score)>>>> Accuracy: 0.695905 You can see that we have achieved ~70% accuracy with our random forest model, which suggests we can predict a user rating score with fairly high degree of accuracy using the feature variables we created for this analysis. Before drawing this conclusion it is important to assess which variables were pertinent to model success. We can view the relative importance of our input variables as such: for name, importance in zip(features.columns, rf_model.feature_importances_):... print(name, “=”, importance)favorites = 0.2778530464552122members = 0.19784680037872093popularity = 0.1759396781482536scored_by = 0.15560656547263593source_label = 0.0509643924057434type_label = 0.04176822827070301title_label = 0.10002128886873099 The above variables are in descending order, with the most important features at the top. You can see that the variables we encoded yielded little importance to our model and likely have minimal predictive capability in this context. The most pertinent feature variable in terms of relative importance to our model was how many favourites the piece of anime content has, which is entirely intuitive. We can also visualise an individual decision tree in our random forest model to see how the data is passed: export_graphviz(tree, feature_names=features.columns, out_file=’rf_anime_tree.dot’, filled=True, rounded=True) The second model we are going to train is a multilayer perceptron (MLP), which is a class of feed-forward neural networks, meant to emulate the neurophysiological process by which the brain processes and stores information. MLPs are often utilised in supervised learning problems, where they train on a set of input–output pairs and learn to model the correlation between them. For more information on MLP, please read one of my earlier posts. The hyper-parameters we are going to optimise for our MLP model are hidden_layer_sizes, which is the number of nodes in the ith hidden layer and activation, which is the activation function for the hidden layer. For the activation function, we are going to determine which function is preferable between a logistic and relu activation: Logistic: uses a sigmoid function (such as logistic regression), returns f(x) = 1 / (1 + exp(-x)) Relu: the rectified linear unit function, returns f(x) = max(0, x). If the value value is positive, this function outputs the input value, otherwise it passes a zero mlp = MLPClassifier()parameters = { ‘hidden_layer_sizes’: [(10,), (50,)], ‘activation’: [‘relu’, ‘logistic’]}mlp_cv = GridSearchCV(mlp, parameters, cv=5)mlp_cv.fit(X_train, y_train.values.ravel())print_results(mlp_cv) We can store our best parameter settings to our local machine to use for model validation at the end of this assessment: joblib.dump(rf_cv.best_estimator_, ‘/.../.../.../AnimeRecs/MLP_model.pkl’) We can now run our MLP model using our optimised parameters and print the accuracy of our model: rf_model = RandomForestClassifier(n_estimators=100, max_depth=20)rf_model.fit(X_train, y_train)rf_predicted_values = rf_model.predict(X_test)score = accuracy_score(y_test,rf_predicted_values)print(score)>>>> Accuracy: 0.6758805 As you can see the model achieves a ~68% accuracy score, which is lower than our random forest model. Due to how MLP models cycle through data, it is important to assess the model’s performance after distinct epochs/passes through the entire training dataset. To assess this, we can visualise the validation loss of the model over time: loss_values = mlp_model.loss_curve_mlp_model.scoreplt.plot(loss_values)plt.ylim((0.61,0.640))plt.axvline(10,0,0.7)plt.show() You can see from the above visual that after 10 epochs the validation loss starts to increase, which suggests the model is over-fitting. There could be value in reducing the number of complete passes through our training data, thus decreasing the time to train our model. It is however worth considering that this could reduce the overall accuracy of the model. As previously mentioned, we split our data such that we had a validation set which would be used to compare models in the final stage of this assessment. This data is completely unseen to either of the two models used, so can be used as a strong gauge of the performance of the models we have trained. Furthermore, we have also been storing the best estimators using a variety of hyper-parameters for this purpose. The following code will loop through your stored best estimators: models = {}for mdl in [‘MLP’, ‘RF’]: models[mdl] = joblib.load(‘/Users/hopkif05/Desktop/AnimeRecs/{}_model.pkl’.format(mdl))models The following code will create a function to evaluate and compare the accuracy of both models used. As seen, the model.predict() function exists between both start and end-time functions, which means we can compute a latency value for each model, to assess how long they take to compute predictions: def evaluate_model(name, model, features, labels): start = time() pred = model.predict(features) end = time() accuracy = round(accuracy_score(labels, pred), 3) print('{} -- Accuracy: {} / Latency: {}ms'.format(name, accuracy, round((end - start)*1000, 1))) We can now loop through our models to determine their accuracy: for name, mdl in models.items(): evaluate_model(name, mdl, X_val, y_val)MLP -- Accuracy: 0.683 / Latency: 675.7msRF -- Accuracy: 0.713 / Latency: 668.9ms As seen above the random forest model performs the best on the unseen validation data. Interestingly it also has a shorter latency, which suggests that the MLP model have been trained for too long; which as previously mentioned can have negative impacts on training a neural network. It can therefore be summarised that our random forest model can predict user ratings on MyAnimeList, using a variety of feature variables. This results is not hugely surprising considering random forest models perform well with classification problems, such as the binary outcome measure used with our anime data. Given the feature importance we computed for our random forest output, it can be further determined that the variables most pertinent to the accuracy of our random forest model were: favorites (0.28), members (0.20), popularity (0.18) and scored_by (0.16). These findings are supported by the correlation matrix printed above and are unsurprising given the nature of these metrics; it is thus expected that they yield relatively high predictive capabilities in comparison to our one-hot encoded variables.
[ { "code": null, "e": 1162, "s": 172, "text": "MyAnimeList is one of the largest online data repositories for anime on the internet with listings ranging from TV series to Manga comics and data dating back to ~1905 (for anyone interested, this is 活動写真/Katsudou Shashin). Luckily this data is all available on Kaggle and comes split into different components/data-frames: user ratings and anime listing information. Given my mutual love for anime and all things data, I thought it would be cool to combine data and to build some predictive models and basic recommendation systems in Python. I will discuss the intricacies of such in more detail below. The first section of my work with the MyAnimeList will focus on some machine learning techniques used to predict user rating scores using a variety of features that were computed for analysis using Sklearn. The second section will follow this post and will hone in on some simple techniques used to recommend anime content, based on both user rating correlations and feature variables." }, { "code": null, "e": 1228, "s": 1162, "text": "Prior to performing any analysis, install the necessary packages:" }, { "code": null, "e": 1811, "s": 1228, "text": "import numpy as npimport pandas as pdimport sklearnimport matplotlib.pyplot as pltimport seaborn as sbfrom sklearn.preprocessing import LabelEncoderfrom sklearn.model_selection import train_test_splitfrom sklearn.ensemble import RandomForestClassifier, RandomForestRegressorfrom sklearn.model_selection import GridSearchCVfrom sklearn.metrics import accuracy_scorefrom sklearn.neural_network import MLPRegressor, MLPClassifierfrom sklearn import metricsfrom matplotlib import rcParamsimport joblibfrom sklearn.tree import export_graphvizimport pydotfrom IPython.display import Image" }, { "code": null, "e": 1852, "s": 1811, "text": "Import both data-frames from your local:" }, { "code": null, "e": 2011, "s": 1852, "text": "local_1 = '/Users/hopkif05/Desktop/rating.csv'ratings = pd.read_csv(local_1)local_2 = '/Users/hopkif05/Desktop/AnimeList.csv'anime_list = pd.read_csv(local_2)" }, { "code": null, "e": 2094, "s": 2011, "text": "And concatenate them on a unique identifier, which in this case is their anime_id:" }, { "code": null, "e": 2159, "s": 2094, "text": "anime = pd.merge(ratings, anime_list, on=’anime_id’)anime.head()" }, { "code": null, "e": 2694, "s": 2159, "text": "You can see from the above data-frame that we now have every single user rating in the database, which has be merged with all of the metadata associated with that piece of content. There are ~ 8 million user ratings here, with 33 rows, which each represent a potential feature variable for our models. For subsequent analysis I have chosen user_id, anime_id, rating_x, title_english, type, source, scored_by, score, favorites, members, popularity and studio to be variables included in the model; and stored these in a new data-frame:" }, { "code": null, "e": 2867, "s": 2694, "text": "anime_df = anime[[‘user_id’,’anime_id’,’rating_x’,’title_english’,’type’,’source’,’scored_by’,’score’,’favorites’,’members’,’popularity’,’studio’]].copy()anime_df.head(100)" }, { "code": null, "e": 3137, "s": 2867, "text": "You may notice that some of the variables are categorical and are currently not in the correct format to include in any subsequent modelling. In order to prep these features we can one-hot encode certain columns in our data. I will use our source feature as an example:" }, { "code": null, "e": 3569, "s": 3137, "text": "enconder = LabelEncoder()source_labels = enconder.fit_transform(anime_df[‘source’])source_mappings = {index: label for index, label in enumerate(enconder.classes_)}source_mappings>>>>>> {0: '4-koma manga', 1: 'Book', 2: 'Card game', 3: 'Digital manga', 4: 'Game', 5: 'Light novel', 6: 'Manga', 7: 'Music', 8: 'Novel', 9: 'Original', 10: 'Other', 11: 'Picture book', 12: 'Radio', 13: 'Unknown', 14: 'Visual novel', 15: 'Web manga'}" }, { "code": null, "e": 3845, "s": 3569, "text": "As you can see from our source variable, every source type has been allocated a numeric variable which can be used as feature variables for our predictive models. Repeat this for the variables you wish to use in your modelling and merge them back to your original data-frame:" }, { "code": null, "e": 3960, "s": 3845, "text": "anime_df[‘source_label’] = source_labelsanime_df[‘type_label’] = type_labelsanime_df[‘title_label’] = title_labels" }, { "code": null, "e": 4251, "s": 3960, "text": "Now we have prepped our feature variables, we are ready to start modelling the data. Prior to this, it is important to visualise the relationship between the variables in our data-frame. As we are looking to predict user ratings, we want to see how correlated our variables are to rating_x:" }, { "code": null, "e": 4356, "s": 4251, "text": "plt.figure(figsize=(12,10))cor = anime_df.corr()sb.heatmap(cor, annot=True, cmap=plt.cm.Dark2)plt.show()" }, { "code": null, "e": 4433, "s": 4356, "text": "It is useful to also look at the distribution of overall scores in our data:" }, { "code": null, "e": 4480, "s": 4433, "text": "sb.distplot(anime_df[‘score’], color=”orchid”)" }, { "code": null, "e": 4752, "s": 4480, "text": "Due to the fact that our outcome variable (rating_x) yielded little correlation to any of the feature variables that were computed or otherwise, I created a binary outcome measure, which uses the mean user rating score as the threshold of an above or below average score:" }, { "code": null, "e": 4854, "s": 4752, "text": "anime_df.rating_x.mean()anime_df[‘rating_bracket’] = np.where(anime_df[‘rating_x’] >= 6.14, ‘1’, ‘0’)" }, { "code": null, "e": 5184, "s": 4854, "text": "We now want to separate this data into train, test and validation components, splitting our outcome measure and feature variables accordingly. As there are ~8 million rows of data in our current frame, running models will be potentially time-consuming; for this reason I took a random sample of 250k from the anime_df data-frame:" }, { "code": null, "e": 5651, "s": 5184, "text": "## Take a random sampleanime_sample = anime_df.sample(n=250000, random_state=1)features = anime_sample[[‘favorites’,’members’, ‘popularity’,’scored_by’,’source_label’, ‘type_label’,’title_label’]].copy()labels = anime_sample[‘rating_bracket’]## Train — testX_train, X_test, y_train, y_test = train_test_split(features, labels, test_size=0.4, random_state=42)## ValidationX_val, X_test, y_val, y_test = train_test_split(X_test, y_test, test_size=0.5, random_state=42)" }, { "code": null, "e": 6016, "s": 5651, "text": "The first model we are going to train is a random forest; you can read more about training a random forest model in an earlier blog post I composed. Prior to running our random forest model, we are going to first optimise two input parameters, which are n_estimators and max_depth, which represent the number of decision trees and depth of each tree, respectively:" }, { "code": null, "e": 6542, "s": 6016, "text": "def print_results(results): print(‘BEST PARAMS: {}\\n’.format(results.best_params_))means = results.cv_results_[‘mean_test_score’] stds = results.cv_results_[‘std_test_score’] for mean, std, params in zip(means, stds, results.cv_results_[‘params’]): print(‘{} (+/-{}) for {}’.format(round(mean, 3), round(std * 2, 3), params))rf = RandomForestClassifier()parameters = { ‘n_estimators’: [50,100], ‘max_depth’: [10,20,None]}rf_cv = GridSearchCV(rf, parameters, cv=5)rf_cv.fit(X_train, y_train.values.ravel())print_results(rf_cv)" }, { "code": null, "e": 6663, "s": 6542, "text": "We can store our best parameter settings to our local machine to use for model validation at the end of this assessment:" }, { "code": null, "e": 6737, "s": 6663, "text": "joblib.dump(rf_cv.best_estimator_, ‘/.../.../.../AnimeRecs/RF_model.pkl’)" }, { "code": null, "e": 6838, "s": 6737, "text": "We can now run our random forest using our optimised parameters and print the accuracy of our model:" }, { "code": null, "e": 7065, "s": 6838, "text": "rf_model = RandomForestClassifier(n_estimators=100, max_depth=20)rf_model.fit(X_train, y_train)rf_predicted_values = rf_model.predict(X_test)score = accuracy_score(y_test,rf_predicted_values)print(score)>>>> Accuracy: 0.695905" }, { "code": null, "e": 7461, "s": 7065, "text": "You can see that we have achieved ~70% accuracy with our random forest model, which suggests we can predict a user rating score with fairly high degree of accuracy using the feature variables we created for this analysis. Before drawing this conclusion it is important to assess which variables were pertinent to model success. We can view the relative importance of our input variables as such:" }, { "code": null, "e": 7790, "s": 7461, "text": "for name, importance in zip(features.columns, rf_model.feature_importances_):... print(name, “=”, importance)favorites = 0.2778530464552122members = 0.19784680037872093popularity = 0.1759396781482536scored_by = 0.15560656547263593source_label = 0.0509643924057434type_label = 0.04176822827070301title_label = 0.10002128886873099" }, { "code": null, "e": 8190, "s": 7790, "text": "The above variables are in descending order, with the most important features at the top. You can see that the variables we encoded yielded little importance to our model and likely have minimal predictive capability in this context. The most pertinent feature variable in terms of relative importance to our model was how many favourites the piece of anime content has, which is entirely intuitive." }, { "code": null, "e": 8298, "s": 8190, "text": "We can also visualise an individual decision tree in our random forest model to see how the data is passed:" }, { "code": null, "e": 8409, "s": 8298, "text": "export_graphviz(tree, feature_names=features.columns, out_file=’rf_anime_tree.dot’, filled=True, rounded=True)" }, { "code": null, "e": 8853, "s": 8409, "text": "The second model we are going to train is a multilayer perceptron (MLP), which is a class of feed-forward neural networks, meant to emulate the neurophysiological process by which the brain processes and stores information. MLPs are often utilised in supervised learning problems, where they train on a set of input–output pairs and learn to model the correlation between them. For more information on MLP, please read one of my earlier posts." }, { "code": null, "e": 9189, "s": 8853, "text": "The hyper-parameters we are going to optimise for our MLP model are hidden_layer_sizes, which is the number of nodes in the ith hidden layer and activation, which is the activation function for the hidden layer. For the activation function, we are going to determine which function is preferable between a logistic and relu activation:" }, { "code": null, "e": 9287, "s": 9189, "text": "Logistic: uses a sigmoid function (such as logistic regression), returns f(x) = 1 / (1 + exp(-x))" }, { "code": null, "e": 9453, "s": 9287, "text": "Relu: the rectified linear unit function, returns f(x) = max(0, x). If the value value is positive, this function outputs the input value, otherwise it passes a zero" }, { "code": null, "e": 9671, "s": 9453, "text": "mlp = MLPClassifier()parameters = { ‘hidden_layer_sizes’: [(10,), (50,)], ‘activation’: [‘relu’, ‘logistic’]}mlp_cv = GridSearchCV(mlp, parameters, cv=5)mlp_cv.fit(X_train, y_train.values.ravel())print_results(mlp_cv)" }, { "code": null, "e": 9792, "s": 9671, "text": "We can store our best parameter settings to our local machine to use for model validation at the end of this assessment:" }, { "code": null, "e": 9867, "s": 9792, "text": "joblib.dump(rf_cv.best_estimator_, ‘/.../.../.../AnimeRecs/MLP_model.pkl’)" }, { "code": null, "e": 9964, "s": 9867, "text": "We can now run our MLP model using our optimised parameters and print the accuracy of our model:" }, { "code": null, "e": 10192, "s": 9964, "text": "rf_model = RandomForestClassifier(n_estimators=100, max_depth=20)rf_model.fit(X_train, y_train)rf_predicted_values = rf_model.predict(X_test)score = accuracy_score(y_test,rf_predicted_values)print(score)>>>> Accuracy: 0.6758805" }, { "code": null, "e": 10529, "s": 10192, "text": "As you can see the model achieves a ~68% accuracy score, which is lower than our random forest model. Due to how MLP models cycle through data, it is important to assess the model’s performance after distinct epochs/passes through the entire training dataset. To assess this, we can visualise the validation loss of the model over time:" }, { "code": null, "e": 10654, "s": 10529, "text": "loss_values = mlp_model.loss_curve_mlp_model.scoreplt.plot(loss_values)plt.ylim((0.61,0.640))plt.axvline(10,0,0.7)plt.show()" }, { "code": null, "e": 11016, "s": 10654, "text": "You can see from the above visual that after 10 epochs the validation loss starts to increase, which suggests the model is over-fitting. There could be value in reducing the number of complete passes through our training data, thus decreasing the time to train our model. It is however worth considering that this could reduce the overall accuracy of the model." }, { "code": null, "e": 11431, "s": 11016, "text": "As previously mentioned, we split our data such that we had a validation set which would be used to compare models in the final stage of this assessment. This data is completely unseen to either of the two models used, so can be used as a strong gauge of the performance of the models we have trained. Furthermore, we have also been storing the best estimators using a variety of hyper-parameters for this purpose." }, { "code": null, "e": 11497, "s": 11431, "text": "The following code will loop through your stored best estimators:" }, { "code": null, "e": 11628, "s": 11497, "text": "models = {}for mdl in [‘MLP’, ‘RF’]: models[mdl] = joblib.load(‘/Users/hopkif05/Desktop/AnimeRecs/{}_model.pkl’.format(mdl))models" }, { "code": null, "e": 11928, "s": 11628, "text": "The following code will create a function to evaluate and compare the accuracy of both models used. As seen, the model.predict() function exists between both start and end-time functions, which means we can compute a latency value for each model, to assess how long they take to compute predictions:" }, { "code": null, "e": 12364, "s": 11928, "text": "def evaluate_model(name, model, features, labels): start = time() pred = model.predict(features) end = time() accuracy = round(accuracy_score(labels, pred), 3) print('{} -- Accuracy: {} / Latency: {}ms'.format(name, accuracy, round((end - start)*1000, 1)))" }, { "code": null, "e": 12428, "s": 12364, "text": "We can now loop through our models to determine their accuracy:" }, { "code": null, "e": 12585, "s": 12428, "text": "for name, mdl in models.items(): evaluate_model(name, mdl, X_val, y_val)MLP -- Accuracy: 0.683 / Latency: 675.7msRF -- Accuracy: 0.713 / Latency: 668.9ms" }, { "code": null, "e": 12869, "s": 12585, "text": "As seen above the random forest model performs the best on the unseen validation data. Interestingly it also has a shorter latency, which suggests that the MLP model have been trained for too long; which as previously mentioned can have negative impacts on training a neural network." } ]
RequireJS - NodeJS
The Node adapter can be used along with the implementation of Require and Node's search path. If there is no module configuration used by RequireJS, you can use the existing Node based modules without changing them. You can install the node packages in the node_modules directory of project by using the npm command. Node will load modules only from the local disk and config options such as map, packages, paths, etc. will be applied only when module is loaded by RequireJS. You can install the Node adapter by using the following command which will install the latest release files − npm install requirejs You can install the Node in the following ways as well − You can download the r.js from this link and keep it in your project folder. You can download the r.js from this link and keep it in your project folder. Obtain the source from r.js repository or install it through node dist.js. Obtain the source from r.js repository or install it through node dist.js. To use the node, you need to have require('requirejs') and move the require function in the configuration to the top level main.js file. For instance − var requirejs = require('requirejs'); requirejs.config({ //load the mode modules to top level JS file //by passing the top level main.js require function to requirejs nodeRequire: require }); requirejs(['name1', 'name2'], function (name1, name2) { //by using requirejs config, name1 and name2 are loaded //node's require loads the module, if they did not find these } ); You can make code module work with RequireJS and Node, without requiring users of library, and then use the amdefine package to accomplish this work. For instance − if (typeof define !== 'function') { var define = require('amdefine')(module); } define(function(require) { var myval = require('dependency'); //The returned value from the function can be used //as module which is visible to Node. return function () {}; }); Node module uses the RequireJS optimizer as an optimize method by using the function call instead of using the command line tool. For instance − var requirejs = require('requirejs'); var config = { baseUrl: '../directory/scripts', name: 'main', out: '../build/main-built.js' }; requirejs.optimize(config, function (buildResponse) { //The text output of the modules specify by using buildResponse //and loads the built file for the contents //get the optimized file contents by using config.out var contents = fs.readFileSync(config.out, 'utf8'); }, function(err) { //code for optimization err callback }); Print Add Notes Bookmark this page
[ { "code": null, "e": 2159, "s": 1842, "text": "The Node adapter can be used along with the implementation of Require and Node's search path. If there is no module configuration used by RequireJS, you can use the existing Node based modules without changing them. You can install the node packages in the node_modules directory of project by using the npm command." }, { "code": null, "e": 2318, "s": 2159, "text": "Node will load modules only from the local disk and config options such as map, packages, paths, etc. will be applied only when module is loaded by RequireJS." }, { "code": null, "e": 2428, "s": 2318, "text": "You can install the Node adapter by using the following command which will install the latest release files −" }, { "code": null, "e": 2451, "s": 2428, "text": "npm install requirejs\n" }, { "code": null, "e": 2508, "s": 2451, "text": "You can install the Node in the following ways as well −" }, { "code": null, "e": 2585, "s": 2508, "text": "You can download the r.js from this link and keep it in your project folder." }, { "code": null, "e": 2662, "s": 2585, "text": "You can download the r.js from this link and keep it in your project folder." }, { "code": null, "e": 2738, "s": 2662, "text": "Obtain the source from r.js repository or install it through node dist.js. " }, { "code": null, "e": 2814, "s": 2738, "text": "Obtain the source from r.js repository or install it through node dist.js. " }, { "code": null, "e": 2951, "s": 2814, "text": "To use the node, you need to have require('requirejs') and move the require function in the configuration to the top level main.js file." }, { "code": null, "e": 2966, "s": 2951, "text": "For instance −" }, { "code": null, "e": 3367, "s": 2966, "text": "var requirejs = require('requirejs');\n\nrequirejs.config({\n //load the mode modules to top level JS file \n //by passing the top level main.js require function to requirejs\n nodeRequire: require\n});\n\nrequirejs(['name1', 'name2'],\n function (name1, name2) {\n //by using requirejs config, name1 and name2 are loaded\n //node's require loads the module, if they did not find these\n }\n);" }, { "code": null, "e": 3517, "s": 3367, "text": "You can make code module work with RequireJS and Node, without requiring users of library, and then use the amdefine package to accomplish this work." }, { "code": null, "e": 3532, "s": 3517, "text": "For instance −" }, { "code": null, "e": 3808, "s": 3532, "text": "if (typeof define !== 'function') {\n var define = require('amdefine')(module);\n}\n\ndefine(function(require) {\n var myval = require('dependency');\n\n //The returned value from the function can be used \n //as module which is visible to Node.\n return function () {};\n});" }, { "code": null, "e": 3938, "s": 3808, "text": "Node module uses the RequireJS optimizer as an optimize method by using the function call instead of using the command line tool." }, { "code": null, "e": 3953, "s": 3938, "text": "For instance −" }, { "code": null, "e": 4443, "s": 3953, "text": "var requirejs = require('requirejs');\n\nvar config = {\n baseUrl: '../directory/scripts',\n name: 'main',\n out: '../build/main-built.js'\n};\n\nrequirejs.optimize(config, function (buildResponse) {\n\n //The text output of the modules specify by using buildResponse \n //and loads the built file for the contents\n //get the optimized file contents by using config.out \n var contents = fs.readFileSync(config.out, 'utf8');\n}, function(err) {\n //code for optimization err callback\n});" }, { "code": null, "e": 4450, "s": 4443, "text": " Print" }, { "code": null, "e": 4461, "s": 4450, "text": " Add Notes" } ]
How to write ETL operations in Python | by hotglue | Towards Data Science
In this article, you’ll learn how to work with Excel/CSV files in a Python environment to clean and transform raw data into a more ingestible format. This is typically useful for data integration. This example will touch on many common ETL operations such as filter, reduce, explode, and flatten. The code for these examples is available publicly on GitHub here, along with descriptions that mirror the information I’ll walk you through. These samples rely on two open source Python packages: pandas: a widely used open source data analysis and manipulation tool. More info on their site and PyPi. gluestick: a small open source Python package containing util functions for ETL maintained by the hotglue team. More info on PyPi and GitHub. Without further ado, let’s dive in! This example leverages sample Quickbooks data from the Quickbooks Sandbox environment, and was initially created in a hotglue environment — a light-weight data integration tool for startups. Feel free to follow along with the Jupyter Notebook on GitHub below! github.com Let’s start by reading the data. This example is built on a hotglue environment with data coming from Quickbooks. In hotglue, the data is placed in the local sync-output folder in a CSV format. We will use the gluestick package to read the raw data in the input folder into a dictionary of pandas dataframes using the read_csv_folder function. By specifying index_cols={'Invoice': 'DocNumber'} the Invoices dataframe will use the DocNumber column as an index. By specifying converters, we can use ast to parse the JSON data in the Line and CustomField columns. Let’s take a look at what data we’re working with. For simplicity, I’ve selected the columns I’d like to work with and saved it to input_df. Typically in hotglue you can configure this using a field map, but I've done it manually here. Let’s clean up the data by renaming the columns to more readable names. CustomerRef__value -> CustomerIdCustomerRef__name -> CustomerMetaData_LastUpdatedTime -> LastUpdatedMetaData_CreateTime -> CreatedOnCurrencyRef__name -> CurrencyCurrencyRef__value -> CurrencyCode The Line column is actually a serialized JSON object provided by Quickbooks with several useful elements in it. We'll need to start by flattening the JSON and then exploding into unique columns so we can work with the data. Again, we’ll use the gluestick package to accomplish this. The explode_json_to_rows function handles the flattening and exploding in one step. To avoid exploding too many levels of this object, we'll specify max_level=1 Here is a snippet from one to give you an idea. [{ 'Id': '1', 'LineNum': '1', 'Amount': 275.0, 'DetailType': 'SalesItemLineDetail', 'SalesItemLineDetail': { 'ItemRef': { 'value': '5', 'name': 'Rock Fountain' }, 'ItemAccountRef': { 'value': '79', 'name': 'Sales of Product Income' }, 'TaxCodeRef': { 'value': 'TAX', 'name': None } }, 'SubTotalLineDetail': None, 'DiscountLineDetail': None}] For our purposes, we only want to work with rows with a Line.DetailType of SalesItemLineDetail (we dont need sub-total lines). This is a common ETL operation known as filtering and is accomplished easily with pandas Look at some of the entries from the Line column we exploded. You'll notice they are name value pairs in JSON. Let’s use gluestick again to explode these into new columns via the json_tuple_to_cols function. We'll need to specify lookup_keys - in our case, the key_prop=name and value_prop=value Take a look at the CustomField column. Below is an example of an entry [{'DefinitionId': '1', 'Name': 'Crew #', 'Type': 'StringType', 'StringValue': '102'}] You can see this is JSON encoded data, specifying one custom field: Crew # with value 102 To explode this, we’ll need to reduce this as we only care about the Name and StringValue. We can use gluestick's explode_json_to_cols function with an array_to_dict_reducer to accomplish this. Our final data looks something like below. In this sample, we went through several basic ETL operations using a real world example all with basic Python tools. Feel free to check out the open source hotglue recipes for more samples in the future. Thanks for reading!
[ { "code": null, "e": 244, "s": 47, "text": "In this article, you’ll learn how to work with Excel/CSV files in a Python environment to clean and transform raw data into a more ingestible format. This is typically useful for data integration." }, { "code": null, "e": 344, "s": 244, "text": "This example will touch on many common ETL operations such as filter, reduce, explode, and flatten." }, { "code": null, "e": 485, "s": 344, "text": "The code for these examples is available publicly on GitHub here, along with descriptions that mirror the information I’ll walk you through." }, { "code": null, "e": 540, "s": 485, "text": "These samples rely on two open source Python packages:" }, { "code": null, "e": 645, "s": 540, "text": "pandas: a widely used open source data analysis and manipulation tool. More info on their site and PyPi." }, { "code": null, "e": 787, "s": 645, "text": "gluestick: a small open source Python package containing util functions for ETL maintained by the hotglue team. More info on PyPi and GitHub." }, { "code": null, "e": 823, "s": 787, "text": "Without further ado, let’s dive in!" }, { "code": null, "e": 1014, "s": 823, "text": "This example leverages sample Quickbooks data from the Quickbooks Sandbox environment, and was initially created in a hotglue environment — a light-weight data integration tool for startups." }, { "code": null, "e": 1083, "s": 1014, "text": "Feel free to follow along with the Jupyter Notebook on GitHub below!" }, { "code": null, "e": 1094, "s": 1083, "text": "github.com" }, { "code": null, "e": 1127, "s": 1094, "text": "Let’s start by reading the data." }, { "code": null, "e": 1438, "s": 1127, "text": "This example is built on a hotglue environment with data coming from Quickbooks. In hotglue, the data is placed in the local sync-output folder in a CSV format. We will use the gluestick package to read the raw data in the input folder into a dictionary of pandas dataframes using the read_csv_folder function." }, { "code": null, "e": 1655, "s": 1438, "text": "By specifying index_cols={'Invoice': 'DocNumber'} the Invoices dataframe will use the DocNumber column as an index. By specifying converters, we can use ast to parse the JSON data in the Line and CustomField columns." }, { "code": null, "e": 1891, "s": 1655, "text": "Let’s take a look at what data we’re working with. For simplicity, I’ve selected the columns I’d like to work with and saved it to input_df. Typically in hotglue you can configure this using a field map, but I've done it manually here." }, { "code": null, "e": 1963, "s": 1891, "text": "Let’s clean up the data by renaming the columns to more readable names." }, { "code": null, "e": 2159, "s": 1963, "text": "CustomerRef__value -> CustomerIdCustomerRef__name -> CustomerMetaData_LastUpdatedTime -> LastUpdatedMetaData_CreateTime -> CreatedOnCurrencyRef__name -> CurrencyCurrencyRef__value -> CurrencyCode" }, { "code": null, "e": 2383, "s": 2159, "text": "The Line column is actually a serialized JSON object provided by Quickbooks with several useful elements in it. We'll need to start by flattening the JSON and then exploding into unique columns so we can work with the data." }, { "code": null, "e": 2603, "s": 2383, "text": "Again, we’ll use the gluestick package to accomplish this. The explode_json_to_rows function handles the flattening and exploding in one step. To avoid exploding too many levels of this object, we'll specify max_level=1" }, { "code": null, "e": 2651, "s": 2603, "text": "Here is a snippet from one to give you an idea." }, { "code": null, "e": 3125, "s": 2651, "text": "[{ 'Id': '1', 'LineNum': '1', 'Amount': 275.0, 'DetailType': 'SalesItemLineDetail', 'SalesItemLineDetail': { 'ItemRef': { 'value': '5', 'name': 'Rock Fountain' }, 'ItemAccountRef': { 'value': '79', 'name': 'Sales of Product Income' }, 'TaxCodeRef': { 'value': 'TAX', 'name': None } }, 'SubTotalLineDetail': None, 'DiscountLineDetail': None}]" }, { "code": null, "e": 3341, "s": 3125, "text": "For our purposes, we only want to work with rows with a Line.DetailType of SalesItemLineDetail (we dont need sub-total lines). This is a common ETL operation known as filtering and is accomplished easily with pandas" }, { "code": null, "e": 3452, "s": 3341, "text": "Look at some of the entries from the Line column we exploded. You'll notice they are name value pairs in JSON." }, { "code": null, "e": 3637, "s": 3452, "text": "Let’s use gluestick again to explode these into new columns via the json_tuple_to_cols function. We'll need to specify lookup_keys - in our case, the key_prop=name and value_prop=value" }, { "code": null, "e": 3708, "s": 3637, "text": "Take a look at the CustomField column. Below is an example of an entry" }, { "code": null, "e": 3794, "s": 3708, "text": "[{'DefinitionId': '1', 'Name': 'Crew #', 'Type': 'StringType', 'StringValue': '102'}]" }, { "code": null, "e": 3884, "s": 3794, "text": "You can see this is JSON encoded data, specifying one custom field: Crew # with value 102" }, { "code": null, "e": 4078, "s": 3884, "text": "To explode this, we’ll need to reduce this as we only care about the Name and StringValue. We can use gluestick's explode_json_to_cols function with an array_to_dict_reducer to accomplish this." }, { "code": null, "e": 4238, "s": 4078, "text": "Our final data looks something like below. In this sample, we went through several basic ETL operations using a real world example all with basic Python tools." } ]
Why, How and When to apply Feature Selection | by Sudharsan Asaithambi | Towards Data Science
Modern day datasets are very rich in information with data collected from millions of IoT devices and sensors. This makes the data high dimensional and it is quite common to see datasets with hundreds of features and is not unusual to see it go to tens of thousands. Feature Selection is a very critical component in a Data Scientist’s workflow. When presented data with very high dimensionality, models usually choke because Training time increases exponentially with number of features.Models have increasing risk of overfitting with increasing number of features. Training time increases exponentially with number of features. Models have increasing risk of overfitting with increasing number of features. Feature Selection methods helps with these problems by reducing the dimensions without much loss of the total information. It also helps to make sense of the features and its importance. In this article, I discuss following feature selection techniques and their traits. Filter MethodsWrapper Methods andEmbedded Methods. Filter Methods Wrapper Methods and Embedded Methods. Filter Methods considers the relationship between features and the target variable to compute the importance of features. F Test is a statistical test used to compare between models and check if the difference is significant between the model. F-Test does a hypothesis testing model X and Y where X is a model created by just a constant and Y is the model created by a constant and a feature. The least square errors in both the models are compared and checks if the difference in errors between model X and Y are significant or introduced by chance. F-Test is useful in feature selection as we get to know the significance of each feature in improving the model. Scikit learn provides the Selecting K best features using F-Test. sklearn.feature_selection.f_regression For Classification tasks sklearn.feature_selection.f_classif There are some drawbacks of using F-Test to select your features. F-Test checks for and only captures linear relationships between features and labels. A highly correlated feature is given higher score and less correlated features are given lower score. Correlation is highly deceptive as it doesn’t capture strong non-linear relationships. Correlation is highly deceptive as it doesn’t capture strong non-linear relationships. 2. Using summary statistics like correlation may be a bad idea, as illustrated by Anscombe’s quartet. Mutual Information between two variables measures the dependence of one variable to another. If X and Y are two variables, and If X and Y are independent, then no information about Y can be obtained by knowing X or vice versa. Hence their mutual information is 0.If X is a deterministic function of Y, then we can determine X from Y and Y from X with mutual information 1.When we have Y = f(X,Z,M,N), 0 < mutual information < 1 If X and Y are independent, then no information about Y can be obtained by knowing X or vice versa. Hence their mutual information is 0. If X is a deterministic function of Y, then we can determine X from Y and Y from X with mutual information 1. When we have Y = f(X,Z,M,N), 0 < mutual information < 1 We can select our features from feature space by ranking their mutual information with the target variable. Advantage of using mutual information over F-Test is, it does well with the non-linear relationship between feature and target variable. Sklearn offers feature selection with Mutual Information for regression and classification tasks. sklearn.feature_selection.mututal_info_regression sklearn.feature_selection.mututal_info_classif This method removes features with variation below a certain cutoff. The idea is when a feature doesn’t vary much within itself, it generally has very little predictive power. sklearn.feature_selection.VarianceThreshold Variance Threshold doesn’t consider the relationship of features with the target variable. Wrapper Methods generate models with a subsets of feature and gauge their model performances. This method allows you to search for the best feature w.r.t model performance and add them to your feature subset one after the other. For data with n features, ->On first round ‘n’ models are created with individual feature and the best predictive feature is selected. ->On second round, ‘n-1’ models are created with each feature and the previously selected feature. ->This is repeated till a best subset of ‘m’ features are selected. As the name suggests, this method eliminates worst performing features on a particular model one after the other until the best subset of features are known. For data with n features, ->On first round ‘n-1’ models are created with combination of all features except one. The least performing feature is removed -> On second round ‘n-2’ models are created by removing another feature. Wrapper Methods promises you a best set of features with a extensive greedy search. But the main drawbacks of wrapper methods is the sheer amount of models that needs to be trained. It is computationally very expensive and is infeasible with large number of features. Feature selection can also be acheived by the insights provided by some Machine Learning models. LASSO Linear Regression can be used for feature selections. Lasso Regression is performed by adding an extra term to the cost function of Linear Regression. This apart from preventing overfitting also reduces the coefficients of less important features to zero. Tree based models calculates feature importance for they need to keep the best performing features as close to the root of the tree. Constructing a decision tree involves calculating the best predictive feature. The feature importance in tree based models are calculated based on Gini Index, Entropy or Chi-Square value. Feature Selection as most things in Data Science is highly context and data dependent and there is no one stop solution for Feature Selection. The best way to go forward is to understand the mechanism of each methods and use when required. I mainly use feature selection techinques to get insights about the features and their relative importance with the target variable. Please comment below on which feature selection technique do you use.
[ { "code": null, "e": 439, "s": 172, "text": "Modern day datasets are very rich in information with data collected from millions of IoT devices and sensors. This makes the data high dimensional and it is quite common to see datasets with hundreds of features and is not unusual to see it go to tens of thousands." }, { "code": null, "e": 598, "s": 439, "text": "Feature Selection is a very critical component in a Data Scientist’s workflow. When presented data with very high dimensionality, models usually choke because" }, { "code": null, "e": 739, "s": 598, "text": "Training time increases exponentially with number of features.Models have increasing risk of overfitting with increasing number of features." }, { "code": null, "e": 802, "s": 739, "text": "Training time increases exponentially with number of features." }, { "code": null, "e": 881, "s": 802, "text": "Models have increasing risk of overfitting with increasing number of features." }, { "code": null, "e": 1068, "s": 881, "text": "Feature Selection methods helps with these problems by reducing the dimensions without much loss of the total information. It also helps to make sense of the features and its importance." }, { "code": null, "e": 1152, "s": 1068, "text": "In this article, I discuss following feature selection techniques and their traits." }, { "code": null, "e": 1203, "s": 1152, "text": "Filter MethodsWrapper Methods andEmbedded Methods." }, { "code": null, "e": 1218, "s": 1203, "text": "Filter Methods" }, { "code": null, "e": 1238, "s": 1218, "text": "Wrapper Methods and" }, { "code": null, "e": 1256, "s": 1238, "text": "Embedded Methods." }, { "code": null, "e": 1378, "s": 1256, "text": "Filter Methods considers the relationship between features and the target variable to compute the importance of features." }, { "code": null, "e": 1500, "s": 1378, "text": "F Test is a statistical test used to compare between models and check if the difference is significant between the model." }, { "code": null, "e": 1649, "s": 1500, "text": "F-Test does a hypothesis testing model X and Y where X is a model created by just a constant and Y is the model created by a constant and a feature." }, { "code": null, "e": 1807, "s": 1649, "text": "The least square errors in both the models are compared and checks if the difference in errors between model X and Y are significant or introduced by chance." }, { "code": null, "e": 1920, "s": 1807, "text": "F-Test is useful in feature selection as we get to know the significance of each feature in improving the model." }, { "code": null, "e": 1986, "s": 1920, "text": "Scikit learn provides the Selecting K best features using F-Test." }, { "code": null, "e": 2025, "s": 1986, "text": "sklearn.feature_selection.f_regression" }, { "code": null, "e": 2050, "s": 2025, "text": "For Classification tasks" }, { "code": null, "e": 2086, "s": 2050, "text": "sklearn.feature_selection.f_classif" }, { "code": null, "e": 2340, "s": 2086, "text": "There are some drawbacks of using F-Test to select your features. F-Test checks for and only captures linear relationships between features and labels. A highly correlated feature is given higher score and less correlated features are given lower score." }, { "code": null, "e": 2427, "s": 2340, "text": "Correlation is highly deceptive as it doesn’t capture strong non-linear relationships." }, { "code": null, "e": 2514, "s": 2427, "text": "Correlation is highly deceptive as it doesn’t capture strong non-linear relationships." }, { "code": null, "e": 2616, "s": 2514, "text": "2. Using summary statistics like correlation may be a bad idea, as illustrated by Anscombe’s quartet." }, { "code": null, "e": 2743, "s": 2616, "text": "Mutual Information between two variables measures the dependence of one variable to another. If X and Y are two variables, and" }, { "code": null, "e": 3044, "s": 2743, "text": "If X and Y are independent, then no information about Y can be obtained by knowing X or vice versa. Hence their mutual information is 0.If X is a deterministic function of Y, then we can determine X from Y and Y from X with mutual information 1.When we have Y = f(X,Z,M,N), 0 < mutual information < 1" }, { "code": null, "e": 3181, "s": 3044, "text": "If X and Y are independent, then no information about Y can be obtained by knowing X or vice versa. Hence their mutual information is 0." }, { "code": null, "e": 3291, "s": 3181, "text": "If X is a deterministic function of Y, then we can determine X from Y and Y from X with mutual information 1." }, { "code": null, "e": 3347, "s": 3291, "text": "When we have Y = f(X,Z,M,N), 0 < mutual information < 1" }, { "code": null, "e": 3455, "s": 3347, "text": "We can select our features from feature space by ranking their mutual information with the target variable." }, { "code": null, "e": 3592, "s": 3455, "text": "Advantage of using mutual information over F-Test is, it does well with the non-linear relationship between feature and target variable." }, { "code": null, "e": 3690, "s": 3592, "text": "Sklearn offers feature selection with Mutual Information for regression and classification tasks." }, { "code": null, "e": 3787, "s": 3690, "text": "sklearn.feature_selection.mututal_info_regression sklearn.feature_selection.mututal_info_classif" }, { "code": null, "e": 3855, "s": 3787, "text": "This method removes features with variation below a certain cutoff." }, { "code": null, "e": 3962, "s": 3855, "text": "The idea is when a feature doesn’t vary much within itself, it generally has very little predictive power." }, { "code": null, "e": 4006, "s": 3962, "text": "sklearn.feature_selection.VarianceThreshold" }, { "code": null, "e": 4097, "s": 4006, "text": "Variance Threshold doesn’t consider the relationship of features with the target variable." }, { "code": null, "e": 4191, "s": 4097, "text": "Wrapper Methods generate models with a subsets of feature and gauge their model performances." }, { "code": null, "e": 4326, "s": 4191, "text": "This method allows you to search for the best feature w.r.t model performance and add them to your feature subset one after the other." }, { "code": null, "e": 4352, "s": 4326, "text": "For data with n features," }, { "code": null, "e": 4461, "s": 4352, "text": "->On first round ‘n’ models are created with individual feature and the best predictive feature is selected." }, { "code": null, "e": 4560, "s": 4461, "text": "->On second round, ‘n-1’ models are created with each feature and the previously selected feature." }, { "code": null, "e": 4628, "s": 4560, "text": "->This is repeated till a best subset of ‘m’ features are selected." }, { "code": null, "e": 4786, "s": 4628, "text": "As the name suggests, this method eliminates worst performing features on a particular model one after the other until the best subset of features are known." }, { "code": null, "e": 4812, "s": 4786, "text": "For data with n features," }, { "code": null, "e": 4939, "s": 4812, "text": "->On first round ‘n-1’ models are created with combination of all features except one. The least performing feature is removed" }, { "code": null, "e": 5012, "s": 4939, "text": "-> On second round ‘n-2’ models are created by removing another feature." }, { "code": null, "e": 5096, "s": 5012, "text": "Wrapper Methods promises you a best set of features with a extensive greedy search." }, { "code": null, "e": 5280, "s": 5096, "text": "But the main drawbacks of wrapper methods is the sheer amount of models that needs to be trained. It is computationally very expensive and is infeasible with large number of features." }, { "code": null, "e": 5377, "s": 5280, "text": "Feature selection can also be acheived by the insights provided by some Machine Learning models." }, { "code": null, "e": 5639, "s": 5377, "text": "LASSO Linear Regression can be used for feature selections. Lasso Regression is performed by adding an extra term to the cost function of Linear Regression. This apart from preventing overfitting also reduces the coefficients of less important features to zero." }, { "code": null, "e": 5851, "s": 5639, "text": "Tree based models calculates feature importance for they need to keep the best performing features as close to the root of the tree. Constructing a decision tree involves calculating the best predictive feature." }, { "code": null, "e": 5960, "s": 5851, "text": "The feature importance in tree based models are calculated based on Gini Index, Entropy or Chi-Square value." }, { "code": null, "e": 6200, "s": 5960, "text": "Feature Selection as most things in Data Science is highly context and data dependent and there is no one stop solution for Feature Selection. The best way to go forward is to understand the mechanism of each methods and use when required." } ]
C program to store even, odd and prime numbers into separate files
A file is a physical storage location on disk and a directory is a logical path which is used to organise the files. A file exists within a directory. The three operations that we can perform on file are as follows − Open a file. Process file (read, write, modify). Save and close file. Following is the C program to store even, odd and prime numbers into separate files − Live Demo #include <stdio.h> #include <stdlib.h> /* Function declarations */ int even(const int num); int prime(const int num); int main(){ FILE * fptrinput, * fptreven, * fptrodd, * fptrprime; int num, success; fptrinput = fopen("numbers.txt", "r"); fptreven = fopen("even-numbers.txt" , "w"); fptrodd = fopen("odd-numbers.txt" , "w"); fptrprime= fopen("prime-numbers.txt", "w"); if(fptrinput == NULL || fptreven == NULL || fptrodd == NULL || fptrprime == NULL){ /* Unable to open file hence exit */ printf("Unable to open file.\n"); exit(EXIT_FAILURE); } /* File open success message */ printf("File opened successfully. Reading integers from file. \n\n"); // Read an integer and store read status in success. while (fscanf(fptrinput, "%d", &num) != -1){ if (prime(num)) fprintf(fptrprime, "%d\n", num); else if (even(num)) fprintf(fptreven, "%d\n", num); else fprintf(fptrodd, "%d\n", num); } fclose(fptrinput); fclose(fptreven); fclose(fptrodd); fclose(fptrprime); printf("Data written successfully."); return 0; } int even(const int num){ return !(num & 1); } int prime(const int num){ int i; if (num < 0) return 0; for ( i=2; i<=num/2; i++ ) { if (num % i == 0) { return 0; } } return 1; } When the above program is executed, it produces the following result − File opened successfully. Reading integers from file. Data written successfully. Given below is an explanation for the program used to store even, odd and prime numbers into separate files − Input file: numbers.txt file contains: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 Which is open in read mode (already exists file) Separated even, odd and prime numbers in separate file after execution even-numbers.txt contains: 4 6 8 10 12 14 16 odd-numbers.txt contains: 9 15 prime-numbers.txt contains: 1 2 3 5 7 11 13 17
[ { "code": null, "e": 1213, "s": 1062, "text": "A file is a physical storage location on disk and a directory is a logical path which is used to organise the files. A file exists within a directory." }, { "code": null, "e": 1279, "s": 1213, "text": "The three operations that we can perform on file are as follows −" }, { "code": null, "e": 1292, "s": 1279, "text": "Open a file." }, { "code": null, "e": 1328, "s": 1292, "text": "Process file (read, write, modify)." }, { "code": null, "e": 1349, "s": 1328, "text": "Save and close file." }, { "code": null, "e": 1435, "s": 1349, "text": "Following is the C program to store even, odd and prime numbers into separate files −" }, { "code": null, "e": 1446, "s": 1435, "text": " Live Demo" }, { "code": null, "e": 2807, "s": 1446, "text": "#include <stdio.h>\n#include <stdlib.h>\n/* Function declarations */\nint even(const int num);\nint prime(const int num);\nint main(){\n FILE * fptrinput,\n * fptreven,\n * fptrodd,\n * fptrprime;\n int num, success;\n fptrinput = fopen(\"numbers.txt\", \"r\");\n fptreven = fopen(\"even-numbers.txt\" , \"w\");\n fptrodd = fopen(\"odd-numbers.txt\" , \"w\");\n fptrprime= fopen(\"prime-numbers.txt\", \"w\");\n if(fptrinput == NULL || fptreven == NULL || fptrodd == NULL || fptrprime == NULL){\n /* Unable to open file hence exit */\n printf(\"Unable to open file.\\n\");\n exit(EXIT_FAILURE);\n }\n /* File open success message */\n printf(\"File opened successfully. Reading integers from file. \\n\\n\");\n // Read an integer and store read status in success.\n while (fscanf(fptrinput, \"%d\", &num) != -1){\n if (prime(num))\n fprintf(fptrprime, \"%d\\n\", num);\n else if (even(num))\n fprintf(fptreven, \"%d\\n\", num);\n else\n fprintf(fptrodd, \"%d\\n\", num);\n\n }\n fclose(fptrinput);\n fclose(fptreven);\n fclose(fptrodd);\n fclose(fptrprime);\n printf(\"Data written successfully.\");\n return 0;\n}\nint even(const int num){\n return !(num & 1);\n}\nint prime(const int num){\n int i;\n if (num < 0)\n return 0;\n for ( i=2; i<=num/2; i++ ) {\n if (num % i == 0) {\n return 0;\n }\n }\n return 1;\n}" }, { "code": null, "e": 2878, "s": 2807, "text": "When the above program is executed, it produces the following result −" }, { "code": null, "e": 2959, "s": 2878, "text": "File opened successfully. Reading integers from file.\nData written successfully." }, { "code": null, "e": 3069, "s": 2959, "text": "Given below is an explanation for the program used to store even, odd and prime numbers into separate files −" }, { "code": null, "e": 3393, "s": 3069, "text": "Input file:\nnumbers.txt file contains: 1 2 3 4 5 6 7 8 9 10\n11 12 13 14 15 16 17\nWhich is open in read mode (already exists file)\nSeparated even, odd and prime numbers in separate file after execution\neven-numbers.txt contains: 4 6 8 10 12 14 16\nodd-numbers.txt contains: 9 15\nprime-numbers.txt contains: 1 2 3 5 7 11 13 17" } ]
How to use the directory class in C#?
The Directory class in C# is used to manipulate the directory structure. It has methods to create, move, remove directories. The following are some of the methods of the Directory class. Let us learn about the usage of GetFiles() method in Directory class. It displays all the files in the specified directory. using System; using System.IO; class Program { static void Main() { // Get all files in the D directory string[] arr = Directory.GetFiles(@"D:\"); Console.WriteLine("Files:"); foreach (string n in arr) { Console.WriteLine(n); } } }
[ { "code": null, "e": 1187, "s": 1062, "text": "The Directory class in C# is used to manipulate the directory structure. It has methods to create, move, remove directories." }, { "code": null, "e": 1249, "s": 1187, "text": "The following are some of the methods of the Directory class." }, { "code": null, "e": 1373, "s": 1249, "text": "Let us learn about the usage of GetFiles() method in Directory class. It displays all the files in the specified directory." }, { "code": null, "e": 1650, "s": 1373, "text": "using System;\nusing System.IO;\nclass Program {\n static void Main() {\n // Get all files in the D directory\n string[] arr = Directory.GetFiles(@\"D:\\\");\n Console.WriteLine(\"Files:\");\n foreach (string n in arr) {\n Console.WriteLine(n);\n }\n }\n}" } ]
Adding Text on Image using Python - PIL - GeeksforGeeks
15 Sep, 2021 In Python to open an image, image editing, saving that image in different formats one additional library called Python Imaging Library (PIL). Using this PIL we can do so many operations on images like create a new Image, edit an existing image, rotate an image, etc. For adding text we have to follow the given approach. Approach Import module Open targeted image Add text property using image object Show that edited Image Save that image Syntax: obj.text( (x,y), Text, font, fill) Parameters: (x, y): This X and Y denotes the starting position(in pixels)/coordinate of adding the text on an image. Text: A Text or message that we want to add to the Image. Font: specific font type and font size that you want to give to the text. Fill: Fill is for to give the Font color to your text. Other than these we required some module from PIL to perform this task. We need ImageDraw that can add 2D graphics ( shapes, text) to an image. Also, we required the ImageFont module to add custom font style and font size. Given below is the Implementation of add text to an image. Image Used: Example 1: Add a simple text to an image. ( without custom Font style) Python3 # Importing the PIL libraryfrom PIL import Imagefrom PIL import ImageDraw # Open an Imageimg = Image.open('car.png') # Call draw Method to add 2D graphics in an imageI1 = ImageDraw.Draw(img) # Add Text to an imageI1.text((28, 36), "nice Car", fill=(255, 0, 0)) # Display edited imageimg.show() # Save the edited imageimg.save("car2.png") Output: Here You can see that we successfully add text to an image but it not properly visible so we can add the Font parameter to give a custom style. Example 2: Add a simple text to an image. ( With custom Font style) Python3 # Importing the PIL libraryfrom PIL import Imagefrom PIL import ImageDrawfrom PIL import ImageFont # Open an Imageimg = Image.open('car.png') # Call draw Method to add 2D graphics in an imageI1 = ImageDraw.Draw(img) # Custom font style and font sizemyFont = ImageFont.truetype('FreeMono.ttf', 65) # Add Text to an imageI1.text((10, 10), "Nice Car", font=myFont, fill =(255, 0, 0)) # Display edited imageimg.show() # Save the edited imageimg.save("car2.png") Output: kapoorsagar226 akshaysingh98088 Picked Python-pil Technical Scripter 2020 Python Technical Scripter Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? How To Convert Python Dictionary To JSON? How to drop one or multiple columns in Pandas Dataframe Check if element exists in list in Python Selecting rows in pandas DataFrame based on conditions Python | os.path.join() method Defaultdict in Python Create a directory in Python Python | Get unique values from a list Python | Pandas dataframe.groupby()
[ { "code": null, "e": 24292, "s": 24264, "text": "\n15 Sep, 2021" }, { "code": null, "e": 24613, "s": 24292, "text": "In Python to open an image, image editing, saving that image in different formats one additional library called Python Imaging Library (PIL). Using this PIL we can do so many operations on images like create a new Image, edit an existing image, rotate an image, etc. For adding text we have to follow the given approach." }, { "code": null, "e": 24622, "s": 24613, "text": "Approach" }, { "code": null, "e": 24636, "s": 24622, "text": "Import module" }, { "code": null, "e": 24656, "s": 24636, "text": "Open targeted image" }, { "code": null, "e": 24693, "s": 24656, "text": "Add text property using image object" }, { "code": null, "e": 24716, "s": 24693, "text": "Show that edited Image" }, { "code": null, "e": 24732, "s": 24716, "text": "Save that image" }, { "code": null, "e": 24775, "s": 24732, "text": "Syntax: obj.text( (x,y), Text, font, fill)" }, { "code": null, "e": 24788, "s": 24775, "text": "Parameters: " }, { "code": null, "e": 24893, "s": 24788, "text": "(x, y): This X and Y denotes the starting position(in pixels)/coordinate of adding the text on an image." }, { "code": null, "e": 24951, "s": 24893, "text": "Text: A Text or message that we want to add to the Image." }, { "code": null, "e": 25025, "s": 24951, "text": "Font: specific font type and font size that you want to give to the text." }, { "code": null, "e": 25080, "s": 25025, "text": "Fill: Fill is for to give the Font color to your text." }, { "code": null, "e": 25363, "s": 25080, "text": "Other than these we required some module from PIL to perform this task. We need ImageDraw that can add 2D graphics ( shapes, text) to an image. Also, we required the ImageFont module to add custom font style and font size. Given below is the Implementation of add text to an image. " }, { "code": null, "e": 25375, "s": 25363, "text": "Image Used:" }, { "code": null, "e": 25446, "s": 25375, "text": "Example 1: Add a simple text to an image. ( without custom Font style)" }, { "code": null, "e": 25454, "s": 25446, "text": "Python3" }, { "code": "# Importing the PIL libraryfrom PIL import Imagefrom PIL import ImageDraw # Open an Imageimg = Image.open('car.png') # Call draw Method to add 2D graphics in an imageI1 = ImageDraw.Draw(img) # Add Text to an imageI1.text((28, 36), \"nice Car\", fill=(255, 0, 0)) # Display edited imageimg.show() # Save the edited imageimg.save(\"car2.png\")", "e": 25792, "s": 25454, "text": null }, { "code": null, "e": 25800, "s": 25792, "text": "Output:" }, { "code": null, "e": 25944, "s": 25800, "text": "Here You can see that we successfully add text to an image but it not properly visible so we can add the Font parameter to give a custom style." }, { "code": null, "e": 26012, "s": 25944, "text": "Example 2: Add a simple text to an image. ( With custom Font style)" }, { "code": null, "e": 26020, "s": 26012, "text": "Python3" }, { "code": "# Importing the PIL libraryfrom PIL import Imagefrom PIL import ImageDrawfrom PIL import ImageFont # Open an Imageimg = Image.open('car.png') # Call draw Method to add 2D graphics in an imageI1 = ImageDraw.Draw(img) # Custom font style and font sizemyFont = ImageFont.truetype('FreeMono.ttf', 65) # Add Text to an imageI1.text((10, 10), \"Nice Car\", font=myFont, fill =(255, 0, 0)) # Display edited imageimg.show() # Save the edited imageimg.save(\"car2.png\")", "e": 26478, "s": 26020, "text": null }, { "code": null, "e": 26486, "s": 26478, "text": "Output:" }, { "code": null, "e": 26501, "s": 26486, "text": "kapoorsagar226" }, { "code": null, "e": 26518, "s": 26501, "text": "akshaysingh98088" }, { "code": null, "e": 26525, "s": 26518, "text": "Picked" }, { "code": null, "e": 26536, "s": 26525, "text": "Python-pil" }, { "code": null, "e": 26560, "s": 26536, "text": "Technical Scripter 2020" }, { "code": null, "e": 26567, "s": 26560, "text": "Python" }, { "code": null, "e": 26586, "s": 26567, "text": "Technical Scripter" }, { "code": null, "e": 26684, "s": 26586, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26716, "s": 26684, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 26758, "s": 26716, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 26814, "s": 26758, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 26856, "s": 26814, "text": "Check if element exists in list in Python" }, { "code": null, "e": 26911, "s": 26856, "text": "Selecting rows in pandas DataFrame based on conditions" }, { "code": null, "e": 26942, "s": 26911, "text": "Python | os.path.join() method" }, { "code": null, "e": 26964, "s": 26942, "text": "Defaultdict in Python" }, { "code": null, "e": 26993, "s": 26964, "text": "Create a directory in Python" }, { "code": null, "e": 27032, "s": 26993, "text": "Python | Get unique values from a list" } ]
Find the last element of a list in scala - GeeksforGeeks
17 Apr, 2019 In Scala, list is defined under scala.collection.immutable package. A list is a collection of same type elements which contains immutable data. we generally use last function to print last element of a list. Below are the examples to find the last element of a given list in Scala. Simply print last element of a list// Scala program to find the last element of a given list import scala.collection.immutable._ // Creating object object GFG{ // Main method def main(args:Array[String]) { // Creating and initializing immutable lists val mylist: List[String] = List("Geeks", "For", "geeks", "is", "best") // Display the last value of mylist println("Last element is: " + mylist.last) } } Output:Last element is: best // Scala program to find the last element of a given list import scala.collection.immutable._ // Creating object object GFG{ // Main method def main(args:Array[String]) { // Creating and initializing immutable lists val mylist: List[String] = List("Geeks", "For", "geeks", "is", "best") // Display the last value of mylist println("Last element is: " + mylist.last) } } Output: Last element is: best Print last element of a list using for loop// Scala program to find the last element of a given list// using for loop import scala.collection.immutable._ // Creating object object GFG{ // Main method def main(args:Array[String]) { // Creating and initializing immutable lists val mylist: List[String] = List("Geeks", "For", "geeks", "is", "a", "fabulous", "portal") // Display the last value of mylist using for loop for(element<-mylist.last) { print(element) } } } Output:portal // Scala program to find the last element of a given list// using for loop import scala.collection.immutable._ // Creating object object GFG{ // Main method def main(args:Array[String]) { // Creating and initializing immutable lists val mylist: List[String] = List("Geeks", "For", "geeks", "is", "a", "fabulous", "portal") // Display the last value of mylist using for loop for(element<-mylist.last) { print(element) } } } Output: portal Print last element of a list using foreach loop// Scala program to find the last element of a given list// using foreach loop import scala.collection.immutable._ // Creating object object GFG{ // Main method def main(args:Array[String]) { // Creating and initializing immutable lists val mylist = List(1, 2, 3, 4, 5, 6) print("Original list is: ") // Display the value of mylist using for loop mylist.foreach{x:Int => print(x + " ") } // calling last function println("\nLast element is: " + mylist.last) } } Output:Original list is: 1 2 3 4 5 6 Last element is: 6 // Scala program to find the last element of a given list// using foreach loop import scala.collection.immutable._ // Creating object object GFG{ // Main method def main(args:Array[String]) { // Creating and initializing immutable lists val mylist = List(1, 2, 3, 4, 5, 6) print("Original list is: ") // Display the value of mylist using for loop mylist.foreach{x:Int => print(x + " ") } // calling last function println("\nLast element is: " + mylist.last) } } Output: Original list is: 1 2 3 4 5 6 Last element is: 6 Scala Scala Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Type Casting in Scala Scala Tutorial – Learn Scala with Step By Step Guide Hello World in Scala Operators in Scala Class and Object in Scala Scala String substring() method with example Inheritance in Scala Throw Keyword in Scala Scala Constructors Break statement in Scala
[ { "code": null, "e": 23926, "s": 23898, "text": "\n17 Apr, 2019" }, { "code": null, "e": 24134, "s": 23926, "text": "In Scala, list is defined under scala.collection.immutable package. A list is a collection of same type elements which contains immutable data. we generally use last function to print last element of a list." }, { "code": null, "e": 24208, "s": 24134, "text": "Below are the examples to find the last element of a given list in Scala." }, { "code": null, "e": 24735, "s": 24208, "text": "Simply print last element of a list// Scala program to find the last element of a given list import scala.collection.immutable._ // Creating object object GFG{ // Main method def main(args:Array[String]) { // Creating and initializing immutable lists val mylist: List[String] = List(\"Geeks\", \"For\", \"geeks\", \"is\", \"best\") // Display the last value of mylist println(\"Last element is: \" + mylist.last) } } Output:Last element is: best " }, { "code": "// Scala program to find the last element of a given list import scala.collection.immutable._ // Creating object object GFG{ // Main method def main(args:Array[String]) { // Creating and initializing immutable lists val mylist: List[String] = List(\"Geeks\", \"For\", \"geeks\", \"is\", \"best\") // Display the last value of mylist println(\"Last element is: \" + mylist.last) } } ", "e": 25198, "s": 24735, "text": null }, { "code": null, "e": 25206, "s": 25198, "text": "Output:" }, { "code": null, "e": 25228, "s": 25206, "text": "Last element is: best" }, { "code": null, "e": 25860, "s": 25230, "text": "Print last element of a list using for loop// Scala program to find the last element of a given list// using for loop import scala.collection.immutable._ // Creating object object GFG{ // Main method def main(args:Array[String]) { // Creating and initializing immutable lists val mylist: List[String] = List(\"Geeks\", \"For\", \"geeks\", \"is\", \"a\", \"fabulous\", \"portal\") // Display the last value of mylist using for loop for(element<-mylist.last) { print(element) } } } Output:portal " }, { "code": "// Scala program to find the last element of a given list// using for loop import scala.collection.immutable._ // Creating object object GFG{ // Main method def main(args:Array[String]) { // Creating and initializing immutable lists val mylist: List[String] = List(\"Geeks\", \"For\", \"geeks\", \"is\", \"a\", \"fabulous\", \"portal\") // Display the last value of mylist using for loop for(element<-mylist.last) { print(element) } } } ", "e": 26433, "s": 25860, "text": null }, { "code": null, "e": 26441, "s": 26433, "text": "Output:" }, { "code": null, "e": 26448, "s": 26441, "text": "portal" }, { "code": null, "e": 27120, "s": 26450, "text": "Print last element of a list using foreach loop// Scala program to find the last element of a given list// using foreach loop import scala.collection.immutable._ // Creating object object GFG{ // Main method def main(args:Array[String]) { // Creating and initializing immutable lists val mylist = List(1, 2, 3, 4, 5, 6) print(\"Original list is: \") // Display the value of mylist using for loop mylist.foreach{x:Int => print(x + \" \") } // calling last function println(\"\\nLast element is: \" + mylist.last) } } Output:Original list is: 1 2 3 4 5 6 \nLast element is: 6" }, { "code": "// Scala program to find the last element of a given list// using foreach loop import scala.collection.immutable._ // Creating object object GFG{ // Main method def main(args:Array[String]) { // Creating and initializing immutable lists val mylist = List(1, 2, 3, 4, 5, 6) print(\"Original list is: \") // Display the value of mylist using for loop mylist.foreach{x:Int => print(x + \" \") } // calling last function println(\"\\nLast element is: \" + mylist.last) } } ", "e": 27687, "s": 27120, "text": null }, { "code": null, "e": 27695, "s": 27687, "text": "Output:" }, { "code": null, "e": 27745, "s": 27695, "text": "Original list is: 1 2 3 4 5 6 \nLast element is: 6" }, { "code": null, "e": 27751, "s": 27745, "text": "Scala" }, { "code": null, "e": 27757, "s": 27751, "text": "Scala" }, { "code": null, "e": 27855, "s": 27757, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27864, "s": 27855, "text": "Comments" }, { "code": null, "e": 27877, "s": 27864, "text": "Old Comments" }, { "code": null, "e": 27899, "s": 27877, "text": "Type Casting in Scala" }, { "code": null, "e": 27952, "s": 27899, "text": "Scala Tutorial – Learn Scala with Step By Step Guide" }, { "code": null, "e": 27973, "s": 27952, "text": "Hello World in Scala" }, { "code": null, "e": 27992, "s": 27973, "text": "Operators in Scala" }, { "code": null, "e": 28018, "s": 27992, "text": "Class and Object in Scala" }, { "code": null, "e": 28063, "s": 28018, "text": "Scala String substring() method with example" }, { "code": null, "e": 28084, "s": 28063, "text": "Inheritance in Scala" }, { "code": null, "e": 28107, "s": 28084, "text": "Throw Keyword in Scala" }, { "code": null, "e": 28126, "s": 28107, "text": "Scala Constructors" } ]
Getting Started with Elasticsearch Query DSL | by Niels D. Goet | Towards Data Science
In this post, I’ll introduce the basics of querying in Elasticsearch (ES). We’ll look at how queries are structured (e.g. the filter vs. query context, and relevance scoring) in Elasticsearch Domain Specific Language (DSL) and apply them with the Python Elasticsearch Client. (And, if DSL makes your head spin, skip to the final section of this post, where we’ll go through the basics of running SQL queries against ES). All code used in this blog post is available in this GitHub repo. For this post, I’m assuming you are familiar with the basics of ES. I’m also assuming you have already provisioned and deployed your own Elasticsearch cluster (either “from scratch” or using a managed service), and that you’ve written data to an index. For a quick primer on the basics of ES and instructions on how to provision a cluster, and set up an index with Python, check my earlier post on Creating and Managing Elasticsearch Indices with Python. towardsdatascience.com For the examples shown below, I’ll be using the neflix_movies index I set up in my earlier post. This index is constructed from data on 7787 Netflix shows available on Kaggle. The original data is in CSV, and contains information on movies and series available on Netflix, including metadata such as their release date, their title, and cast. The mapping for our index is defined as follows: This mapping can be further improved and is not optimised for disk usage or tuned for search speed. However, it’ll suffice for the queries that we’ll be running below. If you’d like to learn how to create better ES indices that are optimised for disk usage, check out my earlier post on Optimising Disk Usage in Elasticsearch. towardsdatascience.com Before we dive into the hands-on sections of this blog post, let’s review some of the basics of querying data from Elasticsearch. The ES search API accepts queries that use Elasticsearch Domain Specific Language (DSL), which is based on JSON. The ES documentation describes DSL as an Abstract Syntax Tree (AST) of queries that consists of two types of clauses: leaf query clauses that look for a specific value in a specific field (e.g. a match or range); andcompound query clauses that are used to logically combine multiple queries (such as multiple leaf or compound queries) or to alter the behaviour of these queries. leaf query clauses that look for a specific value in a specific field (e.g. a match or range); and compound query clauses that are used to logically combine multiple queries (such as multiple leaf or compound queries) or to alter the behaviour of these queries. When you run a query against your index (or indices), ES sorts the results by a relevance score (a float) that represents the quality of the match (the _score field shows its value for each “hit”). An ES query has a query and a filter context. The filter context — as the name suggests — simply filters out documents that do not match the conditions in the syntax. However, unlike the match in the bool context, it will not affect the relevance score. Let’s look at a simple example of a query with a query and a filter context. The example below filters on release year (using a range query), and runs a match query against the movie type in the query context. { "query": { "bool": { "must": [ {"match": {"type": "TV Movie"}}, ], "filter": [ {"range": {"release_year": {"gte": 2021}}} ] } }} We can run this query on our index directly using our ES Console (assuming you’re using a cloud-based platform such as Elastic.co, Bonsai, or Amazon Elasticsearch Service), or through the Python Elasticsearch Client. The queries themselves look the same regardless of whether you use the client or the console. In the remainder of this post, my examples will use the Python ES Client with DSL. To get started, we first set up the ES client connection (for further details, please see my earlier blog post and this GitHub repo): In a second step, we define and run our query against the netflix_movies index: The print statement at the end of the code prints the title and the associated relevance score as tuples. The output looks like this: [ ('Bling Empire', 0.96465576), ('Carmen Sandiego', 0.96465576), ('Cobra Kai', 0.96465576), ('Disenchantment', 0.96465576), ('Dream Home Makeover', 0.96465576), ("Gabby's Dollhouse", 0.96465576), ('Headspace Guide to Meditation', 0.96465576), ('Hilda', 0.96465576), ('History of Swear Words', 0.96465576), ('Inside the World’s Toughest Prisons', 0.96465576)] In this case the relevance scores are the same for all entries: this makes sense, since all of these entries have the exact same value for type (that is, “TV Movie”). Since we know that “TV Movie” is the value that the field can take, we may as well have used the filter context, since we’re looking for that exact value. So when should you use the filter or query context? In general, filters are cheaper and should be used whenever you can (ES caches frequently used filters automatically to boost performance). They are used to search on binary cases (that have a clear “yes” or “no” answer) and on exact values (for example when searching on a numeric value, a specific range, or a keyword). The query context, in turn, should be used when the result can be ambiguous or for full text search (i.e. when searching analysed text fields). Let’s revisit the query shown above with this information on when to use the filter and query contexts in mind: The query applies to a range of a short field type (release_year) and a keyword field type (type). For the latter, we know the exact value we want (“TV Show”). A better way of writing the query therefore is as follows, re-using the range filter, and applying a term query (more on this type of query below) for the latter, and placing both in the “filter” context: Now that we’ve covered the basics of search and DSL, let’s first look at several basic queries. First up is the “ match” query, which is the default option for full-text search. Let’s assume we’re looking for metadata on the “House of Cards” series. Because ES analyses the text when using a match query, it will return any show that has “House” or “Cards” in the title if we go with the default (DSL defaults to the “or” operator). Therefore, we’ll use the “and” operator: The query produces a single hit (one document): { "total": { "value": 1, "relation": "eq" }, "max_score": 15.991642, "hits": [ { "_index": "netflix_movies", "_type": "_doc", "_id": "rWHgLHgBIp2yHscf16v-", "_score": 15.991642, "_source": { "show_id": "s2833", "type": "TV Show", "title": "House of Cards", "director": null, "cast": "Kevin Spacey, Robin Wright, Kate Mara, Corey Stoll, Sakina Jaffrey, Kristen Connolly, Constance Zimmer, Sebastian Arcelus, Nathan Darrow, Sandrine Holt, Michel Gill, Elizabeth Norment, Mahershala Ali, Reg E. Cathey, Molly Parker, Derek Cecil, Elizabeth Marvel, Kim Dickens, Lars Mikkelsen, Michael Kelly, Joel Kinnaman, Campbell Scott, Patricia Clarkson, Neve Campbell", "country": "United States", "date_added": "November 2, 2018", "release_year": 2018, "rating": "TV-MA", "duration": "6 Seasons", "listed_in": "TV Dramas, TV Thrillers", "description": "A ruthless politician will stop at nothing to conquer Washington, D.C., in this Emmy and Golden Globe-winning political drama." } } ]} The relevance score for this hit is 15.991642. This may seem odd at first glance. However, keep in mind that the relevance score is not bounded and that it is used to evaluate the relevance of a document versus all others that match the query. In other words: the score represents how relevant a document is for a query compared to other “hits” (documents) for that same query, in the same search. The term query is used to “find” documents for which a field matches an exact value. We have a number of keyword fields in our index that we can apply a term query to. The example below extracts five documents where the type field is equal to TV Show (note that the size parameter controls how many records ES returns, and it defaults to 10): A term query should not be used for text fields. ES changes text fields as part of analysis, tokenising the text, stripping it of punctuation, and converting it to lowercase. If type had been a text field instead of a keyword field, the query shown above would not have returned a result because any instances of “TV Show” would have been turned into ["tv", "show"] as part of analysis. Last but not least in our “common queries” series: the “range query”. As the name implies, the range query is used to find any documents for which a specific field’s value falls within a defined range. It can be used for, e.g. date and numeric field types. It can also be used on text and keyword fields, provided your cluster settings allow for expensive queries (the default). The query shown below runs a simple range query on release year, searching for 100 movies or TV shows released in 2012 or earlier: There are several more complex queries that I tend to use. In this section, we’ll take a brief look at regex, metric aggregations, and custom filters. The regexp query is designed for finding documents where a term in a specific field matches a regular expression. The example below looks for any documents in our netflix_movies index where the title field includes a word that in part consists of “war” (e.g. war, warror, Warfare, warmest, etc.): Regexp queries can be made case-sensitive (using the case_insensitive option, with default set to false). However, title is a text field for which analysis has not been disabled. Therefore, we can expect the terms in the title field to have been lowercased (among other things — please refer to the previous sections for more details on “analysis”). Enabling or disabling case sensitivity would therefore make no difference given our current mapping. ES aggregations are a great way to explore your data, and they come in three flavours: metric, bucket, and pipeline. Here we’ll look at one from the metric and one from the bucket category. We’ll first take a look at the stats query (a metric aggregation), which comes in handy when you’re looking to review summary statistics (min, max, mean, sum) for numeric values. For example, if we’d quickly want to see how release_year is distributed in our data, we can run the following query: For aggregations we set the size parameter to 0 in our queries. This means that the search API will not return any documents (if you omit this, the hits field will contain the documents). The response for this query gives us simple summary stats for the release_year values across our documents (e.g. min, max, mean): '{ "release_year_stats": { "count": 7787, "min": 1925.0, "max": 2021.0, "avg": 2013.932579940927, "sum": 15682493.0 }}' Let’s now turn to our second aggregation query, this time from the bucket aggregation family. The terms aggregation is useful for getting a quick overview of the availability of observations across different categories. In our netflix_movies index, you may for example want review how many movies were released in any given year, or how many movies of each type are present in the dataset. In DSL, our query for the former (count of movies per release year) looks as follows: There’s two things worth highlighting in this query. First, we specify a second size parameter in the terms object, which controls how many “term buckets” are returned (in this case: 5). Second, we order the output by the keys (i.e. the release years), in ascending order. The output from this query should look like this: { "release_years": { "doc_count_error_upper_bound": 0, "sum_other_doc_count": 7775, "buckets": [ { "key": 1925, "doc_count": 1 }, { "key": 1942, "doc_count": 2 }, { "key": 1943, "doc_count": 3 }, { "key": 1944, "doc_count": 3 }, { "key": 1945, "doc_count": 3 } ] }} Let’s quickly review this output. The buckets fields include the document count for each of our five term buckets (one object for each key). In turn, thesum_other_doc_count is the sum of all counts for the buckets that were excluded from the output. Finally, the doc_count_error_upper_bound value reflects the error associated with the bucket aggregation. At this point you might wonder: “error, what error?”. ES reports an error in the response because term aggregations are approximate. This stems from the fact that documents are distributed across shards, and each shard has its own ordered list of terms, which are combined in the aggregation. The node that coordinates the search process requests a number of term buckets equal to size. Subsequently, the results from these shards are combined to produce the final response. We can therefore expect a greater chance of error if the specified size is less than the number of unique terms. In our example above, we have 73 distinct release_year values, so we may want to change the size parameter (and for large numbers of term buckets, the shard_size too, to address some of the additional overhead that stems from increasing size). Onto our final “complex” query: the “script query”. A script query can be used if you want to use a filter of your own design on documents in your index. The script query is provided in the filter context. In the example below, I’ve written a simple script that extracts documents for which release_year is greater than 2018 (we could achieve the same result with a range query, see above). The source field contains the script, and the params field includes the start_year value that is used by the script. The default language for script queries is “painless” (specified in the lang field), but other languages are available, including Lucene’s Expressions Language and Mustache Language. If you have custom scripts that you use often, you can use a store scripts on the cluster state using the _scripts endpoint, so you can retrieve them for later use. Storing scripts speeds up search since it often reduces the time needed for compilation. For the SQL fans out there: you can use SQL syntax to query your ES indices. This feature is part of X-Pack and you can use to directly execute SQL queries against your ES indices in the console on your cloud-based ES service, such as AWS or Elastic.co, or using the Python Elasticsearch Client. (Note that this does not work on Bonsai as the X-Pack plugin is not included because it requires a license for commercial purposes. I’ve therefore run the below API calls for the SQL translate API on Elastic.co instead, which offers a 14-day free trial). If you work on Elastic.co, you can use the SQL translate API to translate SQL syntax to native Elasticsearch queries. From the console, it’s as simple as using a POST request with your SQL syntax in a JSON document. For example, a query to get a list of titles of Netflix movies released in 2015 or later looks as follows: {"query": "SELECT title FROM netflix_movies WHERE release_year >= 2015"} If you send this document using a POST request on the translate endpoint (POST _sql/translate) on your API console, it will return the corresponding query in native a native ES query (DSL). For our example, the resulting ES query is: { "sort": [ { "_doc": { "order": "asc" } } ], "query": { "range": { "release_year": { "to": null, "include_upper": false, "boost": 1, "from": 2015, "include_lower": true } } }, "_source": false, "fields": [ { "field": "title" } ], "size": 1000} You can also get the output directly, skipping the “translate step” altogether. If you make a POST request with your JSON document with _sql?format=txt, the API returns the response data in a nicely formatted text format (for JSON format, use _sql?format=json): title ------------------------------------- Black Crows Black Earth Rising Black Lightning Black Man White Skin Black Mirror Black Mirror: Bandersnatch Black Panther Black Sea Black Site Delta Black Snow........... Similarly, you can run simple GROUP BY queries (provided the field you perform the aggregation on is not of the text type). For example, the following query will return the number of movies for each release year (here I’m limiting the output to the first five years): POST _sql?format=txt{"query": "SELECT release_year, COUNT(*) as n_entries FROM netflix_movies GROUP BY release_year LIMIT 5"} Again, the output is nicely formatted: release_year | n_entries ---------------+--------------- 1925 |1 1942 |2 1943 |3 1944 |3 1945 |3 And that’s it! We’ve now reviewed the basics of DSL and have run a couple of basic and more complex queries. Thank you for reading! Support my work: If you liked this article and you’d like to support my work, please consider becoming a paying Medium member via my referral page. The price of the subscription is the same if you sign up via my referral page, but I will receive part of your monthly membership fee. If you liked this article, here are some other articles you may enjoy: towardsdatascience.com towardsdatascience.com towardsdatascience.com Disclaimer: “Elasticsearch” is a trademark of Elasticsearch BV, registered in the U.S. and in other countries. Description and/or use of any third-party services and/or trademarks in this blog post should not be seen as endorsement for or by their respective rights holders. Please read this disclaimer carefully before relying on any of the content in my articles on Medium.com.
[ { "code": null, "e": 658, "s": 171, "text": "In this post, I’ll introduce the basics of querying in Elasticsearch (ES). We’ll look at how queries are structured (e.g. the filter vs. query context, and relevance scoring) in Elasticsearch Domain Specific Language (DSL) and apply them with the Python Elasticsearch Client. (And, if DSL makes your head spin, skip to the final section of this post, where we’ll go through the basics of running SQL queries against ES). All code used in this blog post is available in this GitHub repo." }, { "code": null, "e": 911, "s": 658, "text": "For this post, I’m assuming you are familiar with the basics of ES. I’m also assuming you have already provisioned and deployed your own Elasticsearch cluster (either “from scratch” or using a managed service), and that you’ve written data to an index." }, { "code": null, "e": 1113, "s": 911, "text": "For a quick primer on the basics of ES and instructions on how to provision a cluster, and set up an index with Python, check my earlier post on Creating and Managing Elasticsearch Indices with Python." }, { "code": null, "e": 1136, "s": 1113, "text": "towardsdatascience.com" }, { "code": null, "e": 1528, "s": 1136, "text": "For the examples shown below, I’ll be using the neflix_movies index I set up in my earlier post. This index is constructed from data on 7787 Netflix shows available on Kaggle. The original data is in CSV, and contains information on movies and series available on Netflix, including metadata such as their release date, their title, and cast. The mapping for our index is defined as follows:" }, { "code": null, "e": 1696, "s": 1528, "text": "This mapping can be further improved and is not optimised for disk usage or tuned for search speed. However, it’ll suffice for the queries that we’ll be running below." }, { "code": null, "e": 1855, "s": 1696, "text": "If you’d like to learn how to create better ES indices that are optimised for disk usage, check out my earlier post on Optimising Disk Usage in Elasticsearch." }, { "code": null, "e": 1878, "s": 1855, "text": "towardsdatascience.com" }, { "code": null, "e": 2239, "s": 1878, "text": "Before we dive into the hands-on sections of this blog post, let’s review some of the basics of querying data from Elasticsearch. The ES search API accepts queries that use Elasticsearch Domain Specific Language (DSL), which is based on JSON. The ES documentation describes DSL as an Abstract Syntax Tree (AST) of queries that consists of two types of clauses:" }, { "code": null, "e": 2500, "s": 2239, "text": "leaf query clauses that look for a specific value in a specific field (e.g. a match or range); andcompound query clauses that are used to logically combine multiple queries (such as multiple leaf or compound queries) or to alter the behaviour of these queries." }, { "code": null, "e": 2599, "s": 2500, "text": "leaf query clauses that look for a specific value in a specific field (e.g. a match or range); and" }, { "code": null, "e": 2762, "s": 2599, "text": "compound query clauses that are used to logically combine multiple queries (such as multiple leaf or compound queries) or to alter the behaviour of these queries." }, { "code": null, "e": 3214, "s": 2762, "text": "When you run a query against your index (or indices), ES sorts the results by a relevance score (a float) that represents the quality of the match (the _score field shows its value for each “hit”). An ES query has a query and a filter context. The filter context — as the name suggests — simply filters out documents that do not match the conditions in the syntax. However, unlike the match in the bool context, it will not affect the relevance score." }, { "code": null, "e": 3424, "s": 3214, "text": "Let’s look at a simple example of a query with a query and a filter context. The example below filters on release year (using a range query), and runs a match query against the movie type in the query context." }, { "code": null, "e": 3649, "s": 3424, "text": "{ \"query\": { \"bool\": { \"must\": [ {\"match\": {\"type\": \"TV Movie\"}}, ], \"filter\": [ {\"range\": {\"release_year\": {\"gte\": 2021}}} ] } }}" }, { "code": null, "e": 4043, "s": 3649, "text": "We can run this query on our index directly using our ES Console (assuming you’re using a cloud-based platform such as Elastic.co, Bonsai, or Amazon Elasticsearch Service), or through the Python Elasticsearch Client. The queries themselves look the same regardless of whether you use the client or the console. In the remainder of this post, my examples will use the Python ES Client with DSL." }, { "code": null, "e": 4177, "s": 4043, "text": "To get started, we first set up the ES client connection (for further details, please see my earlier blog post and this GitHub repo):" }, { "code": null, "e": 4257, "s": 4177, "text": "In a second step, we define and run our query against the netflix_movies index:" }, { "code": null, "e": 4391, "s": 4257, "text": "The print statement at the end of the code prints the title and the associated relevance score as tuples. The output looks like this:" }, { "code": null, "e": 4750, "s": 4391, "text": "[ ('Bling Empire', 0.96465576), ('Carmen Sandiego', 0.96465576), ('Cobra Kai', 0.96465576), ('Disenchantment', 0.96465576), ('Dream Home Makeover', 0.96465576), (\"Gabby's Dollhouse\", 0.96465576), ('Headspace Guide to Meditation', 0.96465576), ('Hilda', 0.96465576), ('History of Swear Words', 0.96465576), ('Inside the World’s Toughest Prisons', 0.96465576)]" }, { "code": null, "e": 5072, "s": 4750, "text": "In this case the relevance scores are the same for all entries: this makes sense, since all of these entries have the exact same value for type (that is, “TV Movie”). Since we know that “TV Movie” is the value that the field can take, we may as well have used the filter context, since we’re looking for that exact value." }, { "code": null, "e": 5590, "s": 5072, "text": "So when should you use the filter or query context? In general, filters are cheaper and should be used whenever you can (ES caches frequently used filters automatically to boost performance). They are used to search on binary cases (that have a clear “yes” or “no” answer) and on exact values (for example when searching on a numeric value, a specific range, or a keyword). The query context, in turn, should be used when the result can be ambiguous or for full text search (i.e. when searching analysed text fields)." }, { "code": null, "e": 6067, "s": 5590, "text": "Let’s revisit the query shown above with this information on when to use the filter and query contexts in mind: The query applies to a range of a short field type (release_year) and a keyword field type (type). For the latter, we know the exact value we want (“TV Show”). A better way of writing the query therefore is as follows, re-using the range filter, and applying a term query (more on this type of query below) for the latter, and placing both in the “filter” context:" }, { "code": null, "e": 6163, "s": 6067, "text": "Now that we’ve covered the basics of search and DSL, let’s first look at several basic queries." }, { "code": null, "e": 6541, "s": 6163, "text": "First up is the “ match” query, which is the default option for full-text search. Let’s assume we’re looking for metadata on the “House of Cards” series. Because ES analyses the text when using a match query, it will return any show that has “House” or “Cards” in the title if we go with the default (DSL defaults to the “or” operator). Therefore, we’ll use the “and” operator:" }, { "code": null, "e": 6589, "s": 6541, "text": "The query produces a single hit (one document):" }, { "code": null, "e": 7694, "s": 6589, "text": "{ \"total\": { \"value\": 1, \"relation\": \"eq\" }, \"max_score\": 15.991642, \"hits\": [ { \"_index\": \"netflix_movies\", \"_type\": \"_doc\", \"_id\": \"rWHgLHgBIp2yHscf16v-\", \"_score\": 15.991642, \"_source\": { \"show_id\": \"s2833\", \"type\": \"TV Show\", \"title\": \"House of Cards\", \"director\": null, \"cast\": \"Kevin Spacey, Robin Wright, Kate Mara, Corey Stoll, Sakina Jaffrey, Kristen Connolly, Constance Zimmer, Sebastian Arcelus, Nathan Darrow, Sandrine Holt, Michel Gill, Elizabeth Norment, Mahershala Ali, Reg E. Cathey, Molly Parker, Derek Cecil, Elizabeth Marvel, Kim Dickens, Lars Mikkelsen, Michael Kelly, Joel Kinnaman, Campbell Scott, Patricia Clarkson, Neve Campbell\", \"country\": \"United States\", \"date_added\": \"November 2, 2018\", \"release_year\": 2018, \"rating\": \"TV-MA\", \"duration\": \"6 Seasons\", \"listed_in\": \"TV Dramas, TV Thrillers\", \"description\": \"A ruthless politician will stop at nothing to conquer Washington, D.C., in this Emmy and Golden Globe-winning political drama.\" } } ]}" }, { "code": null, "e": 8092, "s": 7694, "text": "The relevance score for this hit is 15.991642. This may seem odd at first glance. However, keep in mind that the relevance score is not bounded and that it is used to evaluate the relevance of a document versus all others that match the query. In other words: the score represents how relevant a document is for a query compared to other “hits” (documents) for that same query, in the same search." }, { "code": null, "e": 8435, "s": 8092, "text": "The term query is used to “find” documents for which a field matches an exact value. We have a number of keyword fields in our index that we can apply a term query to. The example below extracts five documents where the type field is equal to TV Show (note that the size parameter controls how many records ES returns, and it defaults to 10):" }, { "code": null, "e": 8822, "s": 8435, "text": "A term query should not be used for text fields. ES changes text fields as part of analysis, tokenising the text, stripping it of punctuation, and converting it to lowercase. If type had been a text field instead of a keyword field, the query shown above would not have returned a result because any instances of “TV Show” would have been turned into [\"tv\", \"show\"] as part of analysis." }, { "code": null, "e": 9332, "s": 8822, "text": "Last but not least in our “common queries” series: the “range query”. As the name implies, the range query is used to find any documents for which a specific field’s value falls within a defined range. It can be used for, e.g. date and numeric field types. It can also be used on text and keyword fields, provided your cluster settings allow for expensive queries (the default). The query shown below runs a simple range query on release year, searching for 100 movies or TV shows released in 2012 or earlier:" }, { "code": null, "e": 9483, "s": 9332, "text": "There are several more complex queries that I tend to use. In this section, we’ll take a brief look at regex, metric aggregations, and custom filters." }, { "code": null, "e": 9780, "s": 9483, "text": "The regexp query is designed for finding documents where a term in a specific field matches a regular expression. The example below looks for any documents in our netflix_movies index where the title field includes a word that in part consists of “war” (e.g. war, warror, Warfare, warmest, etc.):" }, { "code": null, "e": 10231, "s": 9780, "text": "Regexp queries can be made case-sensitive (using the case_insensitive option, with default set to false). However, title is a text field for which analysis has not been disabled. Therefore, we can expect the terms in the title field to have been lowercased (among other things — please refer to the previous sections for more details on “analysis”). Enabling or disabling case sensitivity would therefore make no difference given our current mapping." }, { "code": null, "e": 10421, "s": 10231, "text": "ES aggregations are a great way to explore your data, and they come in three flavours: metric, bucket, and pipeline. Here we’ll look at one from the metric and one from the bucket category." }, { "code": null, "e": 10718, "s": 10421, "text": "We’ll first take a look at the stats query (a metric aggregation), which comes in handy when you’re looking to review summary statistics (min, max, mean, sum) for numeric values. For example, if we’d quickly want to see how release_year is distributed in our data, we can run the following query:" }, { "code": null, "e": 11036, "s": 10718, "text": "For aggregations we set the size parameter to 0 in our queries. This means that the search API will not return any documents (if you omit this, the hits field will contain the documents). The response for this query gives us simple summary stats for the release_year values across our documents (e.g. min, max, mean):" }, { "code": null, "e": 11173, "s": 11036, "text": "'{ \"release_year_stats\": { \"count\": 7787, \"min\": 1925.0, \"max\": 2021.0, \"avg\": 2013.932579940927, \"sum\": 15682493.0 }}'" }, { "code": null, "e": 11649, "s": 11173, "text": "Let’s now turn to our second aggregation query, this time from the bucket aggregation family. The terms aggregation is useful for getting a quick overview of the availability of observations across different categories. In our netflix_movies index, you may for example want review how many movies were released in any given year, or how many movies of each type are present in the dataset. In DSL, our query for the former (count of movies per release year) looks as follows:" }, { "code": null, "e": 11972, "s": 11649, "text": "There’s two things worth highlighting in this query. First, we specify a second size parameter in the terms object, which controls how many “term buckets” are returned (in this case: 5). Second, we order the output by the keys (i.e. the release years), in ascending order. The output from this query should look like this:" }, { "code": null, "e": 12372, "s": 11972, "text": "{ \"release_years\": { \"doc_count_error_upper_bound\": 0, \"sum_other_doc_count\": 7775, \"buckets\": [ { \"key\": 1925, \"doc_count\": 1 }, { \"key\": 1942, \"doc_count\": 2 }, { \"key\": 1943, \"doc_count\": 3 }, { \"key\": 1944, \"doc_count\": 3 }, { \"key\": 1945, \"doc_count\": 3 } ] }}" }, { "code": null, "e": 13021, "s": 12372, "text": "Let’s quickly review this output. The buckets fields include the document count for each of our five term buckets (one object for each key). In turn, thesum_other_doc_count is the sum of all counts for the buckets that were excluded from the output. Finally, the doc_count_error_upper_bound value reflects the error associated with the bucket aggregation. At this point you might wonder: “error, what error?”. ES reports an error in the response because term aggregations are approximate. This stems from the fact that documents are distributed across shards, and each shard has its own ordered list of terms, which are combined in the aggregation." }, { "code": null, "e": 13560, "s": 13021, "text": "The node that coordinates the search process requests a number of term buckets equal to size. Subsequently, the results from these shards are combined to produce the final response. We can therefore expect a greater chance of error if the specified size is less than the number of unique terms. In our example above, we have 73 distinct release_year values, so we may want to change the size parameter (and for large numbers of term buckets, the shard_size too, to address some of the additional overhead that stems from increasing size)." }, { "code": null, "e": 13951, "s": 13560, "text": "Onto our final “complex” query: the “script query”. A script query can be used if you want to use a filter of your own design on documents in your index. The script query is provided in the filter context. In the example below, I’ve written a simple script that extracts documents for which release_year is greater than 2018 (we could achieve the same result with a range query, see above)." }, { "code": null, "e": 14505, "s": 13951, "text": "The source field contains the script, and the params field includes the start_year value that is used by the script. The default language for script queries is “painless” (specified in the lang field), but other languages are available, including Lucene’s Expressions Language and Mustache Language. If you have custom scripts that you use often, you can use a store scripts on the cluster state using the _scripts endpoint, so you can retrieve them for later use. Storing scripts speeds up search since it often reduces the time needed for compilation." }, { "code": null, "e": 15056, "s": 14505, "text": "For the SQL fans out there: you can use SQL syntax to query your ES indices. This feature is part of X-Pack and you can use to directly execute SQL queries against your ES indices in the console on your cloud-based ES service, such as AWS or Elastic.co, or using the Python Elasticsearch Client. (Note that this does not work on Bonsai as the X-Pack plugin is not included because it requires a license for commercial purposes. I’ve therefore run the below API calls for the SQL translate API on Elastic.co instead, which offers a 14-day free trial)." }, { "code": null, "e": 15379, "s": 15056, "text": "If you work on Elastic.co, you can use the SQL translate API to translate SQL syntax to native Elasticsearch queries. From the console, it’s as simple as using a POST request with your SQL syntax in a JSON document. For example, a query to get a list of titles of Netflix movies released in 2015 or later looks as follows:" }, { "code": null, "e": 15452, "s": 15379, "text": "{\"query\": \"SELECT title FROM netflix_movies WHERE release_year >= 2015\"}" }, { "code": null, "e": 15686, "s": 15452, "text": "If you send this document using a POST request on the translate endpoint (POST _sql/translate) on your API console, it will return the corresponding query in native a native ES query (DSL). For our example, the resulting ES query is:" }, { "code": null, "e": 16024, "s": 15686, "text": "{ \"sort\": [ { \"_doc\": { \"order\": \"asc\" } } ], \"query\": { \"range\": { \"release_year\": { \"to\": null, \"include_upper\": false, \"boost\": 1, \"from\": 2015, \"include_lower\": true } } }, \"_source\": false, \"fields\": [ { \"field\": \"title\" } ], \"size\": 1000}" }, { "code": null, "e": 16286, "s": 16024, "text": "You can also get the output directly, skipping the “translate step” altogether. If you make a POST request with your JSON document with _sql?format=txt, the API returns the response data in a nicely formatted text format (for JSON format, use _sql?format=json):" }, { "code": null, "e": 17103, "s": 16286, "text": "title ------------------------------------- Black Crows Black Earth Rising Black Lightning Black Man White Skin Black Mirror Black Mirror: Bandersnatch Black Panther Black Sea Black Site Delta Black Snow..........." }, { "code": null, "e": 17371, "s": 17103, "text": "Similarly, you can run simple GROUP BY queries (provided the field you perform the aggregation on is not of the text type). For example, the following query will return the number of movies for each release year (here I’m limiting the output to the first five years):" }, { "code": null, "e": 17497, "s": 17371, "text": "POST _sql?format=txt{\"query\": \"SELECT release_year, COUNT(*) as n_entries FROM netflix_movies GROUP BY release_year LIMIT 5\"}" }, { "code": null, "e": 17536, "s": 17497, "text": "Again, the output is nicely formatted:" }, { "code": null, "e": 17745, "s": 17536, "text": "release_year | n_entries ---------------+--------------- 1925 |1 1942 |2 1943 |3 1944 |3 1945 |3" }, { "code": null, "e": 17854, "s": 17745, "text": "And that’s it! We’ve now reviewed the basics of DSL and have run a couple of basic and more complex queries." }, { "code": null, "e": 17877, "s": 17854, "text": "Thank you for reading!" }, { "code": null, "e": 18160, "s": 17877, "text": "Support my work: If you liked this article and you’d like to support my work, please consider becoming a paying Medium member via my referral page. The price of the subscription is the same if you sign up via my referral page, but I will receive part of your monthly membership fee." }, { "code": null, "e": 18231, "s": 18160, "text": "If you liked this article, here are some other articles you may enjoy:" }, { "code": null, "e": 18254, "s": 18231, "text": "towardsdatascience.com" }, { "code": null, "e": 18277, "s": 18254, "text": "towardsdatascience.com" }, { "code": null, "e": 18300, "s": 18277, "text": "towardsdatascience.com" }, { "code": null, "e": 18575, "s": 18300, "text": "Disclaimer: “Elasticsearch” is a trademark of Elasticsearch BV, registered in the U.S. and in other countries. Description and/or use of any third-party services and/or trademarks in this blog post should not be seen as endorsement for or by their respective rights holders." } ]
Scikit Learn - Anomaly Detection
Here, we will learn about what is anomaly detection in Sklearn and how it is used in identification of the data points. Anomaly detection is a technique used to identify data points in dataset that does not fit well with the rest of the data. It has many applications in business such as fraud detection, intrusion detection, system health monitoring, surveillance, and predictive maintenance. Anomalies, which are also called outlier, can be divided into following three categories − Point anomalies − It occurs when an individual data instance is considered as anomalous w.r.t the rest of the data. Point anomalies − It occurs when an individual data instance is considered as anomalous w.r.t the rest of the data. Contextual anomalies − Such kind of anomaly is context specific. It occurs if a data instance is anomalous in a specific context. Contextual anomalies − Such kind of anomaly is context specific. It occurs if a data instance is anomalous in a specific context. Collective anomalies − It occurs when a collection of related data instances is anomalous w.r.t entire dataset rather than individual values. Collective anomalies − It occurs when a collection of related data instances is anomalous w.r.t entire dataset rather than individual values. Two methods namely outlier detection and novelty detection can be used for anomaly detection. It’s necessary to see the distinction between them. The training data contains outliers that are far from the rest of the data. Such outliers are defined as observations. That’s the reason, outlier detection estimators always try to fit the region having most concentrated training data while ignoring the deviant observations. It is also known as unsupervised anomaly detection. It is concerned with detecting an unobserved pattern in new observations which is not included in training data. Here, the training data is not polluted by the outliers. It is also known as semi-supervised anomaly detection. There are set of ML tools, provided by scikit-learn, which can be used for both outlier detection as well novelty detection. These tools first implementing object learning from the data in an unsupervised by using fit () method as follows − estimator.fit(X_train) Now, the new observations would be sorted as inliers (labeled 1) or outliers (labeled -1) by using predict() method as follows − estimator.fit(X_test) The estimator will first compute the raw scoring function and then predict method will make use of threshold on that raw scoring function. We can access this raw scoring function with the help of score_sample method and can control the threshold by contamination parameter. We can also define decision_function method that defines outliers as negative value and inliers as non-negative value. estimator.decision_function(X_test) Let us begin by understanding what an elliptic envelop is. This algorithm assume that regular data comes from a known distribution such as Gaussian distribution. For outlier detection, Scikit-learn provides an object named covariance.EllipticEnvelop. This object fits a robust covariance estimate to the data, and thus, fits an ellipse to the central data points. It ignores the points outside the central mode. Following table consist the parameters used by sklearn. covariance.EllipticEnvelop method − store_precision − Boolean, optional, default = True We can specify it if the estimated precision is stored. assume_centered − Boolean, optional, default = False If we set it False, it will compute the robust location and covariance directly with the help of FastMCD algorithm. On the other hand, if set True, it will compute the support of robust location and covarian. support_fraction − float in (0., 1.), optional, default = None This parameter tells the method that how much proportion of points to be included in the support of the raw MCD estimates. contamination − float in (0., 1.), optional, default = 0.1 It provides the proportion of the outliers in the data set. random_state − int, RandomState instance or None, optional, default = none This parameter represents the seed of the pseudo random number generated which is used while shuffling the data. Followings are the options − int − In this case, random_state is the seed used by random number generator. int − In this case, random_state is the seed used by random number generator. RandomState instance − In this case, random_state is the random number generator. RandomState instance − In this case, random_state is the random number generator. None − In this case, the random number generator is the RandonState instance used by np.random. None − In this case, the random number generator is the RandonState instance used by np.random. Following table consist the attributes used by sklearn. covariance.EllipticEnvelop method − support_ − array-like, shape(n_samples,) It represents the mask of the observations used to compute robust estimates of location and shape. location_ − array-like, shape (n_features) It returns the estimated robust location. covariance_ − array-like, shape (n_features, n_features) It returns the estimated robust covariance matrix. precision_ − array-like, shape (n_features, n_features) It returns the estimated pseudo inverse matrix. offset_ − float It is used to define the decision function from the raw scores. decision_function = score_samples -offset_ Implementation Example import numpy as np^M from sklearn.covariance import EllipticEnvelope^M true_cov = np.array([[.5, .6],[.6, .4]]) X = np.random.RandomState(0).multivariate_normal(mean = [0, 0], cov=true_cov,size=500) cov = EllipticEnvelope(random_state = 0).fit(X)^M # Now we can use predict method. It will return 1 for an inlier and -1 for an outlier. cov.predict([[0, 0],[2, 2]]) Output array([ 1, -1]) In case of high-dimensional dataset, one efficient way for outlier detection is to use random forests. The scikit-learn provides ensemble.IsolationForest method that isolates the observations by randomly selecting a feature. Afterwards, it randomly selects a value between the maximum and minimum values of the selected features. Here, the number of splitting needed to isolate a sample is equivalent to path length from the root node to the terminating node. Followings table consist the parameters used by sklearn. ensemble.IsolationForest method − n_estimators − int, optional, default = 100 It represents the number of base estimators in the ensemble. max_samples − int or float, optional, default = “auto” It represents the number of samples to be drawn from X to train each base estimator. If we choose int as its value, it will draw max_samples samples. If we choose float as its value, it will draw max_samples ∗ X.shape[0] samples. And, if we choose auto as its value, it will draw max_samples = min(256,n_samples). support_fraction − float in (0., 1.), optional, default = None This parameter tells the method that how much proportion of points to be included in the support of the raw MCD estimates. contamination − auto or float, optional, default = auto It provides the proportion of the outliers in the data set. If we set it default i.e. auto, it will determine the threshold as in the original paper. If set to float, the range of contamination will be in the range of [0,0.5]. random_state − int, RandomState instance or None, optional, default = none This parameter represents the seed of the pseudo random number generated which is used while shuffling the data. Followings are the options − int − In this case, random_state is the seed used by random number generator. int − In this case, random_state is the seed used by random number generator. RandomState instance − In this case, random_state is the random number generator. RandomState instance − In this case, random_state is the random number generator. None − In this case, the random number generator is the RandonState instance used by np.random. None − In this case, the random number generator is the RandonState instance used by np.random. max_features − int or float, optional (default = 1.0) It represents the number of features to be drawn from X to train each base estimator. If we choose int as its value, it will draw max_features features. If we choose float as its value, it will draw max_features * X.shape[1] samples. bootstrap − Boolean, optional (default = False) Its default option is False which means the sampling would be performed without replacement. And on the other hand, if set to True, means individual trees are fit on a random subset of the training data sampled with replacement. n_jobs − int or None, optional (default = None) It represents the number of jobs to be run in parallel for fit() and predict() methods both. verbose − int, optional (default = 0) This parameter controls the verbosity of the tree building process. warm_start − Bool, optional (default=False) If warm_start = true, we can reuse previous calls solution to fit and can add more estimators to the ensemble. But if is set to false, we need to fit a whole new forest. Following table consist the attributes used by sklearn. ensemble.IsolationForest method − estimators_ − list of DecisionTreeClassifier Providing the collection of all fitted sub-estimators. max_samples_ − integer It provides the actual number of samples used. offset_ − float It is used to define the decision function from the raw scores. decision_function = score_samples -offset_ Implementation Example The Python script below will use sklearn. ensemble.IsolationForest method to fit 10 trees on given data from sklearn.ensemble import IsolationForest import numpy as np X = np.array([[-1, -2], [-3, -3], [-3, -4], [0, 0], [-50, 60]]) OUTDClf = IsolationForest(n_estimators = 10) OUTDclf.fit(X) Output IsolationForest( behaviour = 'old', bootstrap = False, contamination='legacy', max_features = 1.0, max_samples = 'auto', n_estimators = 10, n_jobs=None, random_state = None, verbose = 0 ) Local Outlier Factor (LOF) algorithm is another efficient algorithm to perform outlier detection on high dimension data. The scikit-learn provides neighbors.LocalOutlierFactor method that computes a score, called local outlier factor, reflecting the degree of anomality of the observations. The main logic of this algorithm is to detect the samples that have a substantially lower density than its neighbors. Thats why it measures the local density deviation of given data points w.r.t. their neighbors. Followings table consist the parameters used by sklearn. neighbors.LocalOutlierFactor method n_neighbors − int, optional, default = 20 It represents the number of neighbors use by default for kneighbors query. All samples would be used if . algorithm − optional Which algorithm to be used for computing nearest neighbors. If you choose ball_tree, it will use BallTree algorithm. If you choose ball_tree, it will use BallTree algorithm. If you choose kd_tree, it will use KDTree algorithm. If you choose kd_tree, it will use KDTree algorithm. If you choose brute, it will use brute-force search algorithm. If you choose brute, it will use brute-force search algorithm. If you choose auto, it will decide the most appropriate algorithm on the basis of the value we passed to fit() method. If you choose auto, it will decide the most appropriate algorithm on the basis of the value we passed to fit() method. leaf_size − int, optional, default = 30 The value of this parameter can affect the speed of the construction and query. It also affects the memory required to store the tree. This parameter is passed to BallTree or KdTree algorithms. contamination − auto or float, optional, default = auto It provides the proportion of the outliers in the data set. If we set it default i.e. auto, it will determine the threshold as in the original paper. If set to float, the range of contamination will be in the range of [0,0.5]. metric − string or callable, default It represents the metric used for distance computation. P − int, optional (default = 2) It is the parameter for the Minkowski metric. P=1 is equivalent to using manhattan_distance i.e. L1, whereas P=2 is equivalent to using euclidean_distance i.e. L2. novelty − Boolean, (default = False) By default, LOF algorithm is used for outlier detection but it can be used for novelty detection if we set novelty = true. n_jobs − int or None, optional (default = None) It represents the number of jobs to be run in parallel for fit() and predict() methods both. Following table consist the attributes used by sklearn.neighbors.LocalOutlierFactor method − negative_outlier_factor_ − numpy array, shape(n_samples,) Providing opposite LOF of the training samples. n_neighbors_ − integer It provides the actual number of neighbors used for neighbors queries. offset_ − float It is used to define the binary labels from the raw scores. Implementation Example The Python script given below will use sklearn.neighbors.LocalOutlierFactor method to construct NeighborsClassifier class from any array corresponding our data set from sklearn.neighbors import NearestNeighbors samples = [[0., 0., 0.], [0., .5, 0.], [1., 1., .5]] LOFneigh = NearestNeighbors(n_neighbors = 1, algorithm = "ball_tree",p=1) LOFneigh.fit(samples) Output NearestNeighbors( algorithm = 'ball_tree', leaf_size = 30, metric='minkowski', metric_params = None, n_jobs = None, n_neighbors = 1, p = 1, radius = 1.0 ) Example Now, we can ask from this constructed classifier is the closet point to [0.5, 1., 1.5] by using the following python script − print(neigh.kneighbors([[.5, 1., 1.5]]) Output (array([[1.7]]), array([[1]], dtype = int64)) The One-Class SVM, introduced by Schölkopf et al., is the unsupervised Outlier Detection. It is also very efficient in high-dimensional data and estimates the support of a high-dimensional distribution. It is implemented in the Support Vector Machines module in the Sklearn.svm.OneClassSVM object. For defining a frontier, it requires a kernel (mostly used is RBF) and a scalar parameter. For better understanding let's fit our data with svm.OneClassSVM object − from sklearn.svm import OneClassSVM X = [[0], [0.89], [0.90], [0.91], [1]] OSVMclf = OneClassSVM(gamma = 'scale').fit(X) Now, we can get the score_samples for input data as follows − OSVMclf.score_samples(X) array([1.12218594, 1.58645126, 1.58673086, 1.58645127, 1.55713767]) 11 Lectures 2 hours PARTHA MAJUMDAR Print Add Notes Bookmark this page
[ { "code": null, "e": 2341, "s": 2221, "text": "Here, we will learn about what is anomaly detection in Sklearn and how it is used in identification of the data points." }, { "code": null, "e": 2706, "s": 2341, "text": "Anomaly detection is a technique used to identify data points in dataset that does not fit well with the rest of the data. It has many applications in business such as fraud detection, intrusion detection, system health monitoring, surveillance, and predictive maintenance. Anomalies, which are also called outlier, can be divided into following three categories −" }, { "code": null, "e": 2822, "s": 2706, "text": "Point anomalies − It occurs when an individual data instance is considered as anomalous w.r.t the rest of the data." }, { "code": null, "e": 2938, "s": 2822, "text": "Point anomalies − It occurs when an individual data instance is considered as anomalous w.r.t the rest of the data." }, { "code": null, "e": 3068, "s": 2938, "text": "Contextual anomalies − Such kind of anomaly is context specific. It occurs if a data instance is anomalous in a specific context." }, { "code": null, "e": 3198, "s": 3068, "text": "Contextual anomalies − Such kind of anomaly is context specific. It occurs if a data instance is anomalous in a specific context." }, { "code": null, "e": 3340, "s": 3198, "text": "Collective anomalies − It occurs when a collection of related data instances is anomalous w.r.t entire dataset rather than individual values." }, { "code": null, "e": 3482, "s": 3340, "text": "Collective anomalies − It occurs when a collection of related data instances is anomalous w.r.t entire dataset rather than individual values." }, { "code": null, "e": 3628, "s": 3482, "text": "Two methods namely outlier detection and novelty detection can be used for anomaly detection. It’s necessary to see the distinction between them." }, { "code": null, "e": 3956, "s": 3628, "text": "The training data contains outliers that are far from the rest of the data. Such outliers are defined as observations. That’s the reason, outlier detection estimators always try to fit the region having most concentrated training data while ignoring the deviant observations. It is also known as unsupervised anomaly detection." }, { "code": null, "e": 4181, "s": 3956, "text": "It is concerned with detecting an unobserved pattern in new observations which is not included in training data. Here, the training data is not polluted by the outliers. It is also known as semi-supervised anomaly detection." }, { "code": null, "e": 4422, "s": 4181, "text": "There are set of ML tools, provided by scikit-learn, which can be used for both outlier detection as well novelty detection. These tools first implementing object learning from the data in an unsupervised by using fit () method as follows −" }, { "code": null, "e": 4446, "s": 4422, "text": "estimator.fit(X_train)\n" }, { "code": null, "e": 4575, "s": 4446, "text": "Now, the new observations would be sorted as inliers (labeled 1) or outliers (labeled -1) by using predict() method as follows −" }, { "code": null, "e": 4598, "s": 4575, "text": "estimator.fit(X_test)\n" }, { "code": null, "e": 4872, "s": 4598, "text": "The estimator will first compute the raw scoring function and then predict method will make use of threshold on that raw scoring function. We can access this raw scoring function with the help of score_sample method and can control the threshold by contamination parameter." }, { "code": null, "e": 4991, "s": 4872, "text": "We can also define decision_function method that defines outliers as negative value and inliers as non-negative value." }, { "code": null, "e": 5028, "s": 4991, "text": "estimator.decision_function(X_test)\n" }, { "code": null, "e": 5087, "s": 5028, "text": "Let us begin by understanding what an elliptic envelop is." }, { "code": null, "e": 5279, "s": 5087, "text": "This algorithm assume that regular data comes from a known distribution such as Gaussian distribution. For outlier detection, Scikit-learn provides an object named covariance.EllipticEnvelop." }, { "code": null, "e": 5440, "s": 5279, "text": "This object fits a robust covariance estimate to the data, and thus, fits an ellipse to the central data points. It ignores the points outside the central mode." }, { "code": null, "e": 5532, "s": 5440, "text": "Following table consist the parameters used by sklearn. covariance.EllipticEnvelop method −" }, { "code": null, "e": 5584, "s": 5532, "text": "store_precision − Boolean, optional, default = True" }, { "code": null, "e": 5640, "s": 5584, "text": "We can specify it if the estimated precision is stored." }, { "code": null, "e": 5693, "s": 5640, "text": "assume_centered − Boolean, optional, default = False" }, { "code": null, "e": 5902, "s": 5693, "text": "If we set it False, it will compute the robust location and covariance directly with the help of FastMCD algorithm. On the other hand, if set True, it will compute the support of robust location and covarian." }, { "code": null, "e": 5965, "s": 5902, "text": "support_fraction − float in (0., 1.), optional, default = None" }, { "code": null, "e": 6088, "s": 5965, "text": "This parameter tells the method that how much proportion of points to be included in the support of the raw MCD estimates." }, { "code": null, "e": 6147, "s": 6088, "text": "contamination − float in (0., 1.), optional, default = 0.1" }, { "code": null, "e": 6207, "s": 6147, "text": "It provides the proportion of the outliers in the data set." }, { "code": null, "e": 6282, "s": 6207, "text": "random_state − int, RandomState instance or None, optional, default = none" }, { "code": null, "e": 6424, "s": 6282, "text": "This parameter represents the seed of the pseudo random number generated which is used while shuffling the data. Followings are the options −" }, { "code": null, "e": 6502, "s": 6424, "text": "int − In this case, random_state is the seed used by random number generator." }, { "code": null, "e": 6580, "s": 6502, "text": "int − In this case, random_state is the seed used by random number generator." }, { "code": null, "e": 6662, "s": 6580, "text": "RandomState instance − In this case, random_state is the random number generator." }, { "code": null, "e": 6744, "s": 6662, "text": "RandomState instance − In this case, random_state is the random number generator." }, { "code": null, "e": 6840, "s": 6744, "text": "None − In this case, the random number generator is the RandonState instance used by np.random." }, { "code": null, "e": 6936, "s": 6840, "text": "None − In this case, the random number generator is the RandonState instance used by np.random." }, { "code": null, "e": 7028, "s": 6936, "text": "Following table consist the attributes used by sklearn. covariance.EllipticEnvelop method −" }, { "code": null, "e": 7069, "s": 7028, "text": "support_ − array-like, shape(n_samples,)" }, { "code": null, "e": 7168, "s": 7069, "text": "It represents the mask of the observations used to compute robust estimates of location and shape." }, { "code": null, "e": 7211, "s": 7168, "text": "location_ − array-like, shape (n_features)" }, { "code": null, "e": 7253, "s": 7211, "text": "It returns the estimated robust location." }, { "code": null, "e": 7310, "s": 7253, "text": "covariance_ − array-like, shape (n_features, n_features)" }, { "code": null, "e": 7361, "s": 7310, "text": "It returns the estimated robust covariance matrix." }, { "code": null, "e": 7417, "s": 7361, "text": "precision_ − array-like, shape (n_features, n_features)" }, { "code": null, "e": 7465, "s": 7417, "text": "It returns the estimated pseudo inverse matrix." }, { "code": null, "e": 7481, "s": 7465, "text": "offset_ − float" }, { "code": null, "e": 7588, "s": 7481, "text": "It is used to define the decision function from the raw scores. decision_function = score_samples -offset_" }, { "code": null, "e": 7611, "s": 7588, "text": "Implementation Example" }, { "code": null, "e": 7976, "s": 7611, "text": "import numpy as np^M\nfrom sklearn.covariance import EllipticEnvelope^M\ntrue_cov = np.array([[.5, .6],[.6, .4]])\nX = np.random.RandomState(0).multivariate_normal(mean = [0, 0], cov=true_cov,size=500)\ncov = EllipticEnvelope(random_state = 0).fit(X)^M\n# Now we can use predict method. It will return 1 for an inlier and -1 for an outlier.\ncov.predict([[0, 0],[2, 2]])" }, { "code": null, "e": 7983, "s": 7976, "text": "Output" }, { "code": null, "e": 8000, "s": 7983, "text": "array([ 1, -1])\n" }, { "code": null, "e": 8330, "s": 8000, "text": "In case of high-dimensional dataset, one efficient way for outlier detection is to use random forests. The scikit-learn provides ensemble.IsolationForest method that isolates the observations by randomly selecting a feature. Afterwards, it randomly selects a value between the maximum and minimum values of the selected features." }, { "code": null, "e": 8460, "s": 8330, "text": "Here, the number of splitting needed to isolate a sample is equivalent to path length from the root node to the terminating node." }, { "code": null, "e": 8551, "s": 8460, "text": "Followings table consist the parameters used by sklearn. ensemble.IsolationForest method −" }, { "code": null, "e": 8595, "s": 8551, "text": "n_estimators − int, optional, default = 100" }, { "code": null, "e": 8656, "s": 8595, "text": "It represents the number of base estimators in the ensemble." }, { "code": null, "e": 8711, "s": 8656, "text": "max_samples − int or float, optional, default = “auto”" }, { "code": null, "e": 9025, "s": 8711, "text": "It represents the number of samples to be drawn from X to train each base estimator. If we choose int as its value, it will draw max_samples samples. If we choose float as its value, it will draw max_samples ∗ X.shape[0] samples. And, if we choose auto as its value, it will draw max_samples = min(256,n_samples)." }, { "code": null, "e": 9088, "s": 9025, "text": "support_fraction − float in (0., 1.), optional, default = None" }, { "code": null, "e": 9211, "s": 9088, "text": "This parameter tells the method that how much proportion of points to be included in the support of the raw MCD estimates." }, { "code": null, "e": 9267, "s": 9211, "text": "contamination − auto or float, optional, default = auto" }, { "code": null, "e": 9494, "s": 9267, "text": "It provides the proportion of the outliers in the data set. If we set it default i.e. auto, it will determine the threshold as in the original paper. If set to float, the range of contamination will be in the range of [0,0.5]." }, { "code": null, "e": 9569, "s": 9494, "text": "random_state − int, RandomState instance or None, optional, default = none" }, { "code": null, "e": 9711, "s": 9569, "text": "This parameter represents the seed of the pseudo random number generated which is used while shuffling the data. Followings are the options −" }, { "code": null, "e": 9789, "s": 9711, "text": "int − In this case, random_state is the seed used by random number generator." }, { "code": null, "e": 9867, "s": 9789, "text": "int − In this case, random_state is the seed used by random number generator." }, { "code": null, "e": 9949, "s": 9867, "text": "RandomState instance − In this case, random_state is the random number generator." }, { "code": null, "e": 10031, "s": 9949, "text": "RandomState instance − In this case, random_state is the random number generator." }, { "code": null, "e": 10127, "s": 10031, "text": "None − In this case, the random number generator is the RandonState instance used by np.random." }, { "code": null, "e": 10223, "s": 10127, "text": "None − In this case, the random number generator is the RandonState instance used by np.random." }, { "code": null, "e": 10277, "s": 10223, "text": "max_features − int or float, optional (default = 1.0)" }, { "code": null, "e": 10511, "s": 10277, "text": "It represents the number of features to be drawn from X to train each base estimator. If we choose int as its value, it will draw max_features features. If we choose float as its value, it will draw max_features * X.shape[1] samples." }, { "code": null, "e": 10559, "s": 10511, "text": "bootstrap − Boolean, optional (default = False)" }, { "code": null, "e": 10788, "s": 10559, "text": "Its default option is False which means the sampling would be performed without replacement. And on the other hand, if set to True, means individual trees are fit on a random subset of the training data sampled with replacement." }, { "code": null, "e": 10836, "s": 10788, "text": "n_jobs − int or None, optional (default = None)" }, { "code": null, "e": 10929, "s": 10836, "text": "It represents the number of jobs to be run in parallel for fit() and predict() methods both." }, { "code": null, "e": 10967, "s": 10929, "text": "verbose − int, optional (default = 0)" }, { "code": null, "e": 11035, "s": 10967, "text": "This parameter controls the verbosity of the tree building process." }, { "code": null, "e": 11079, "s": 11035, "text": "warm_start − Bool, optional (default=False)" }, { "code": null, "e": 11249, "s": 11079, "text": "If warm_start = true, we can reuse previous calls solution to fit and can add more estimators to the ensemble. But if is set to false, we need to fit a whole new forest." }, { "code": null, "e": 11339, "s": 11249, "text": "Following table consist the attributes used by sklearn. ensemble.IsolationForest method −" }, { "code": null, "e": 11384, "s": 11339, "text": "estimators_ − list of DecisionTreeClassifier" }, { "code": null, "e": 11439, "s": 11384, "text": "Providing the collection of all fitted sub-estimators." }, { "code": null, "e": 11462, "s": 11439, "text": "max_samples_ − integer" }, { "code": null, "e": 11509, "s": 11462, "text": "It provides the actual number of samples used." }, { "code": null, "e": 11525, "s": 11509, "text": "offset_ − float" }, { "code": null, "e": 11632, "s": 11525, "text": "It is used to define the decision function from the raw scores. decision_function = score_samples -offset_" }, { "code": null, "e": 11655, "s": 11632, "text": "Implementation Example" }, { "code": null, "e": 11759, "s": 11655, "text": "The Python script below will use sklearn. ensemble.IsolationForest method to fit 10 trees on given data" }, { "code": null, "e": 11947, "s": 11759, "text": "from sklearn.ensemble import IsolationForest\nimport numpy as np\nX = np.array([[-1, -2], [-3, -3], [-3, -4], [0, 0], [-50, 60]])\nOUTDClf = IsolationForest(n_estimators = 10)\nOUTDclf.fit(X)" }, { "code": null, "e": 11954, "s": 11947, "text": "Output" }, { "code": null, "e": 12152, "s": 11954, "text": "IsolationForest(\n behaviour = 'old', bootstrap = False, contamination='legacy',\n max_features = 1.0, max_samples = 'auto', n_estimators = 10, n_jobs=None,\n random_state = None, verbose = 0\n)\n" }, { "code": null, "e": 12656, "s": 12152, "text": "Local Outlier Factor (LOF) algorithm is another efficient algorithm to perform outlier detection on high dimension data. The scikit-learn provides neighbors.LocalOutlierFactor method that computes a score, called local outlier factor, reflecting the degree of anomality of the observations. The main logic of this algorithm is to detect the samples that have a substantially lower density than its neighbors. Thats why it measures the local density deviation of given data points w.r.t. their neighbors." }, { "code": null, "e": 12749, "s": 12656, "text": "Followings table consist the parameters used by sklearn. neighbors.LocalOutlierFactor method" }, { "code": null, "e": 12791, "s": 12749, "text": "n_neighbors − int, optional, default = 20" }, { "code": null, "e": 12897, "s": 12791, "text": "It represents the number of neighbors use by default for kneighbors query. All samples would be used if ." }, { "code": null, "e": 12918, "s": 12897, "text": "algorithm − optional" }, { "code": null, "e": 12978, "s": 12918, "text": "Which algorithm to be used for computing nearest neighbors." }, { "code": null, "e": 13035, "s": 12978, "text": "If you choose ball_tree, it will use BallTree algorithm." }, { "code": null, "e": 13092, "s": 13035, "text": "If you choose ball_tree, it will use BallTree algorithm." }, { "code": null, "e": 13145, "s": 13092, "text": "If you choose kd_tree, it will use KDTree algorithm." }, { "code": null, "e": 13198, "s": 13145, "text": "If you choose kd_tree, it will use KDTree algorithm." }, { "code": null, "e": 13261, "s": 13198, "text": "If you choose brute, it will use brute-force search algorithm." }, { "code": null, "e": 13324, "s": 13261, "text": "If you choose brute, it will use brute-force search algorithm." }, { "code": null, "e": 13443, "s": 13324, "text": "If you choose auto, it will decide the most appropriate algorithm on the basis of the value we passed to fit() method." }, { "code": null, "e": 13562, "s": 13443, "text": "If you choose auto, it will decide the most appropriate algorithm on the basis of the value we passed to fit() method." }, { "code": null, "e": 13602, "s": 13562, "text": "leaf_size − int, optional, default = 30" }, { "code": null, "e": 13796, "s": 13602, "text": "The value of this parameter can affect the speed of the construction and query. It also affects the memory required to store the tree. This parameter is passed to BallTree or KdTree algorithms." }, { "code": null, "e": 13852, "s": 13796, "text": "contamination − auto or float, optional, default = auto" }, { "code": null, "e": 14079, "s": 13852, "text": "It provides the proportion of the outliers in the data set. If we set it default i.e. auto, it will determine the threshold as in the original paper. If set to float, the range of contamination will be in the range of [0,0.5]." }, { "code": null, "e": 14116, "s": 14079, "text": "metric − string or callable, default" }, { "code": null, "e": 14172, "s": 14116, "text": "It represents the metric used for distance computation." }, { "code": null, "e": 14204, "s": 14172, "text": "P − int, optional (default = 2)" }, { "code": null, "e": 14368, "s": 14204, "text": "It is the parameter for the Minkowski metric. P=1 is equivalent to using manhattan_distance i.e. L1, whereas P=2 is equivalent to using euclidean_distance i.e. L2." }, { "code": null, "e": 14405, "s": 14368, "text": "novelty − Boolean, (default = False)" }, { "code": null, "e": 14528, "s": 14405, "text": "By default, LOF algorithm is used for outlier detection but it can be used for novelty detection if we set novelty = true." }, { "code": null, "e": 14576, "s": 14528, "text": "n_jobs − int or None, optional (default = None)" }, { "code": null, "e": 14669, "s": 14576, "text": "It represents the number of jobs to be run in parallel for fit() and predict() methods both." }, { "code": null, "e": 14762, "s": 14669, "text": "Following table consist the attributes used by sklearn.neighbors.LocalOutlierFactor method −" }, { "code": null, "e": 14820, "s": 14762, "text": "negative_outlier_factor_ − numpy array, shape(n_samples,)" }, { "code": null, "e": 14868, "s": 14820, "text": "Providing opposite LOF of the training samples." }, { "code": null, "e": 14891, "s": 14868, "text": "n_neighbors_ − integer" }, { "code": null, "e": 14962, "s": 14891, "text": "It provides the actual number of neighbors used for neighbors queries." }, { "code": null, "e": 14978, "s": 14962, "text": "offset_ − float" }, { "code": null, "e": 15038, "s": 14978, "text": "It is used to define the binary labels from the raw scores." }, { "code": null, "e": 15061, "s": 15038, "text": "Implementation Example" }, { "code": null, "e": 15225, "s": 15061, "text": "The Python script given below will use sklearn.neighbors.LocalOutlierFactor method to construct NeighborsClassifier class from any array corresponding our data set" }, { "code": null, "e": 15421, "s": 15225, "text": "from sklearn.neighbors import NearestNeighbors\nsamples = [[0., 0., 0.], [0., .5, 0.], [1., 1., .5]]\nLOFneigh = NearestNeighbors(n_neighbors = 1, algorithm = \"ball_tree\",p=1)\nLOFneigh.fit(samples)" }, { "code": null, "e": 15428, "s": 15421, "text": "Output" }, { "code": null, "e": 15590, "s": 15428, "text": "NearestNeighbors(\n algorithm = 'ball_tree', leaf_size = 30, metric='minkowski',\n metric_params = None, n_jobs = None, n_neighbors = 1, p = 1, radius = 1.0\n)\n" }, { "code": null, "e": 15598, "s": 15590, "text": "Example" }, { "code": null, "e": 15725, "s": 15598, "text": "Now, we can ask from this constructed classifier is the closet point to [0.5, 1., 1.5] by using the following python script −" }, { "code": null, "e": 15765, "s": 15725, "text": "print(neigh.kneighbors([[.5, 1., 1.5]])" }, { "code": null, "e": 15772, "s": 15765, "text": "Output" }, { "code": null, "e": 15819, "s": 15772, "text": "(array([[1.7]]), array([[1]], dtype = int64))\n" }, { "code": null, "e": 16209, "s": 15819, "text": "The One-Class SVM, introduced by Schölkopf et al., is the unsupervised Outlier Detection. It is also very efficient in high-dimensional data and estimates the support of a high-dimensional distribution. It is implemented in the Support Vector Machines module in the Sklearn.svm.OneClassSVM object. For defining a frontier, it requires a kernel (mostly used is RBF) and a scalar parameter." }, { "code": null, "e": 16283, "s": 16209, "text": "For better understanding let's fit our data with svm.OneClassSVM object −" }, { "code": null, "e": 16404, "s": 16283, "text": "from sklearn.svm import OneClassSVM\nX = [[0], [0.89], [0.90], [0.91], [1]]\nOSVMclf = OneClassSVM(gamma = 'scale').fit(X)" }, { "code": null, "e": 16466, "s": 16404, "text": "Now, we can get the score_samples for input data as follows −" }, { "code": null, "e": 16491, "s": 16466, "text": "OSVMclf.score_samples(X)" }, { "code": null, "e": 16560, "s": 16491, "text": "array([1.12218594, 1.58645126, 1.58673086, 1.58645127, 1.55713767])\n" }, { "code": null, "e": 16593, "s": 16560, "text": "\n 11 Lectures \n 2 hours \n" }, { "code": null, "e": 16610, "s": 16593, "text": " PARTHA MAJUMDAR" }, { "code": null, "e": 16617, "s": 16610, "text": " Print" }, { "code": null, "e": 16628, "s": 16617, "text": " Add Notes" } ]
What is the difference between Read() and ReadLine() methods in C#?
The Read() reads the next characters from the standard input stream. If a key is pressed on the console, then it would close. int a = Console.Read() Console.WriteLine(a); It reads the next line of characters from the standard input stream. Live Demo using System; class Program { static void Main() { int x = 10; Console.WriteLine(x); Console.Write("\nPress any key to continue... "); Console.ReadLine(); } } 10 Press any key to continue...
[ { "code": null, "e": 1188, "s": 1062, "text": "The Read() reads the next characters from the standard input stream. If a key is pressed on the console, then it would close." }, { "code": null, "e": 1233, "s": 1188, "text": "int a = Console.Read()\nConsole.WriteLine(a);" }, { "code": null, "e": 1302, "s": 1233, "text": "It reads the next line of characters from the standard input stream." }, { "code": null, "e": 1313, "s": 1302, "text": " Live Demo" }, { "code": null, "e": 1504, "s": 1313, "text": "using System;\nclass Program {\n static void Main() {\n\n int x = 10;\n Console.WriteLine(x);\n Console.Write(\"\\nPress any key to continue... \");\n Console.ReadLine();\n\n }\n}" }, { "code": null, "e": 1536, "s": 1504, "text": "10\nPress any key to continue..." } ]
SQL Tryit Editor v1.6
SELECT Employees.LastName, COUNT(Orders.OrderID) AS NumberOfOrders FROM Orders INNER JOIN Employees ON Orders.EmployeeID = Employees.EmployeeID WHERE LastName = 'Davolio' OR LastName = 'Fuller' GROUP BY LastName HAVING COUNT(Orders.OrderID) > 25; ​ Edit the SQL Statement, and click "Run SQL" to see the result. This SQL-Statement is not supported in the WebSQL Database. The example still works, because it uses a modified version of SQL. Your browser does not support WebSQL. Your are now using a light-version of the Try-SQL Editor, with a read-only Database. If you switch to a browser with WebSQL support, you can try any SQL statement, and play with the Database as much as you like. The Database can also be restored at any time. Our Try-SQL Editor uses WebSQL to demonstrate SQL. A Database-object is created in your browser, for testing purposes. You can try any SQL statement, and play with the Database as much as you like. The Database can be restored at any time, simply by clicking the "Restore Database" button. WebSQL stores a Database locally, on the user's computer. Each user gets their own Database object. WebSQL is supported in Chrome, Safari, Opera, and Edge(79). If you use another browser you will still be able to use our Try SQL Editor, but a different version, using a server-based ASP application, with a read-only Access Database, where users are not allowed to make any changes to the data.
[ { "code": null, "e": 67, "s": 0, "text": "SELECT Employees.LastName, COUNT(Orders.OrderID) AS NumberOfOrders" }, { "code": null, "e": 79, "s": 67, "text": "FROM Orders" }, { "code": null, "e": 144, "s": 79, "text": "INNER JOIN Employees ON Orders.EmployeeID = Employees.EmployeeID" }, { "code": null, "e": 194, "s": 144, "text": "WHERE LastName = 'Davolio' OR LastName = 'Fuller'" }, { "code": null, "e": 212, "s": 194, "text": "GROUP BY LastName" }, { "code": null, "e": 247, "s": 212, "text": "HAVING COUNT(Orders.OrderID) > 25;" }, { "code": null, "e": 249, "s": 247, "text": "​" }, { "code": null, "e": 312, "s": 249, "text": "Edit the SQL Statement, and click \"Run SQL\" to see the result." }, { "code": null, "e": 372, "s": 312, "text": "This SQL-Statement is not supported in the WebSQL Database." }, { "code": null, "e": 440, "s": 372, "text": "The example still works, because it uses a modified version of SQL." }, { "code": null, "e": 478, "s": 440, "text": "Your browser does not support WebSQL." }, { "code": null, "e": 563, "s": 478, "text": "Your are now using a light-version of the Try-SQL Editor, with a read-only Database." }, { "code": null, "e": 737, "s": 563, "text": "If you switch to a browser with WebSQL support, you can try any SQL statement, and play with the Database as much as you like. The Database can also be restored at any time." }, { "code": null, "e": 788, "s": 737, "text": "Our Try-SQL Editor uses WebSQL to demonstrate SQL." }, { "code": null, "e": 856, "s": 788, "text": "A Database-object is created in your browser, for testing purposes." }, { "code": null, "e": 1027, "s": 856, "text": "You can try any SQL statement, and play with the Database as much as you like. The Database can be restored at any time, simply by clicking the \"Restore Database\" button." }, { "code": null, "e": 1127, "s": 1027, "text": "WebSQL stores a Database locally, on the user's computer. Each user gets their own Database object." }, { "code": null, "e": 1187, "s": 1127, "text": "WebSQL is supported in Chrome, Safari, Opera, and Edge(79)." } ]
Build a Realtime Object Detection Web App in 30 Minutes | by Erdem Isbilen | Towards Data Science
Tensorflow.js is an open-source library enabling us to define, train and run machine learning models in the browser, using Javascript. I will use the Tensorflow.js framework in Angular to build a Web App that detects multiple objects on a webcam video feed. First, we have to select the pre-trained model which we are going to use for object detection. Tensorflow.js provides several pre-trained models for classification, pose estimation, speech recognition and object detection purposes. Check out all the Tensoflow.js pre-trained models for more information. COCO-SSD model, which is a pre-trained object detection model that aims to localize and identify multiple objects in an image, is the one we will use for object detection. The original ssd_mobilenet_v2_coco model size is 187.8 MB and can be downloaded from the TensorFlow model zoo. Compared to the original model, the Tensorflow.js version of the model is very lightweight and optimized for browser execution. The default object detection model for Tensorflow.js COCO-SSD is ‘lite_mobilenet_v2’ which is very small in size, under 1MB, and fastest in inference speed. If you would like better classification accuracy you can use ‘mobilenet_v2’, in this case, the size of the model increases to 75 MB, which is not suitable for the web-browser experience. ‘model.detect’ takes image or video inputs directly from HTML, so you do not need to convert the inputs into tensors before using them. It returns an array of classes, probability scores as well as bounding box coordinates for the detected objects. model.detect( img: tf.Tensor3D | ImageData | HTMLImageElement | HTMLCanvasElement | HTMLVideoElement, maxDetectionSize: number)[{ bbox: [x, y, width, height], class: "person", score: 0.8380282521247864}, { bbox: [x, y, width, height], class: "kite", score: 0.74644153267145157}] After we all clear about the model, it is time to use the Angular command-line interface to initialize the Angular web application. npm install -g @angular/cling new TFJS-ObjectDetectioncd TFJS-ObjectDetection Then I will use the NMP package manager to load Tensorflow.js and COCO-SSD library. TFJS-ObjectDetection npm install @tensorflow/tfjs --saveTFJS-ObjectDetection npm install @tensorflow-models/coco-ssd --save It is all set now. So we can start coding. I will start by importing the COCO-SSD model in ‘app.component.ts’. import { Component, OnInit } from '@angular/core';//import COCO-SSD model as cocoSSDimport * as cocoSSD from '@tensorflow-models/coco-ssd'; Then, I will start webcam feed with the following code. webcam_init(){ this.video = <HTMLVideoElement> document.getElementById("vid"); navigator.mediaDevices .getUserMedia({ audio: false, video: {facingMode: "user",} }) .then(stream => { this.video.srcObject = stream; this.video.onloadedmetadata = () => { this.video.play();}; });} We need another function to load the COCO-SSD model which also calls ‘detectFrame’ function to make the prediction using images from the webcam feed. public async predictWithCocoModel(){ const model = await cocoSSD.load('lite_mobilenet_v2'); this.detectFrame(this.video,model); } ‘detectFrame’ function uses requestAnimationFrame to loop the prediction over and over by making sure that the video feed is as much smooth as possible. detectFrame = (video, model) => { model.detect(video).then(predictions => { this.renderPredictions(predictions); requestAnimationFrame(() => { this.detectFrame(video, model);}); });} Meantime, the ‘renderPredictions’ function draws the bounding boxes and class names into the screen for detected objects. renderPredictions = predictions => {const canvas = <HTMLCanvasElement> document.getElementById ("canvas"); const ctx = canvas.getContext("2d"); canvas.width = 300; canvas.height = 300; ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height); // Fonts const font = "16px sans-serif"; ctx.font = font; ctx.textBaseline = "top"; ctx.drawImage(this.video,0,0,300,300); predictions.forEach(prediction => { // Bounding boxes's coordinates and sizes const x = prediction.bbox[0]; const y = prediction.bbox[1]; const width = prediction.bbox[2]; const height = prediction.bbox[3];// Bounding box style ctx.strokeStyle = "#00FFFF"; ctx.lineWidth = 2;// Draw the bounding ctx.strokeRect(x, y, width, height); // Label background ctx.fillStyle = "#00FFFF"; const textWidth = ctx.measureText(prediction.class).width; const textHeight = parseInt(font, 10); // base 10 ctx.fillRect(x, y, textWidth + 4, textHeight + 4); }); predictions.forEach(prediction => { // Write prediction class names const x = prediction.bbox[0]; const y = prediction.bbox[1]; ctx.fillStyle = "#000000"; ctx.fillText(prediction.class, x, y);}); }; All required functions are ready now to perform the object detection on the browser. We just need to call ‘webcam_init’ and ‘predictWithCocoModel’ on ‘ngOnInit’ to initialize the app on the start. ngOnInit(){ this.webcam_init(); this.predictWithCocoModel();} One last step remaining is to modify ‘app.component.html’ to include <video> and <canvas> HTML elements which are required for the above functions to work. <div style="text-align:center"> <h1>Tensorflow.js Real Time Object Detection</h1> <video hidden id="vid" width="300" height="300"></video> <canvas id="canvas"></canvas></div> Visit my GitHub repository for the full code of this project. Visit the live demo application to see the codes in action. The application runs in the Google Chrome browser without any issue. If you use any other browser, make sure the browser you use supports ‘requestAnimationFrame’.
[ { "code": null, "e": 430, "s": 172, "text": "Tensorflow.js is an open-source library enabling us to define, train and run machine learning models in the browser, using Javascript. I will use the Tensorflow.js framework in Angular to build a Web App that detects multiple objects on a webcam video feed." }, { "code": null, "e": 734, "s": 430, "text": "First, we have to select the pre-trained model which we are going to use for object detection. Tensorflow.js provides several pre-trained models for classification, pose estimation, speech recognition and object detection purposes. Check out all the Tensoflow.js pre-trained models for more information." }, { "code": null, "e": 906, "s": 734, "text": "COCO-SSD model, which is a pre-trained object detection model that aims to localize and identify multiple objects in an image, is the one we will use for object detection." }, { "code": null, "e": 1145, "s": 906, "text": "The original ssd_mobilenet_v2_coco model size is 187.8 MB and can be downloaded from the TensorFlow model zoo. Compared to the original model, the Tensorflow.js version of the model is very lightweight and optimized for browser execution." }, { "code": null, "e": 1489, "s": 1145, "text": "The default object detection model for Tensorflow.js COCO-SSD is ‘lite_mobilenet_v2’ which is very small in size, under 1MB, and fastest in inference speed. If you would like better classification accuracy you can use ‘mobilenet_v2’, in this case, the size of the model increases to 75 MB, which is not suitable for the web-browser experience." }, { "code": null, "e": 1738, "s": 1489, "text": "‘model.detect’ takes image or video inputs directly from HTML, so you do not need to convert the inputs into tensors before using them. It returns an array of classes, probability scores as well as bounding box coordinates for the detected objects." }, { "code": null, "e": 2019, "s": 1738, "text": "model.detect( img: tf.Tensor3D | ImageData | HTMLImageElement | HTMLCanvasElement | HTMLVideoElement, maxDetectionSize: number)[{ bbox: [x, y, width, height], class: \"person\", score: 0.8380282521247864}, { bbox: [x, y, width, height], class: \"kite\", score: 0.74644153267145157}]" }, { "code": null, "e": 2151, "s": 2019, "text": "After we all clear about the model, it is time to use the Angular command-line interface to initialize the Angular web application." }, { "code": null, "e": 2229, "s": 2151, "text": "npm install -g @angular/cling new TFJS-ObjectDetectioncd TFJS-ObjectDetection" }, { "code": null, "e": 2313, "s": 2229, "text": "Then I will use the NMP package manager to load Tensorflow.js and COCO-SSD library." }, { "code": null, "e": 2437, "s": 2313, "text": "TFJS-ObjectDetection npm install @tensorflow/tfjs --saveTFJS-ObjectDetection npm install @tensorflow-models/coco-ssd --save" }, { "code": null, "e": 2548, "s": 2437, "text": "It is all set now. So we can start coding. I will start by importing the COCO-SSD model in ‘app.component.ts’." }, { "code": null, "e": 2688, "s": 2548, "text": "import { Component, OnInit } from '@angular/core';//import COCO-SSD model as cocoSSDimport * as cocoSSD from '@tensorflow-models/coco-ssd';" }, { "code": null, "e": 2744, "s": 2688, "text": "Then, I will start webcam feed with the following code." }, { "code": null, "e": 3032, "s": 2744, "text": "webcam_init(){ this.video = <HTMLVideoElement> document.getElementById(\"vid\"); navigator.mediaDevices .getUserMedia({ audio: false, video: {facingMode: \"user\",} }) .then(stream => { this.video.srcObject = stream; this.video.onloadedmetadata = () => { this.video.play();}; });}" }, { "code": null, "e": 3182, "s": 3032, "text": "We need another function to load the COCO-SSD model which also calls ‘detectFrame’ function to make the prediction using images from the webcam feed." }, { "code": null, "e": 3315, "s": 3182, "text": "public async predictWithCocoModel(){ const model = await cocoSSD.load('lite_mobilenet_v2'); this.detectFrame(this.video,model); }" }, { "code": null, "e": 3468, "s": 3315, "text": "‘detectFrame’ function uses requestAnimationFrame to loop the prediction over and over by making sure that the video feed is as much smooth as possible." }, { "code": null, "e": 3656, "s": 3468, "text": "detectFrame = (video, model) => { model.detect(video).then(predictions => { this.renderPredictions(predictions); requestAnimationFrame(() => { this.detectFrame(video, model);}); });}" }, { "code": null, "e": 3778, "s": 3656, "text": "Meantime, the ‘renderPredictions’ function draws the bounding boxes and class names into the screen for detected objects." }, { "code": null, "e": 4977, "s": 3778, "text": "renderPredictions = predictions => {const canvas = <HTMLCanvasElement> document.getElementById (\"canvas\"); const ctx = canvas.getContext(\"2d\"); canvas.width = 300; canvas.height = 300; ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height); // Fonts const font = \"16px sans-serif\"; ctx.font = font; ctx.textBaseline = \"top\"; ctx.drawImage(this.video,0,0,300,300); predictions.forEach(prediction => { // Bounding boxes's coordinates and sizes const x = prediction.bbox[0]; const y = prediction.bbox[1]; const width = prediction.bbox[2]; const height = prediction.bbox[3];// Bounding box style ctx.strokeStyle = \"#00FFFF\"; ctx.lineWidth = 2;// Draw the bounding ctx.strokeRect(x, y, width, height); // Label background ctx.fillStyle = \"#00FFFF\"; const textWidth = ctx.measureText(prediction.class).width; const textHeight = parseInt(font, 10); // base 10 ctx.fillRect(x, y, textWidth + 4, textHeight + 4); }); predictions.forEach(prediction => { // Write prediction class names const x = prediction.bbox[0]; const y = prediction.bbox[1]; ctx.fillStyle = \"#000000\"; ctx.fillText(prediction.class, x, y);}); };" }, { "code": null, "e": 5062, "s": 4977, "text": "All required functions are ready now to perform the object detection on the browser." }, { "code": null, "e": 5174, "s": 5062, "text": "We just need to call ‘webcam_init’ and ‘predictWithCocoModel’ on ‘ngOnInit’ to initialize the app on the start." }, { "code": null, "e": 5238, "s": 5174, "text": "ngOnInit(){ this.webcam_init(); this.predictWithCocoModel();}" }, { "code": null, "e": 5394, "s": 5238, "text": "One last step remaining is to modify ‘app.component.html’ to include <video> and <canvas> HTML elements which are required for the above functions to work." }, { "code": null, "e": 5572, "s": 5394, "text": "<div style=\"text-align:center\"> <h1>Tensorflow.js Real Time Object Detection</h1> <video hidden id=\"vid\" width=\"300\" height=\"300\"></video> <canvas id=\"canvas\"></canvas></div>" }, { "code": null, "e": 5634, "s": 5572, "text": "Visit my GitHub repository for the full code of this project." } ]
CICS - READ
READ command reads data from a file using primary key. Following is the syntax of the READ command − EXEC CICS READ FILE('name') INTO(data-area) RIDFLD(data-area) LENGTH(data-value) KEYLENGTH(data-value) END-EXEC. The following table lists the parameters used in the READ command − FILE File name is the name of the file which we want to read. This is the CICS symbolic file name which identifies the FCT entry for the file. File names can be up to 8 characters long and should be enclosed in quotes if they are literals. INTO Data area is the variable into which the record is to be read, usually a structure in working storage. The INTO is required for the uses of the READ command. RIDFLD It has the name of the data area containing the key of the record which we want to read. LENGTH It specifies the maximum number of characters that may be read into the data area specified. It must be a halfword binary value (PIC S9(4) COMP). After the READ command is completed, CICS replaces the maximum value we specify with the true length of the record. For this reason, we must specify LENGTH as the name of a data area rather than a literal and must re-initialize this data area if we use it for LENGTH more than once in the program. An longer record will raise an error condition. KEYLENGTH It specifies the length of the key. The following example shows how to read a record from 'FL001' file where Student-id is the primary key − IDENTIFICATION DIVISION. PROGRAM-ID. HELLO. DATA DIVISION. WORKING-STORAGE SECTION. 01 WS-STD-REC-LEN PIC S9(4) COMP. 01 WS-STD-KEY-LEN PIC S9(4) COMP. 01 WS-STD-REC-KEY PIC 9(3). 01 WS-STD-REC PIC X(70). PROCEDURE DIVISION. MOVE +70 TO WS-STD-REC-LEN. MOVE ‘100’ TO WS-STD-REC-KEY. MOVE 3 TO WS-STD-KEY-LEN. EXEC CICS READ FILE ('FL001') INTO (WS-STD-REC) LENGTH (WS-STD-REC-LEN) RIDFLD (WS-STD-REC-KEY) KEYLENGTH (WS-STD-KEY-LEN) END-EXEC. Following options can be used with READ command − GENERIC − It is used when we do not know the complete key value. For example, we want a record whose primary key starts with ‘10’ and the rest of the key can be anything. Although the key length is 3 characters, we are mentioning only 2. It is important to mention the key-length which gives the length for which it needs to do the matching. The first record that satisfies the criteria will get picked up. GENERIC − It is used when we do not know the complete key value. For example, we want a record whose primary key starts with ‘10’ and the rest of the key can be anything. Although the key length is 3 characters, we are mentioning only 2. It is important to mention the key-length which gives the length for which it needs to do the matching. The first record that satisfies the criteria will get picked up. UPDATE − It specifies that we intend to update the record in the current transaction. Specifying UPDATE gives your transaction exclusive control of the requested record. It should be used when we want to rewrite the record. UPDATE − It specifies that we intend to update the record in the current transaction. Specifying UPDATE gives your transaction exclusive control of the requested record. It should be used when we want to rewrite the record. EQUAL − It specifies that we want only the record whose key exactly matches with what is specified by RIDFLD. EQUAL − It specifies that we want only the record whose key exactly matches with what is specified by RIDFLD. GTEQ − It specifies that we want the first record whose key is greater than or equal to the key specified. GTEQ − It specifies that we want the first record whose key is greater than or equal to the key specified. EXEC CICS READ FILE('name') INTO(data-area) RIDFLD(data-area) LENGTH(data-value) KEYLENGTH(data-value) GENERIC UPDATE EQUAL GTEQ END-EXEC. The following table shows the list of exceptions that arise during READ statement − NOTOPEN File is not open. NOTFND Record that is being searched does not exist in the dataset. FILENOTFOUND File entry is not made in FCT. LENGERR Mismatch between the length specified in command and actual length of the record. NOTAUTH If the user does not have enough permissions to use the file. DUPKEY If more than 1 record satisfy the condition on the alternate key. Print Add Notes Bookmark this page
[ { "code": null, "e": 2027, "s": 1926, "text": "READ command reads data from a file using primary key. Following is the syntax of the READ command −" }, { "code": null, "e": 2156, "s": 2027, "text": "EXEC CICS READ\n FILE('name')\n INTO(data-area)\n RIDFLD(data-area)\n LENGTH(data-value)\n KEYLENGTH(data-value)\nEND-EXEC.\n" }, { "code": null, "e": 2224, "s": 2156, "text": "The following table lists the parameters used in the READ command −" }, { "code": null, "e": 2229, "s": 2224, "text": "FILE" }, { "code": null, "e": 2464, "s": 2229, "text": "File name is the name of the file which we want to read. This is the CICS symbolic file name which identifies the FCT entry for the file. File names can be up to 8 characters long and should be enclosed in quotes if they are literals." }, { "code": null, "e": 2469, "s": 2464, "text": "INTO" }, { "code": null, "e": 2627, "s": 2469, "text": "Data area is the variable into which the record is to be read, usually a structure in working storage. The INTO is required for the uses of the READ command." }, { "code": null, "e": 2634, "s": 2627, "text": "RIDFLD" }, { "code": null, "e": 2723, "s": 2634, "text": "It has the name of the data area containing the key of the record which we want to read." }, { "code": null, "e": 2730, "s": 2723, "text": "LENGTH" }, { "code": null, "e": 3222, "s": 2730, "text": "It specifies the maximum number of characters that may be read into the data area specified. It must be a halfword binary value (PIC S9(4) COMP). After the READ command is completed, CICS replaces the maximum value we specify with the true length of the record. For this reason, we must specify LENGTH as the name of a data area rather than a literal and must re-initialize this data area if we use it for LENGTH more than once in the program. An longer record will raise an error condition." }, { "code": null, "e": 3232, "s": 3222, "text": "KEYLENGTH" }, { "code": null, "e": 3268, "s": 3232, "text": "It specifies the length of the key." }, { "code": null, "e": 3373, "s": 3268, "text": "The following example shows how to read a record from 'FL001' file where Student-id is the primary key −" }, { "code": null, "e": 3965, "s": 3373, "text": "IDENTIFICATION DIVISION. \nPROGRAM-ID. HELLO. \nDATA DIVISION. \nWORKING-STORAGE SECTION.\n01 WS-STD-REC-LEN PIC S9(4) COMP.\n01 WS-STD-KEY-LEN PIC S9(4) COMP.\n01 WS-STD-REC-KEY PIC 9(3).\n01 WS-STD-REC PIC X(70).\nPROCEDURE DIVISION.\nMOVE +70 TO WS-STD-REC-LEN.\nMOVE ‘100’ TO WS-STD-REC-KEY.\nMOVE 3 TO WS-STD-KEY-LEN.\nEXEC CICS READ\n FILE ('FL001')\n INTO (WS-STD-REC)\n LENGTH (WS-STD-REC-LEN)\n RIDFLD (WS-STD-REC-KEY)\n KEYLENGTH (WS-STD-KEY-LEN)\nEND-EXEC." }, { "code": null, "e": 4015, "s": 3965, "text": "Following options can be used with READ command −" }, { "code": null, "e": 4422, "s": 4015, "text": "GENERIC − It is used when we do not know the complete key value. For example, we want a record whose primary key starts with ‘10’ and the rest of the key can be anything. Although the key length is 3 characters, we are mentioning only 2. It is important to mention the key-length which gives the length for which it needs to do the matching. The first record that satisfies the criteria will get picked up." }, { "code": null, "e": 4829, "s": 4422, "text": "GENERIC − It is used when we do not know the complete key value. For example, we want a record whose primary key starts with ‘10’ and the rest of the key can be anything. Although the key length is 3 characters, we are mentioning only 2. It is important to mention the key-length which gives the length for which it needs to do the matching. The first record that satisfies the criteria will get picked up." }, { "code": null, "e": 5053, "s": 4829, "text": "UPDATE − It specifies that we intend to update the record in the current transaction. Specifying UPDATE gives your transaction exclusive control of the requested record. It should be used when we want to rewrite the record." }, { "code": null, "e": 5277, "s": 5053, "text": "UPDATE − It specifies that we intend to update the record in the current transaction. Specifying UPDATE gives your transaction exclusive control of the requested record. It should be used when we want to rewrite the record." }, { "code": null, "e": 5387, "s": 5277, "text": "EQUAL − It specifies that we want only the record whose key exactly matches with what is specified by RIDFLD." }, { "code": null, "e": 5497, "s": 5387, "text": "EQUAL − It specifies that we want only the record whose key exactly matches with what is specified by RIDFLD." }, { "code": null, "e": 5604, "s": 5497, "text": "GTEQ − It specifies that we want the first record whose key is greater than or equal to the key specified." }, { "code": null, "e": 5711, "s": 5604, "text": "GTEQ − It specifies that we want the first record whose key is greater than or equal to the key specified." }, { "code": null, "e": 5878, "s": 5711, "text": "EXEC CICS READ\n FILE('name')\n INTO(data-area)\n RIDFLD(data-area)\n LENGTH(data-value)\n KEYLENGTH(data-value)\n GENERIC\n UPDATE\n EQUAL\n GTEQ\nEND-EXEC.\n" }, { "code": null, "e": 5962, "s": 5878, "text": "The following table shows the list of exceptions that arise during READ statement −" }, { "code": null, "e": 5970, "s": 5962, "text": "NOTOPEN" }, { "code": null, "e": 5988, "s": 5970, "text": "File is not open." }, { "code": null, "e": 5995, "s": 5988, "text": "NOTFND" }, { "code": null, "e": 6056, "s": 5995, "text": "Record that is being searched does not exist in the dataset." }, { "code": null, "e": 6069, "s": 6056, "text": "FILENOTFOUND" }, { "code": null, "e": 6100, "s": 6069, "text": "File entry is not made in FCT." }, { "code": null, "e": 6108, "s": 6100, "text": "LENGERR" }, { "code": null, "e": 6190, "s": 6108, "text": "Mismatch between the length specified in command and actual length of the record." }, { "code": null, "e": 6198, "s": 6190, "text": "NOTAUTH" }, { "code": null, "e": 6260, "s": 6198, "text": "If the user does not have enough permissions to use the file." }, { "code": null, "e": 6267, "s": 6260, "text": "DUPKEY" }, { "code": null, "e": 6333, "s": 6267, "text": "If more than 1 record satisfy the condition on the alternate key." }, { "code": null, "e": 6340, "s": 6333, "text": " Print" }, { "code": null, "e": 6351, "s": 6340, "text": " Add Notes" } ]
Java try Keyword
❮ Java Keywords If an error occur, use try...catch to catch the error and execute some code to handle it: try { int[] myNumbers = {1, 2, 3}; System.out.println(myNumbers[10]); } catch (Exception e) { System.out.println("Something went wrong."); } Try it Yourself » The try keyword creates a try...catch statement. The try statement allows you to define a block of code to be tested for errors while it is being executed. The catch statement allows you to define a block of code to be executed, if an error occurs in the try block. Read more about exceptions in our Java Try..Catch Tutorial. ❮ Java Keywords We just launchedW3Schools videos Get certifiedby completinga course today! If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail: help@w3schools.com Your message has been sent to W3Schools.
[ { "code": null, "e": 18, "s": 0, "text": "\n❮ Java Keywords\n" }, { "code": null, "e": 108, "s": 18, "text": "If an error occur, use try...catch to catch the error and execute some code to handle it:" }, { "code": null, "e": 256, "s": 108, "text": "try {\n int[] myNumbers = {1, 2, 3};\n System.out.println(myNumbers[10]);\n} catch (Exception e) {\n System.out.println(\"Something went wrong.\");\n}\n" }, { "code": null, "e": 276, "s": 256, "text": "\nTry it Yourself »\n" }, { "code": null, "e": 325, "s": 276, "text": "The try keyword creates a try...catch statement." }, { "code": null, "e": 433, "s": 325, "text": "The try statement allows you to define a block of code to be \ntested for errors while it is being executed." }, { "code": null, "e": 544, "s": 433, "text": "The catch statement allows you to define a block of code to \nbe executed, if an error occurs in the try block." }, { "code": null, "e": 604, "s": 544, "text": "Read more about exceptions in our Java Try..Catch Tutorial." }, { "code": null, "e": 622, "s": 604, "text": "\n❮ Java Keywords\n" }, { "code": null, "e": 655, "s": 622, "text": "We just launchedW3Schools videos" }, { "code": null, "e": 697, "s": 655, "text": "Get certifiedby completinga course today!" }, { "code": null, "e": 804, "s": 697, "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": 823, "s": 804, "text": "help@w3schools.com" } ]
PHP | intdiv() Function - GeeksforGeeks
09 Mar, 2018 intdiv stands for integer division. This function returns the integer quotient of the division of the given dividend and divisor. This function internally removes the remainder from the dividend to make it evenly divisible by the divisor and returns the quotient after division. Syntax: int intdiv($dividend, $divisor) Parameters: The function takes two parameters as follows: $dividend: This signed integer parameter refers to the number to be divided. $divisor: This signed integer parameter refers to the number to be used as the divisor. Return Type: This function returns the quotient calculated. Examples: Input : $dividend = 5, $divisor = 2 Output : 2 Input : $dividend = -11, $divisor = 2 Output : -5 Exception/Error:: The function raises exception in following cases: If we pass the divisor as 0, then the function raises DivisionByZeroError exception. If we pass PHP_INT_MIN as the dividend and -1 as the divisor, then an ArithmeticError exception is thrown.Below program illustrates the working of intdiv in PHP:<?php // PHP code to illustrate the working // of intdiv() Functions $dividend = 19;$divisor = 3; echo intdiv($dividend, $divisor); ?>Output:6 After Seeing so far many may think that this function is equivalent tofloor($dividend/$divisor)but the example will elaborate the difference.<?php // PHP code to differentiate between // intdiv() and floor() $dividend = -19;$divisor = 3; echo intdiv($dividend, $divisor) ."\n". floor($dividend/ $divisor); ?>Output:-6 -7 Important points to note:intdiv() Function returns the quotient of integer division.The function may raise exceptions thus the developer has to tackle edge cases.The function is not equivalent to the floor function applied to the float division or ‘/’.Reference:http://php.net/manual/en/function.intdiv.phpMy Personal Notes arrow_drop_upSave Below program illustrates the working of intdiv in PHP: <?php // PHP code to illustrate the working // of intdiv() Functions $dividend = 19;$divisor = 3; echo intdiv($dividend, $divisor); ?> Output: 6 After Seeing so far many may think that this function is equivalent to floor($dividend/$divisor) but the example will elaborate the difference. <?php // PHP code to differentiate between // intdiv() and floor() $dividend = -19;$divisor = 3; echo intdiv($dividend, $divisor) ."\n". floor($dividend/ $divisor); ?> Output: -6 -7 Important points to note: intdiv() Function returns the quotient of integer division. The function may raise exceptions thus the developer has to tackle edge cases. The function is not equivalent to the floor function applied to the float division or ‘/’. Reference:http://php.net/manual/en/function.intdiv.php PHP-function PHP-math PHP Web Technologies PHP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Insert Form Data into Database using PHP ? How to convert array to string in PHP ? How to Upload Image into Database and Display it using PHP ? How to check whether an array is empty using PHP? PHP | Converting string to Date and DateTime 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": 26057, "s": 26029, "text": "\n09 Mar, 2018" }, { "code": null, "e": 26336, "s": 26057, "text": "intdiv stands for integer division. This function returns the integer quotient of the division of the given dividend and divisor. This function internally removes the remainder from the dividend to make it evenly divisible by the divisor and returns the quotient after division." }, { "code": null, "e": 26344, "s": 26336, "text": "Syntax:" }, { "code": null, "e": 26377, "s": 26344, "text": "int intdiv($dividend, $divisor)\n" }, { "code": null, "e": 26435, "s": 26377, "text": "Parameters: The function takes two parameters as follows:" }, { "code": null, "e": 26512, "s": 26435, "text": "$dividend: This signed integer parameter refers to the number to be divided." }, { "code": null, "e": 26600, "s": 26512, "text": "$divisor: This signed integer parameter refers to the number to be used as the divisor." }, { "code": null, "e": 26660, "s": 26600, "text": "Return Type: This function returns the quotient calculated." }, { "code": null, "e": 26670, "s": 26660, "text": "Examples:" }, { "code": null, "e": 26778, "s": 26670, "text": "Input : $dividend = 5, $divisor = 2\nOutput : 2\n\nInput : $dividend = -11, $divisor = 2\nOutput : -5 \n" }, { "code": null, "e": 26846, "s": 26778, "text": "Exception/Error:: The function raises exception in following cases:" }, { "code": null, "e": 26931, "s": 26846, "text": "If we pass the divisor as 0, then the function raises DivisionByZeroError exception." }, { "code": null, "e": 27923, "s": 26931, "text": "If we pass PHP_INT_MIN as the dividend and -1 as the divisor, then an ArithmeticError exception is thrown.Below program illustrates the working of intdiv in PHP:<?php // PHP code to illustrate the working // of intdiv() Functions $dividend = 19;$divisor = 3; echo intdiv($dividend, $divisor); ?>Output:6\nAfter Seeing so far many may think that this function is equivalent tofloor($dividend/$divisor)but the example will elaborate the difference.<?php // PHP code to differentiate between // intdiv() and floor() $dividend = -19;$divisor = 3; echo intdiv($dividend, $divisor) .\"\\n\". floor($dividend/ $divisor); ?>Output:-6\n-7\nImportant points to note:intdiv() Function returns the quotient of integer division.The function may raise exceptions thus the developer has to tackle edge cases.The function is not equivalent to the floor function applied to the float division or ‘/’.Reference:http://php.net/manual/en/function.intdiv.phpMy Personal Notes\narrow_drop_upSave" }, { "code": null, "e": 27979, "s": 27923, "text": "Below program illustrates the working of intdiv in PHP:" }, { "code": "<?php // PHP code to illustrate the working // of intdiv() Functions $dividend = 19;$divisor = 3; echo intdiv($dividend, $divisor); ?>", "e": 28120, "s": 27979, "text": null }, { "code": null, "e": 28128, "s": 28120, "text": "Output:" }, { "code": null, "e": 28131, "s": 28128, "text": "6\n" }, { "code": null, "e": 28202, "s": 28131, "text": "After Seeing so far many may think that this function is equivalent to" }, { "code": null, "e": 28228, "s": 28202, "text": "floor($dividend/$divisor)" }, { "code": null, "e": 28275, "s": 28228, "text": "but the example will elaborate the difference." }, { "code": "<?php // PHP code to differentiate between // intdiv() and floor() $dividend = -19;$divisor = 3; echo intdiv($dividend, $divisor) .\"\\n\". floor($dividend/ $divisor); ?>", "e": 28462, "s": 28275, "text": null }, { "code": null, "e": 28470, "s": 28462, "text": "Output:" }, { "code": null, "e": 28477, "s": 28470, "text": "-6\n-7\n" }, { "code": null, "e": 28503, "s": 28477, "text": "Important points to note:" }, { "code": null, "e": 28563, "s": 28503, "text": "intdiv() Function returns the quotient of integer division." }, { "code": null, "e": 28642, "s": 28563, "text": "The function may raise exceptions thus the developer has to tackle edge cases." }, { "code": null, "e": 28733, "s": 28642, "text": "The function is not equivalent to the floor function applied to the float division or ‘/’." }, { "code": null, "e": 28788, "s": 28733, "text": "Reference:http://php.net/manual/en/function.intdiv.php" }, { "code": null, "e": 28801, "s": 28788, "text": "PHP-function" }, { "code": null, "e": 28810, "s": 28801, "text": "PHP-math" }, { "code": null, "e": 28814, "s": 28810, "text": "PHP" }, { "code": null, "e": 28831, "s": 28814, "text": "Web Technologies" }, { "code": null, "e": 28835, "s": 28831, "text": "PHP" }, { "code": null, "e": 28933, "s": 28835, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28983, "s": 28933, "text": "How to Insert Form Data into Database using PHP ?" }, { "code": null, "e": 29023, "s": 28983, "text": "How to convert array to string in PHP ?" }, { "code": null, "e": 29084, "s": 29023, "text": "How to Upload Image into Database and Display it using PHP ?" }, { "code": null, "e": 29134, "s": 29084, "text": "How to check whether an array is empty using PHP?" }, { "code": null, "e": 29179, "s": 29134, "text": "PHP | Converting string to Date and DateTime" }, { "code": null, "e": 29219, "s": 29179, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 29252, "s": 29219, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 29297, "s": 29252, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 29340, "s": 29297, "text": "How to fetch data from an API in ReactJS ?" } ]
PyQt5 - How to get percentage of Progress Bar ? - GeeksforGeeks
22 Apr, 2020 In this article we will see how to get the percentage value of progress bar, we can set the percentage of progress bar using setValue method. In order to get the percentage value we use text method which will return the integer that indicates the percentage. Syntax : bar.text() Argument : It takes no argument. Return : It return integer. Below is the implementation. # importing librariesfrom PyQt5.QtWidgets import * from PyQt5 import QtCore, QtGuifrom PyQt5.QtGui import * from PyQt5.QtCore import * import sys class Window(QMainWindow): def __init__(self): super().__init__() # setting title self.setWindowTitle("Python ") # setting geometry self.setGeometry(100, 100, 600, 400) # calling method self.UiComponents() # showing all the widgets self.show() # method for widgets def UiComponents(self): # creating progress bar bar = QProgressBar(self) # setting geometry to progress bar bar.setGeometry(200, 150, 200, 30) # set value to progress bar bar.setValue(70) # getting percentage value p_value = bar.text() # creating label to print percentage label = QLabel("percentage = " + str(p_value), self) # moving the label label.move(200, 200) # setting alignment to centre bar.setAlignment(Qt.AlignCenter) # create pyqt5 appApp = QApplication(sys.argv) # create the instance of our Windowwindow = Window() # start the appsys.exit(App.exec()) Output : Python-gui Python-PyQt Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary How to Install PIP on Windows ? Read a file line by line in Python Enumerate() in Python Different ways to create Pandas Dataframe Iterate over a list in Python Python String | replace() Reading and Writing to text files in Python *args and **kwargs in Python Convert integer to string in Python
[ { "code": null, "e": 25753, "s": 25725, "text": "\n22 Apr, 2020" }, { "code": null, "e": 26012, "s": 25753, "text": "In this article we will see how to get the percentage value of progress bar, we can set the percentage of progress bar using setValue method. In order to get the percentage value we use text method which will return the integer that indicates the percentage." }, { "code": null, "e": 26032, "s": 26012, "text": "Syntax : bar.text()" }, { "code": null, "e": 26065, "s": 26032, "text": "Argument : It takes no argument." }, { "code": null, "e": 26093, "s": 26065, "text": "Return : It return integer." }, { "code": null, "e": 26122, "s": 26093, "text": "Below is the implementation." }, { "code": "# importing librariesfrom PyQt5.QtWidgets import * from PyQt5 import QtCore, QtGuifrom PyQt5.QtGui import * from PyQt5.QtCore import * import sys class Window(QMainWindow): def __init__(self): super().__init__() # setting title self.setWindowTitle(\"Python \") # setting geometry self.setGeometry(100, 100, 600, 400) # calling method self.UiComponents() # showing all the widgets self.show() # method for widgets def UiComponents(self): # creating progress bar bar = QProgressBar(self) # setting geometry to progress bar bar.setGeometry(200, 150, 200, 30) # set value to progress bar bar.setValue(70) # getting percentage value p_value = bar.text() # creating label to print percentage label = QLabel(\"percentage = \" + str(p_value), self) # moving the label label.move(200, 200) # setting alignment to centre bar.setAlignment(Qt.AlignCenter) # create pyqt5 appApp = QApplication(sys.argv) # create the instance of our Windowwindow = Window() # start the appsys.exit(App.exec())", "e": 27304, "s": 26122, "text": null }, { "code": null, "e": 27313, "s": 27304, "text": "Output :" }, { "code": null, "e": 27324, "s": 27313, "text": "Python-gui" }, { "code": null, "e": 27336, "s": 27324, "text": "Python-PyQt" }, { "code": null, "e": 27343, "s": 27336, "text": "Python" }, { "code": null, "e": 27441, "s": 27343, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27459, "s": 27441, "text": "Python Dictionary" }, { "code": null, "e": 27491, "s": 27459, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 27526, "s": 27491, "text": "Read a file line by line in Python" }, { "code": null, "e": 27548, "s": 27526, "text": "Enumerate() in Python" }, { "code": null, "e": 27590, "s": 27548, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 27620, "s": 27590, "text": "Iterate over a list in Python" }, { "code": null, "e": 27646, "s": 27620, "text": "Python String | replace()" }, { "code": null, "e": 27690, "s": 27646, "text": "Reading and Writing to text files in Python" }, { "code": null, "e": 27719, "s": 27690, "text": "*args and **kwargs in Python" } ]
Pair formation such that maximum pair sum is minimized - GeeksforGeeks
05 Apr, 2021 Given an array of size 2 * N integers. Divide the array into N pairs, such that the maximum pair sum is minimized. In other words, the optimal division of array into N pairs should result into a maximum pair sum which is minimum of other maximum pair sum of all possibilities.Examples: Input : N = 2 arr[] = { 5, 8, 3, 9 } Output : (3, 9) (5, 8) Explanation: Possible pairs are : 1. (8, 9) (3, 5) Maximum Sum of a Pair = 17 2. (5, 9) (3, 8) Maximum Sum of a Pair = 14 3. (3, 9) (5, 8) Maximum Sum of a Pair = 13 Thus, in case 3, the maximum pair sum is minimum of all the other cases. Hence, the answer is(3, 9) (5, 8).Input : N = 2 arr[] = { 9, 6, 5, 1 } Output : (1, 9) (5, 6) Approach: The idea is to first sort the given array and then iterate over the loop to form pairs (i, j) where i would start from 0 and j would start from end of array correspondingly. Increment i and Decrement j to form the next pair and so on.Below is the implementation of above approach. C++ Java Python3 C# PHP Javascript // CPP Program to divide the array into// N pairs such that maximum pair is minimized#include <bits/stdc++.h> using namespace std; void findOptimalPairs(int arr[], int N){ sort(arr, arr + N); // After Sorting Maintain two variables i and j // pointing to start and end of array Such that // smallest element of array pairs with largest // element for (int i = 0, j = N - 1; i <= j; i++, j--) cout << "(" << arr[i] << ", " << arr[j] << ")" << " ";} // Driver Codeint main(){ int arr[] = { 9, 6, 5, 1 }; int N = sizeof(arr) / sizeof(arr[0]); findOptimalPairs(arr, N); return 0;} // Java Program to divide the array into// N pairs such that maximum pair is minimizedimport java.io.*;import java.util.Arrays; class GFG { static void findOptimalPairs(int arr[], int N){ Arrays.sort(arr); // After Sorting Maintain two variables i and j // pointing to start and end of array Such that // smallest element of array pairs with largest // element for (int i = 0, j = N - 1; i <= j; i++, j--) System.out.print( "(" + arr[i] + ", " + arr[j] + ")" + " ");} // Driver Code public static void main (String[] args) { int arr[] = {9, 6, 5, 1}; int N = arr.length; findOptimalPairs(arr, N); }} // This code is contributed by anuj_67. # Python 3 Program to divide the array into# N pairs such that maximum pair is minimized def findOptimalPairs(arr, N): arr.sort(reverse = False) # After Sorting Maintain two variables # i and j pointing to start and end of # array Such that smallest element of # array pairs with largest element i = 0 j = N - 1 while(i <= j): print("(", arr[i], ",", arr[j], ")", end = " ") i += 1 j -= 1 # Driver Codeif __name__ == '__main__': arr = [9, 6, 5, 1] N = len(arr) findOptimalPairs(arr, N) # This code is contributed by# Sahil_Shelangia // C# Program to divide the array into// N pairs such that maximum pair is minimized using System; public class GFG{ static void findOptimalPairs(int []arr, int N){ Array.Sort(arr); // After Sorting Maintain two variables i and j // pointing to start and end of array Such that // smallest element of array pairs with largest // element for (int i = 0, j = N - 1; i <= j; i++, j--) Console.Write( "(" + arr[i] + ", " + arr[j] + ")" + " ");} // Driver Code static public void Main (){ int []arr = {9, 6, 5, 1}; int N = arr.Length; findOptimalPairs(arr, N); // This code is contributed by ajit. }} <?php// PHP Program to divide the array into// N pairs such that maximum pair is minimized function findOptimalPairs($arr, $N){ sort($arr); // After Sorting Maintain two variables // i and j pointing to start and end of // array Such that smallest element of // array pairs with largest element for ($i = 0, $j = $N - 1; $i <= $j; $i++, $j--) echo "(", $arr[$i], ", ", $arr[$j], ")", " ";} // Driver Code$arr = array( 9, 6, 5, 1 );$N = sizeof($arr); findOptimalPairs($arr, $N); // This code is contributed by jit_t?> <script> /// Javascript Program to divide the array into// N pairs such that maximum pair is minimizedfunction findOptimalPairs(arr, N){ arr.sort(function(a,b){ return a-b;}); // After Sorting Maintain two variables i and j // pointing to start and end of array Such that // smallest element of array pairs with largest // element for (var i = 0, j = N - 1; i <= j; i++, j--) document.write("(" + arr[i] + ", " + arr[j] + ")" + " ");} // Driver Codevar arr = [ 9, 6, 5, 1 ];var N = arr.length;findOptimalPairs(arr, N); </script> (1, 9) (5, 6) vt_m jit_t sahilshelangia rrrtnx Sorting Quiz Arrays Greedy Sorting Arrays Greedy Sorting Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Chocolate Distribution Problem Count pairs with given sum Window Sliding Technique Reversal algorithm for array rotation Next Greater Element Dijkstra's shortest path algorithm | Greedy Algo-7 Prim’s Minimum Spanning Tree (MST) | Greedy Algo-5 Kruskal’s Minimum Spanning Tree Algorithm | Greedy Algo-2 Write a program to print all permutations of a given string Huffman Coding | Greedy Algo-3
[ { "code": null, "e": 26066, "s": 26038, "text": "\n05 Apr, 2021" }, { "code": null, "e": 26354, "s": 26066, "text": "Given an array of size 2 * N integers. Divide the array into N pairs, such that the maximum pair sum is minimized. In other words, the optimal division of array into N pairs should result into a maximum pair sum which is minimum of other maximum pair sum of all possibilities.Examples: " }, { "code": null, "e": 26749, "s": 26354, "text": "Input : N = 2 arr[] = { 5, 8, 3, 9 } Output : (3, 9) (5, 8) Explanation: Possible pairs are : 1. (8, 9) (3, 5) Maximum Sum of a Pair = 17 2. (5, 9) (3, 8) Maximum Sum of a Pair = 14 3. (3, 9) (5, 8) Maximum Sum of a Pair = 13 Thus, in case 3, the maximum pair sum is minimum of all the other cases. Hence, the answer is(3, 9) (5, 8).Input : N = 2 arr[] = { 9, 6, 5, 1 } Output : (1, 9) (5, 6) " }, { "code": null, "e": 27044, "s": 26751, "text": "Approach: The idea is to first sort the given array and then iterate over the loop to form pairs (i, j) where i would start from 0 and j would start from end of array correspondingly. Increment i and Decrement j to form the next pair and so on.Below is the implementation of above approach. " }, { "code": null, "e": 27048, "s": 27044, "text": "C++" }, { "code": null, "e": 27053, "s": 27048, "text": "Java" }, { "code": null, "e": 27061, "s": 27053, "text": "Python3" }, { "code": null, "e": 27064, "s": 27061, "text": "C#" }, { "code": null, "e": 27068, "s": 27064, "text": "PHP" }, { "code": null, "e": 27079, "s": 27068, "text": "Javascript" }, { "code": "// CPP Program to divide the array into// N pairs such that maximum pair is minimized#include <bits/stdc++.h> using namespace std; void findOptimalPairs(int arr[], int N){ sort(arr, arr + N); // After Sorting Maintain two variables i and j // pointing to start and end of array Such that // smallest element of array pairs with largest // element for (int i = 0, j = N - 1; i <= j; i++, j--) cout << \"(\" << arr[i] << \", \" << arr[j] << \")\" << \" \";} // Driver Codeint main(){ int arr[] = { 9, 6, 5, 1 }; int N = sizeof(arr) / sizeof(arr[0]); findOptimalPairs(arr, N); return 0;}", "e": 27695, "s": 27079, "text": null }, { "code": "// Java Program to divide the array into// N pairs such that maximum pair is minimizedimport java.io.*;import java.util.Arrays; class GFG { static void findOptimalPairs(int arr[], int N){ Arrays.sort(arr); // After Sorting Maintain two variables i and j // pointing to start and end of array Such that // smallest element of array pairs with largest // element for (int i = 0, j = N - 1; i <= j; i++, j--) System.out.print( \"(\" + arr[i] + \", \" + arr[j] + \")\" + \" \");} // Driver Code public static void main (String[] args) { int arr[] = {9, 6, 5, 1}; int N = arr.length; findOptimalPairs(arr, N); }} // This code is contributed by anuj_67.", "e": 28400, "s": 27695, "text": null }, { "code": "# Python 3 Program to divide the array into# N pairs such that maximum pair is minimized def findOptimalPairs(arr, N): arr.sort(reverse = False) # After Sorting Maintain two variables # i and j pointing to start and end of # array Such that smallest element of # array pairs with largest element i = 0 j = N - 1 while(i <= j): print(\"(\", arr[i], \",\", arr[j], \")\", end = \" \") i += 1 j -= 1 # Driver Codeif __name__ == '__main__': arr = [9, 6, 5, 1] N = len(arr) findOptimalPairs(arr, N) # This code is contributed by# Sahil_Shelangia", "e": 29011, "s": 28400, "text": null }, { "code": "// C# Program to divide the array into// N pairs such that maximum pair is minimized using System; public class GFG{ static void findOptimalPairs(int []arr, int N){ Array.Sort(arr); // After Sorting Maintain two variables i and j // pointing to start and end of array Such that // smallest element of array pairs with largest // element for (int i = 0, j = N - 1; i <= j; i++, j--) Console.Write( \"(\" + arr[i] + \", \" + arr[j] + \")\" + \" \");} // Driver Code static public void Main (){ int []arr = {9, 6, 5, 1}; int N = arr.Length; findOptimalPairs(arr, N); // This code is contributed by ajit. }}", "e": 29678, "s": 29011, "text": null }, { "code": "<?php// PHP Program to divide the array into// N pairs such that maximum pair is minimized function findOptimalPairs($arr, $N){ sort($arr); // After Sorting Maintain two variables // i and j pointing to start and end of // array Such that smallest element of // array pairs with largest element for ($i = 0, $j = $N - 1; $i <= $j; $i++, $j--) echo \"(\", $arr[$i], \", \", $arr[$j], \")\", \" \";} // Driver Code$arr = array( 9, 6, 5, 1 );$N = sizeof($arr); findOptimalPairs($arr, $N); // This code is contributed by jit_t?>", "e": 30241, "s": 29678, "text": null }, { "code": "<script> /// Javascript Program to divide the array into// N pairs such that maximum pair is minimizedfunction findOptimalPairs(arr, N){ arr.sort(function(a,b){ return a-b;}); // After Sorting Maintain two variables i and j // pointing to start and end of array Such that // smallest element of array pairs with largest // element for (var i = 0, j = N - 1; i <= j; i++, j--) document.write(\"(\" + arr[i] + \", \" + arr[j] + \")\" + \" \");} // Driver Codevar arr = [ 9, 6, 5, 1 ];var N = arr.length;findOptimalPairs(arr, N); </script>", "e": 30796, "s": 30241, "text": null }, { "code": null, "e": 30810, "s": 30796, "text": "(1, 9) (5, 6)" }, { "code": null, "e": 30817, "s": 30812, "text": "vt_m" }, { "code": null, "e": 30823, "s": 30817, "text": "jit_t" }, { "code": null, "e": 30838, "s": 30823, "text": "sahilshelangia" }, { "code": null, "e": 30845, "s": 30838, "text": "rrrtnx" }, { "code": null, "e": 30858, "s": 30845, "text": "Sorting Quiz" }, { "code": null, "e": 30865, "s": 30858, "text": "Arrays" }, { "code": null, "e": 30872, "s": 30865, "text": "Greedy" }, { "code": null, "e": 30880, "s": 30872, "text": "Sorting" }, { "code": null, "e": 30887, "s": 30880, "text": "Arrays" }, { "code": null, "e": 30894, "s": 30887, "text": "Greedy" }, { "code": null, "e": 30902, "s": 30894, "text": "Sorting" }, { "code": null, "e": 31000, "s": 30902, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 31031, "s": 31000, "text": "Chocolate Distribution Problem" }, { "code": null, "e": 31058, "s": 31031, "text": "Count pairs with given sum" }, { "code": null, "e": 31083, "s": 31058, "text": "Window Sliding Technique" }, { "code": null, "e": 31121, "s": 31083, "text": "Reversal algorithm for array rotation" }, { "code": null, "e": 31142, "s": 31121, "text": "Next Greater Element" }, { "code": null, "e": 31193, "s": 31142, "text": "Dijkstra's shortest path algorithm | Greedy Algo-7" }, { "code": null, "e": 31244, "s": 31193, "text": "Prim’s Minimum Spanning Tree (MST) | Greedy Algo-5" }, { "code": null, "e": 31302, "s": 31244, "text": "Kruskal’s Minimum Spanning Tree Algorithm | Greedy Algo-2" }, { "code": null, "e": 31362, "s": 31302, "text": "Write a program to print all permutations of a given string" } ]
Feature Normalisation and Scaling | Towards Data Science
One of the most fundamental steps in machine learning is probably feature engineering, during which we try to craft as predictive features as possible. Once we manage to get there, we probably end up with a bunch of features of significantly different nature. So what is the effect of this irregularity in the model performance and how can we deal with it? Feature Engineering is the process of creating predictive features that can potentially help Machine Learning models achieve a desired performance. In most of the cases, features will be measurements of different unit and range of values. For instance, you might consider adding to your feature space the age of your employees — that could theoretically take values between 1 and 100 — and also their compensation which could range between a few thousands to a few millions. In this article, I am going to introduce Feature Scaling, a pre-processing technique that handles cases where our ML models require scaled features for optimal results. Having features varying in scale and range could be an issue when the model we are trying to build uses distance measures such as Euclidean Distance. Such models could be K-Nearest Neighbours, K-Means Clustering, Learning Vector Quantization (LVQ) etc. Principal Component Analysics (PCA) is also a good example of when feature scaling is important since we are interested in the components that maximize the variance and therefore we need to ensure that we are comparing apples to apples. Furthermore, feature scaling can also help models that use Gradient Descent as their optimisation algorithm - since feature standardisation helps reach convergence much faster. On the other hand, feature scaling is not required (and thus not effective when applied) for models that don’t take a distance-based approach. These include tree-based models such as Decision Trees and Random Forests. Feature scaling is the process of scaling the values of features in a dataset so that they proportionally contribute to the distance calculation. The two most commonly used feature scaling techniques are Standardisation (or Z-Score Normalisation) and Min-Max scaling. Standardisation (also known as Z-Score Normalisation/Standardisation) is the process of rescaling features χ so that they have μ=0 and σ=1. Technically, standardisation centres and normalises the data by subtracting the mean and dividing by the standard deviation. The resulting values are called standard score (or z-score) and can be computed as follows: In Python and scikit-learn this would probably translate to from sklearn.preprocessing import StandardScalerscaler = StandardScaler()train_X = scaler.fit_transform(train_X)test_X = scaler.transform(test_X) Min-Max Scaling is the process of rescaling feature values into a particular range (for example [0, 1]). The formula for scaling the values into a range -σbetween [a, b] is given below+ -(m: from sklearn.preprocessing import MinMaxScalerscaler = MinMaxScaler()train_X = scaler.fit_transform(train_X)test_X = scaler.transform(test_X) It is important to mention that before applying any sort of data normalisation, we first need to split our initial dataset into training and testing sets. Don’t forget that testing data points represent real-world data. As mentioned earlier, mean and standard deviation is taken into account when standardising our data. If we take the mean and variance of the whole dataset then we will be introducing future information into the training explanatory variables. Therefore, we should perform feature scaling over the training data and then perform normalisation on testing instances as well, but this time using the mean and standard deviation of training explanatory variables. In this way, we can test and evaluate whether our model can generalise well to new, unseen data points. Now let’s assume that we want to perform Principal Component Analysis (PCA) over the UCI ML Wine recognition dataset. These data are the results of a chemical analysis of wines grown in the same region in Italy but derived from three different cultivars.The analysis determined the quantities of 13 constituents found in each of the three types of wines. The features are Alcohol, Malic acid, Ash, Alcalinity of ash, Magnesium, Total phenols, Flavanoids, Nonflavanoid phenols, Proanthocyanins, Color intensity, Hue, OD280/OD315 of diluted wines and Proline. The goal is to predict the cultivar that could be one of class_0, class_1 and class_2. For the sake of this example, we are going to skip the feature scaling step at first and observe the results when no pre-processing step is taken. Then, we will repeat the same procedure but this time using feature scaling and finally compare the results. Step 1: Load the data We load the data and separate our features from their respective target variables: from sklearn.datasets import load_winefeatures, target = load_wine(return_X_y=True) Step 2: Split initial dataset into training and testing sets As mentioned earlier, before taking a pre-processing step we first need to split our dataset into training and testing tests. The former will be used for model training and the latter for evaluating the performance of the trained model. from sklearn.model_selection import train_test_splitX_train, X_test, y_train, y_test = train_test_split( features, target, test_size=0.3, random_state=42) Step 3: Scale the data Now we need to scale the data so that we fit the scaler and transform both training and testing sets using the parameters learned after observing training examples. from sklearn.preprocessing import StandardScalerscaler = StandardScaler()X_train_scaled = scaler.fit_transform(X_train)X_test_scaled = scaler.transform(X_test) Step 4: Apply Dimensionality Reduction using PCA Now we can perform Principal Component Analysis. For the sake of ease, I am gonna use two components so that it’s easier to visualise the results later on in a two-dimensional space: pca = PCA(n_components=2)X_train_dim_red = pca.fit_transform(X_train_scaled)X_test_dim_red = pca.transform(X_test_scaled) Now we can quickly visualise the training instances after scaling and performing dimensionality reduction (the link to the code is given below): Below, the same plot is generated but this time no feature scaling was applied: Step 5: Train and evaluate a model Finally, we can fit a Gaussian Naive Bayes model and evaluate the performance of the model on testing instances: from sklearn.naive_bayes import GaussianNBmodel = GaussianNB()model.fit(X_train_dim_red, y_train)predictions = model.predict(X_test_dim_red)print(f'Model Accuracy: {accuracy_score(y_test, predictions):.2f}')>>> Model Accuracy: 0.98 The model accuracy hits 98% on testing instances. In case no scaling is applied, the test accuracy drops to 0.81%. The full code is available on Github as a Gist. Feature scaling is one of the most fundamental pre-processing steps that we need to consider before training machine learning models. As we already discussed, we need to understand whether feature scaling is required. This is dependent to the model we aim to build (for example tree based models don’t require any sort of feature scaling) and the nature of our feature values. Become a member and read every story on Medium. Your membership fee directly supports me and other writers you read.
[ { "code": null, "e": 529, "s": 172, "text": "One of the most fundamental steps in machine learning is probably feature engineering, during which we try to craft as predictive features as possible. Once we manage to get there, we probably end up with a bunch of features of significantly different nature. So what is the effect of this irregularity in the model performance and how can we deal with it?" }, { "code": null, "e": 1004, "s": 529, "text": "Feature Engineering is the process of creating predictive features that can potentially help Machine Learning models achieve a desired performance. In most of the cases, features will be measurements of different unit and range of values. For instance, you might consider adding to your feature space the age of your employees — that could theoretically take values between 1 and 100 — and also their compensation which could range between a few thousands to a few millions." }, { "code": null, "e": 1173, "s": 1004, "text": "In this article, I am going to introduce Feature Scaling, a pre-processing technique that handles cases where our ML models require scaled features for optimal results." }, { "code": null, "e": 1426, "s": 1173, "text": "Having features varying in scale and range could be an issue when the model we are trying to build uses distance measures such as Euclidean Distance. Such models could be K-Nearest Neighbours, K-Means Clustering, Learning Vector Quantization (LVQ) etc." }, { "code": null, "e": 1663, "s": 1426, "text": "Principal Component Analysics (PCA) is also a good example of when feature scaling is important since we are interested in the components that maximize the variance and therefore we need to ensure that we are comparing apples to apples." }, { "code": null, "e": 1840, "s": 1663, "text": "Furthermore, feature scaling can also help models that use Gradient Descent as their optimisation algorithm - since feature standardisation helps reach convergence much faster." }, { "code": null, "e": 2058, "s": 1840, "text": "On the other hand, feature scaling is not required (and thus not effective when applied) for models that don’t take a distance-based approach. These include tree-based models such as Decision Trees and Random Forests." }, { "code": null, "e": 2326, "s": 2058, "text": "Feature scaling is the process of scaling the values of features in a dataset so that they proportionally contribute to the distance calculation. The two most commonly used feature scaling techniques are Standardisation (or Z-Score Normalisation) and Min-Max scaling." }, { "code": null, "e": 2683, "s": 2326, "text": "Standardisation (also known as Z-Score Normalisation/Standardisation) is the process of rescaling features χ so that they have μ=0 and σ=1. Technically, standardisation centres and normalises the data by subtracting the mean and dividing by the standard deviation. The resulting values are called standard score (or z-score) and can be computed as follows:" }, { "code": null, "e": 2743, "s": 2683, "text": "In Python and scikit-learn this would probably translate to" }, { "code": null, "e": 2889, "s": 2743, "text": "from sklearn.preprocessing import StandardScalerscaler = StandardScaler()train_X = scaler.fit_transform(train_X)test_X = scaler.transform(test_X)" }, { "code": null, "e": 3080, "s": 2889, "text": "Min-Max Scaling is the process of rescaling feature values into a particular range (for example [0, 1]). The formula for scaling the values into a range -σbetween [a, b] is given below+ -(m:" }, { "code": null, "e": 3222, "s": 3080, "text": "from sklearn.preprocessing import MinMaxScalerscaler = MinMaxScaler()train_X = scaler.fit_transform(train_X)test_X = scaler.transform(test_X)" }, { "code": null, "e": 3442, "s": 3222, "text": "It is important to mention that before applying any sort of data normalisation, we first need to split our initial dataset into training and testing sets. Don’t forget that testing data points represent real-world data." }, { "code": null, "e": 4005, "s": 3442, "text": "As mentioned earlier, mean and standard deviation is taken into account when standardising our data. If we take the mean and variance of the whole dataset then we will be introducing future information into the training explanatory variables. Therefore, we should perform feature scaling over the training data and then perform normalisation on testing instances as well, but this time using the mean and standard deviation of training explanatory variables. In this way, we can test and evaluate whether our model can generalise well to new, unseen data points." }, { "code": null, "e": 4123, "s": 4005, "text": "Now let’s assume that we want to perform Principal Component Analysis (PCA) over the UCI ML Wine recognition dataset." }, { "code": null, "e": 4360, "s": 4123, "text": "These data are the results of a chemical analysis of wines grown in the same region in Italy but derived from three different cultivars.The analysis determined the quantities of 13 constituents found in each of the three types of wines." }, { "code": null, "e": 4650, "s": 4360, "text": "The features are Alcohol, Malic acid, Ash, Alcalinity of ash, Magnesium, Total phenols, Flavanoids, Nonflavanoid phenols, Proanthocyanins, Color intensity, Hue, OD280/OD315 of diluted wines and Proline. The goal is to predict the cultivar that could be one of class_0, class_1 and class_2." }, { "code": null, "e": 4906, "s": 4650, "text": "For the sake of this example, we are going to skip the feature scaling step at first and observe the results when no pre-processing step is taken. Then, we will repeat the same procedure but this time using feature scaling and finally compare the results." }, { "code": null, "e": 4928, "s": 4906, "text": "Step 1: Load the data" }, { "code": null, "e": 5011, "s": 4928, "text": "We load the data and separate our features from their respective target variables:" }, { "code": null, "e": 5095, "s": 5011, "text": "from sklearn.datasets import load_winefeatures, target = load_wine(return_X_y=True)" }, { "code": null, "e": 5156, "s": 5095, "text": "Step 2: Split initial dataset into training and testing sets" }, { "code": null, "e": 5393, "s": 5156, "text": "As mentioned earlier, before taking a pre-processing step we first need to split our dataset into training and testing tests. The former will be used for model training and the latter for evaluating the performance of the trained model." }, { "code": null, "e": 5551, "s": 5393, "text": "from sklearn.model_selection import train_test_splitX_train, X_test, y_train, y_test = train_test_split( features, target, test_size=0.3, random_state=42)" }, { "code": null, "e": 5574, "s": 5551, "text": "Step 3: Scale the data" }, { "code": null, "e": 5739, "s": 5574, "text": "Now we need to scale the data so that we fit the scaler and transform both training and testing sets using the parameters learned after observing training examples." }, { "code": null, "e": 5899, "s": 5739, "text": "from sklearn.preprocessing import StandardScalerscaler = StandardScaler()X_train_scaled = scaler.fit_transform(X_train)X_test_scaled = scaler.transform(X_test)" }, { "code": null, "e": 5948, "s": 5899, "text": "Step 4: Apply Dimensionality Reduction using PCA" }, { "code": null, "e": 6131, "s": 5948, "text": "Now we can perform Principal Component Analysis. For the sake of ease, I am gonna use two components so that it’s easier to visualise the results later on in a two-dimensional space:" }, { "code": null, "e": 6253, "s": 6131, "text": "pca = PCA(n_components=2)X_train_dim_red = pca.fit_transform(X_train_scaled)X_test_dim_red = pca.transform(X_test_scaled)" }, { "code": null, "e": 6398, "s": 6253, "text": "Now we can quickly visualise the training instances after scaling and performing dimensionality reduction (the link to the code is given below):" }, { "code": null, "e": 6478, "s": 6398, "text": "Below, the same plot is generated but this time no feature scaling was applied:" }, { "code": null, "e": 6513, "s": 6478, "text": "Step 5: Train and evaluate a model" }, { "code": null, "e": 6626, "s": 6513, "text": "Finally, we can fit a Gaussian Naive Bayes model and evaluate the performance of the model on testing instances:" }, { "code": null, "e": 6858, "s": 6626, "text": "from sklearn.naive_bayes import GaussianNBmodel = GaussianNB()model.fit(X_train_dim_red, y_train)predictions = model.predict(X_test_dim_red)print(f'Model Accuracy: {accuracy_score(y_test, predictions):.2f}')>>> Model Accuracy: 0.98" }, { "code": null, "e": 6973, "s": 6858, "text": "The model accuracy hits 98% on testing instances. In case no scaling is applied, the test accuracy drops to 0.81%." }, { "code": null, "e": 7021, "s": 6973, "text": "The full code is available on Github as a Gist." }, { "code": null, "e": 7398, "s": 7021, "text": "Feature scaling is one of the most fundamental pre-processing steps that we need to consider before training machine learning models. As we already discussed, we need to understand whether feature scaling is required. This is dependent to the model we aim to build (for example tree based models don’t require any sort of feature scaling) and the nature of our feature values." } ]
How to Create Full Screen Overlay Navigation Bar using HTML CSS and JavaScript ? - GeeksforGeeks
24 Apr, 2020 Create a full screen Navigation Bar: In this article, you will learn how to create a full-screen navbar for your website. There are three methods to create a full screen overlay navigation bar which are listed below: From Left From top No animation- Just show You will be required to create two divs. One for the overlay container and the other for the overlay content container. Step 1: The first step is to create an HTML file. <div id="myNav" class="overlay"> <!-- Button to close the overlay navigation --> <a href="javascript:void(0)" class="closebtn" onclick="closeNav()">× </a> <!-- Overlay content --> <div class="overlay-content"> <a href="#">About</a> <a href="#">Services</a> <a href="#">Clients</a> <a href="#">Contact</a> </div></div> <!-- Use any element to open/show the overlay navigation menu --><span onclick="openNav()">open</span></div> Step 2: Add CSS to the file. <style> overlay { height: 100%; width: 0; position: fixed; ] z-index: 1; left: 0; top: 0; background-color: rgb(0, 0, 0); background-color: rgba(0, 0, 0, 0.9); overflow-x: hidden; transition: 0.5s; } ].overlay-content { position: relative; top: 25%; width: 100%; text-align: center; margin-top: 30px; } .overlay a { padding: 8px; text-decoration: none; font-size: 36px; color: #818181; /* Display block instead of inline */ display: block; /* Transition effects on hover (color) */ transition: 0.3s; } .overlay a:hover, .overlay a:focus { color: #f1f1f1; } .overlay .closebtn { position: absolute; top: 20px; right: 45px; font-size: 60px; } @media screen and (max-height: 450px) { .overlay a { font-size: 20px } .overlay .closebtn { font-size: 40px; top: 15px; right: 35px; } }</style> Step 3: In the final step add JavaScript to the files. <script> function openNav() { document.getElementById("myNav").style.width = "100%"; } function closeNav() { document.getElementById("myNav").style.width = "0%"; } //or function openNav() { document.getElementById("myNav").style.display = "block"; } function closeNav() { document.getElementById("myNav").style.display = "none"; }</script> Example 1: This example creating the Full Screen Overlay Navigation Bar from left. <!DOCTYPE html><html> <head> <meta name="viewport" content="width=device-width, initial-scale=1"> <style> .overlay { height: 100%; width: 0; position: fixed; top: 0; left: 0; background-color: #1a6e1a; overflow-x: hidden; transition: 1.0s; } .overlay-content { position: relative; top: 25%; width: 100%; text-align: center; } .overlay a { padding: 10px; text-decoration: none; font-size: 40px; color: white; display: block; transition: 0.3s; } .overlay a:hover, .overlay a:focus { color: black; } .overlay .closebtn { position: absolute; top: 10px; right: 35px; font-size: 70px; } </style></head> <body> <div id="myNav" class="overlay"> <a href="javascript:void(0)" class="closebtn" onclick="closeNav()"> × </a> <div class="overlay-content"> <a href="#">About</a> <a href="#">Practice</a> <a href="#">Courses</a> <a href="#">Contact</a> </div> </div> <span style="font-size:35px;cursor:pointer" onclick="openNav()"> ≡ </span> <h2>GeeksForGeeks</h2> <p> Click on the nav bar icon to see full screen overlay: </p> <script> function openNav() { document.getElementById( "myNav").style.width = "100%"; } function closeNav() { document.getElementById( "myNav").style.width = "0%"; } </script></body> </html> Output: Example 2: This example creating the Full-Screen Overlay Navigation Bar from the top. <!DOCTYPE html><html> <head> <meta name="viewport" content="width=device-width, initial-scale=1"> <style> .overlay { height: 0%; width: 100%; position: fixed; top: 0; left: 0; background-color: #1a6e1a; overflow-y: hidden; transition: 1.0s; } .overlay-content { position: relative; top: 25%; width: 100%; text-align: center; } .overlay a { padding: 10px; text-decoration: none; font-size: 40px; color: white; display: block; transition: 0.3s; } .overlay a:hover, .overlay a:focus { color: black; } .overlay .closebtn { position: absolute; top: 10px; right: 35px; font-size: 70px; } </style></head> <body> <div id="myNav" class="overlay"> <a href="javascript:void(0)" class="closebtn" onclick="closeNav()"> × </a> <div class="overlay-content"> <a href="#">About</a> <a href="#">Practice</a> <a href="#">Courses</a> <a href="#">Contact</a> </div> </div> <span style="font-size:35px;cursor:pointer" onclick="openNav()"> ≡ </span> <h2>GeeksForGeeks</h2> <p> Click on the nav bar icon to see full screen overlay: </p> <script> function openNav() { document.getElementById( "myNav").style.height = "100%"; } function closeNav() { document.getElementById( "myNav").style.height = "0%"; } </script></body> </html> Output: Example 3: This example creating the Full-Screen Overlay Navigation Bar without animation. <!DOCTYPE html><html> <head> <meta name="viewport" content= "width=device-width, initial-scale=1"> <style> .overlay { height: 100%; width: 100%; display: none; position: fixed; top: 0; left: 0; background-color: #1a6e1a; } .overlay-content { position: relative; top: 25%; width: 100%; text-align: center; } .overlay a { padding: 10px; text-decoration: none; font-size: 40px; color: white; display: block; transition: 0.3s; } .overlay a:hover, .overlay a:focus { color: black; } .overlay .closebtn { position: absolute; top: 10px; right: 35px; font-size: 70px; } </style></head> <body> <div id="myNav" class="overlay"> <a href="javascript:void(0)" class="closebtn" onclick="closeNav()"> × </a> <div class="overlay-content"> <a href="#">About</a> <a href="#">Practice</a> <a href="#">Courses</a> <a href="#">Contact</a> </div> </div> <span style="font-size:35px;cursor:pointer" onclick="openNav()"> ≡ </span> <h2>GeeksForGeeks</h2> <p> Click on the nav bar icon to see full screen overlay: </p> <script> function openNav() { document.getElementById( "myNav").style.display = "block"; } function closeNav() { document.getElementById( "myNav").style.display = "none"; } </script></body> </html> Output: CSS-Misc HTML-Misc JavaScript-Misc CSS HTML JavaScript Web Technologies Web technologies Questions Write From Home HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to apply style to parent if it has child with CSS? How to set space between the flexbox ? Design a web page using HTML and CSS How to Upload Image into Database and Display it using PHP ? Create a Responsive Navbar using ReactJS How to set the default value for an HTML <select> element ? Hide or show elements in HTML using display property How to set input type date in dd-mm-yyyy format using HTML ? REST API (Introduction) HTML Cheat Sheet - A Basic Guide to HTML
[ { "code": null, "e": 26609, "s": 26581, "text": "\n24 Apr, 2020" }, { "code": null, "e": 26826, "s": 26609, "text": "Create a full screen Navigation Bar: In this article, you will learn how to create a full-screen navbar for your website. There are three methods to create a full screen overlay navigation bar which are listed below:" }, { "code": null, "e": 26836, "s": 26826, "text": "From Left" }, { "code": null, "e": 26845, "s": 26836, "text": "From top" }, { "code": null, "e": 26869, "s": 26845, "text": "No animation- Just show" }, { "code": null, "e": 26989, "s": 26869, "text": "You will be required to create two divs. One for the overlay container and the other for the overlay content container." }, { "code": null, "e": 27039, "s": 26989, "text": "Step 1: The first step is to create an HTML file." }, { "code": "<div id=\"myNav\" class=\"overlay\"> <!-- Button to close the overlay navigation --> <a href=\"javascript:void(0)\" class=\"closebtn\" onclick=\"closeNav()\">× </a> <!-- Overlay content --> <div class=\"overlay-content\"> <a href=\"#\">About</a> <a href=\"#\">Services</a> <a href=\"#\">Clients</a> <a href=\"#\">Contact</a> </div></div> <!-- Use any element to open/show the overlay navigation menu --><span onclick=\"openNav()\">open</span></div>", "e": 27527, "s": 27039, "text": null }, { "code": null, "e": 27556, "s": 27527, "text": "Step 2: Add CSS to the file." }, { "code": "<style> overlay { height: 100%; width: 0; position: fixed; ] z-index: 1; left: 0; top: 0; background-color: rgb(0, 0, 0); background-color: rgba(0, 0, 0, 0.9); overflow-x: hidden; transition: 0.5s; } ].overlay-content { position: relative; top: 25%; width: 100%; text-align: center; margin-top: 30px; } .overlay a { padding: 8px; text-decoration: none; font-size: 36px; color: #818181; /* Display block instead of inline */ display: block; /* Transition effects on hover (color) */ transition: 0.3s; } .overlay a:hover, .overlay a:focus { color: #f1f1f1; } .overlay .closebtn { position: absolute; top: 20px; right: 45px; font-size: 60px; } @media screen and (max-height: 450px) { .overlay a { font-size: 20px } .overlay .closebtn { font-size: 40px; top: 15px; right: 35px; } }</style>", "e": 28699, "s": 27556, "text": null }, { "code": null, "e": 28754, "s": 28699, "text": "Step 3: In the final step add JavaScript to the files." }, { "code": "<script> function openNav() { document.getElementById(\"myNav\").style.width = \"100%\"; } function closeNav() { document.getElementById(\"myNav\").style.width = \"0%\"; } //or function openNav() { document.getElementById(\"myNav\").style.display = \"block\"; } function closeNav() { document.getElementById(\"myNav\").style.display = \"none\"; }</script>", "e": 29157, "s": 28754, "text": null }, { "code": null, "e": 29240, "s": 29157, "text": "Example 1: This example creating the Full Screen Overlay Navigation Bar from left." }, { "code": "<!DOCTYPE html><html> <head> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\"> <style> .overlay { height: 100%; width: 0; position: fixed; top: 0; left: 0; background-color: #1a6e1a; overflow-x: hidden; transition: 1.0s; } .overlay-content { position: relative; top: 25%; width: 100%; text-align: center; } .overlay a { padding: 10px; text-decoration: none; font-size: 40px; color: white; display: block; transition: 0.3s; } .overlay a:hover, .overlay a:focus { color: black; } .overlay .closebtn { position: absolute; top: 10px; right: 35px; font-size: 70px; } </style></head> <body> <div id=\"myNav\" class=\"overlay\"> <a href=\"javascript:void(0)\" class=\"closebtn\" onclick=\"closeNav()\"> × </a> <div class=\"overlay-content\"> <a href=\"#\">About</a> <a href=\"#\">Practice</a> <a href=\"#\">Courses</a> <a href=\"#\">Contact</a> </div> </div> <span style=\"font-size:35px;cursor:pointer\" onclick=\"openNav()\"> ≡ </span> <h2>GeeksForGeeks</h2> <p> Click on the nav bar icon to see full screen overlay: </p> <script> function openNav() { document.getElementById( \"myNav\").style.width = \"100%\"; } function closeNav() { document.getElementById( \"myNav\").style.width = \"0%\"; } </script></body> </html>", "e": 31051, "s": 29240, "text": null }, { "code": null, "e": 31059, "s": 31051, "text": "Output:" }, { "code": null, "e": 31145, "s": 31059, "text": "Example 2: This example creating the Full-Screen Overlay Navigation Bar from the top." }, { "code": "<!DOCTYPE html><html> <head> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\"> <style> .overlay { height: 0%; width: 100%; position: fixed; top: 0; left: 0; background-color: #1a6e1a; overflow-y: hidden; transition: 1.0s; } .overlay-content { position: relative; top: 25%; width: 100%; text-align: center; } .overlay a { padding: 10px; text-decoration: none; font-size: 40px; color: white; display: block; transition: 0.3s; } .overlay a:hover, .overlay a:focus { color: black; } .overlay .closebtn { position: absolute; top: 10px; right: 35px; font-size: 70px; } </style></head> <body> <div id=\"myNav\" class=\"overlay\"> <a href=\"javascript:void(0)\" class=\"closebtn\" onclick=\"closeNav()\"> × </a> <div class=\"overlay-content\"> <a href=\"#\">About</a> <a href=\"#\">Practice</a> <a href=\"#\">Courses</a> <a href=\"#\">Contact</a> </div> </div> <span style=\"font-size:35px;cursor:pointer\" onclick=\"openNav()\"> ≡ </span> <h2>GeeksForGeeks</h2> <p> Click on the nav bar icon to see full screen overlay: </p> <script> function openNav() { document.getElementById( \"myNav\").style.height = \"100%\"; } function closeNav() { document.getElementById( \"myNav\").style.height = \"0%\"; } </script></body> </html>", "e": 32965, "s": 31145, "text": null }, { "code": null, "e": 32973, "s": 32965, "text": "Output:" }, { "code": null, "e": 33064, "s": 32973, "text": "Example 3: This example creating the Full-Screen Overlay Navigation Bar without animation." }, { "code": "<!DOCTYPE html><html> <head> <meta name=\"viewport\" content= \"width=device-width, initial-scale=1\"> <style> .overlay { height: 100%; width: 100%; display: none; position: fixed; top: 0; left: 0; background-color: #1a6e1a; } .overlay-content { position: relative; top: 25%; width: 100%; text-align: center; } .overlay a { padding: 10px; text-decoration: none; font-size: 40px; color: white; display: block; transition: 0.3s; } .overlay a:hover, .overlay a:focus { color: black; } .overlay .closebtn { position: absolute; top: 10px; right: 35px; font-size: 70px; } </style></head> <body> <div id=\"myNav\" class=\"overlay\"> <a href=\"javascript:void(0)\" class=\"closebtn\" onclick=\"closeNav()\"> × </a> <div class=\"overlay-content\"> <a href=\"#\">About</a> <a href=\"#\">Practice</a> <a href=\"#\">Courses</a> <a href=\"#\">Contact</a> </div> </div> <span style=\"font-size:35px;cursor:pointer\" onclick=\"openNav()\"> ≡ </span> <h2>GeeksForGeeks</h2> <p> Click on the nav bar icon to see full screen overlay: </p> <script> function openNav() { document.getElementById( \"myNav\").style.display = \"block\"; } function closeNav() { document.getElementById( \"myNav\").style.display = \"none\"; } </script></body> </html>", "e": 34854, "s": 33064, "text": null }, { "code": null, "e": 34862, "s": 34854, "text": "Output:" }, { "code": null, "e": 34871, "s": 34862, "text": "CSS-Misc" }, { "code": null, "e": 34881, "s": 34871, "text": "HTML-Misc" }, { "code": null, "e": 34897, "s": 34881, "text": "JavaScript-Misc" }, { "code": null, "e": 34901, "s": 34897, "text": "CSS" }, { "code": null, "e": 34906, "s": 34901, "text": "HTML" }, { "code": null, "e": 34917, "s": 34906, "text": "JavaScript" }, { "code": null, "e": 34934, "s": 34917, "text": "Web Technologies" }, { "code": null, "e": 34961, "s": 34934, "text": "Web technologies Questions" }, { "code": null, "e": 34977, "s": 34961, "text": "Write From Home" }, { "code": null, "e": 34982, "s": 34977, "text": "HTML" }, { "code": null, "e": 35080, "s": 34982, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 35135, "s": 35080, "text": "How to apply style to parent if it has child with CSS?" }, { "code": null, "e": 35174, "s": 35135, "text": "How to set space between the flexbox ?" }, { "code": null, "e": 35211, "s": 35174, "text": "Design a web page using HTML and CSS" }, { "code": null, "e": 35272, "s": 35211, "text": "How to Upload Image into Database and Display it using PHP ?" }, { "code": null, "e": 35313, "s": 35272, "text": "Create a Responsive Navbar using ReactJS" }, { "code": null, "e": 35373, "s": 35313, "text": "How to set the default value for an HTML <select> element ?" }, { "code": null, "e": 35426, "s": 35373, "text": "Hide or show elements in HTML using display property" }, { "code": null, "e": 35487, "s": 35426, "text": "How to set input type date in dd-mm-yyyy format using HTML ?" }, { "code": null, "e": 35511, "s": 35487, "text": "REST API (Introduction)" } ]
Angular Material Basic Card Section - GeeksforGeeks
04 Jan, 2022 Angular Material is a UI component library which is developed by Google so that Angular developers can develop modern applications in a structured and responsive way. By making use of this library, we can greatly increase the user experience of an end-user thereby gaining popularity for our application. This library contains modern ready-to-use elements which can be directly used with minimum or no extra code. The <mat-card> is a container for the content that can be used to insert the media, text & action in context to the single subject. The basic requirement for design the card is only an <mat-card> element that has some content in it, that will be used to build simple cards. Syntax: <mat-card> Content </mat-card> This element has opening tag followed with the content or some code & ended with the closing tag. Angular Material facilitates the number of preset sections that can be used with the <mat-card> element, which is given below: <mat-card-title> Title of the respective card <mat-card-subtitle> The subtitle of the respective card <mat-card-content> All the data and information which is the body of the card needs to be written in this section. <mat-card-actions> This tag is used to mention all the events like submit, cancel and etcto be written in the card. <mat-card-header> It is used to mention all the details on the header of the card like title, subtitle etc. This section is anchored to the bottom of the card., that contains the copyright symbol with year, company name, etc. The above elements are primarily used for pre-styled content containers, instead of using any additional APIs. However, the align property with <mat-card-actions>, is mainly used to position the actions at the ‘start’ or ‘end’ of the container. Installation Syntax: In order to use the Basic Card Section in the Angular Material, we must have Angular CLI installed in the local machine, that will help to add and configure the Angular material library. After satisfying the required condition, type the following command on the Angular CLI: ng add @angular/material Please refer to the Adding Angular Material Component to Angular Application article for the detailed installation procedure. Project Structure: After successful installation, the project structure will look like the following: Example: The below example illustrates the implementation of the Angular Material Card. app.module.ts import { NgModule } from "@angular/core";import { BrowserModule } from "@angular/platform-browser";import { FormsModule } from "@angular/forms"; import { AppComponent } from "./app.component";import { MatCardModule } from "@angular/material/card";import { MatButtonModule } from "@angular/material/button"; @NgModule({ imports: [BrowserModule, FormsModule, MatCardModule, MatButtonModule ], declarations: [AppComponent], bootstrap: [AppComponent],})export class AppModule {} app.component.css @import "~material-icons/iconfont/material-icons.css";p { font-family: "Lato", sans-serif; text-align: justify;}.example-card { max-width: 450px; margin: 10px;} mat-card-subtitle { font-size: 18px;} mat-card-title { color: green; font-size: 55px; justify-content: center; display: flex;} app.component.html <mat-card class="example-card"> <mat-card-header> <mat-card-title>GeeksforGeeks</mat-card-title> <mat-card-subtitle> One stop solution for all CS Subjects </mat-card-subtitle> </mat-card-header> <mat-card-content> <p> With the idea of imparting programming knowledge, Mr. Sandeep Jain, an IIT Roorkee alumnus started a dream, GeeksforGeeks. Whether programming excites you or you feel stifled, wondering how to prepare for interview questions or how to ace data structures and algorithms, GeeksforGeeks is a one-stop solution. With every tick of time, we are adding arrows in our quiver. From articles on various computer science subjects to programming problems for practice, from basic to premium courses, from technologies to entrance examinations, we have been building ample content with superior quality. In a short span, we have built a community of 1 Million+ Geeks around the world, 20,000+ Contributors and 500+ Campus Ambassador in various colleges across the nation. Our success stories include a lot of students who benefitted in their placements and landed jobs at tech giants. Our vision is to build a gigantic network of geeks and we are only a fraction of it yet. </p> </mat-card-content> <mat-card-actions> <button mat-button style= "background-color:blue; color:white"> LIKE </button> <button mat-button style= "background-color:green; color:white"> SHARE </button> </mat-card-actions></mat-card> app.component.ts import { Component } from '@angular/core'; @Component({ selector: 'my-app', templateUrl: './app.component.html', styleUrls: [ './app.component.css' ]})export class AppComponent {} Output: Reference: https://material.angular.io/components/card/overview#basic-card-sections bijaybhaskar Angular-material Picked AngularJS CSS 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 ? How to insert spaces/tabs in text using HTML/CSS? Top 10 Projects For Beginners To Practice HTML and CSS Skills How to update Node.js and NPM to next version ? How to create footer to stay at the bottom of a Web page? How to apply style to parent if it has child with CSS?
[ { "code": null, "e": 26282, "s": 26254, "text": "\n04 Jan, 2022" }, { "code": null, "e": 26696, "s": 26282, "text": "Angular Material is a UI component library which is developed by Google so that Angular developers can develop modern applications in a structured and responsive way. By making use of this library, we can greatly increase the user experience of an end-user thereby gaining popularity for our application. This library contains modern ready-to-use elements which can be directly used with minimum or no extra code." }, { "code": null, "e": 26970, "s": 26696, "text": "The <mat-card> is a container for the content that can be used to insert the media, text & action in context to the single subject. The basic requirement for design the card is only an <mat-card> element that has some content in it, that will be used to build simple cards." }, { "code": null, "e": 26978, "s": 26970, "text": "Syntax:" }, { "code": null, "e": 27009, "s": 26978, "text": "<mat-card> Content </mat-card>" }, { "code": null, "e": 27234, "s": 27009, "text": "This element has opening tag followed with the content or some code & ended with the closing tag. Angular Material facilitates the number of preset sections that can be used with the <mat-card> element, which is given below:" }, { "code": null, "e": 27251, "s": 27234, "text": "<mat-card-title>" }, { "code": null, "e": 27280, "s": 27251, "text": "Title of the respective card" }, { "code": null, "e": 27300, "s": 27280, "text": "<mat-card-subtitle>" }, { "code": null, "e": 27336, "s": 27300, "text": "The subtitle of the respective card" }, { "code": null, "e": 27355, "s": 27336, "text": "<mat-card-content>" }, { "code": null, "e": 27452, "s": 27355, "text": "All the data and information which is the body of the card needs to be written in this section. " }, { "code": null, "e": 27471, "s": 27452, "text": "<mat-card-actions>" }, { "code": null, "e": 27568, "s": 27471, "text": "This tag is used to mention all the events like submit, cancel and etcto be written in the card." }, { "code": null, "e": 27586, "s": 27568, "text": "<mat-card-header>" }, { "code": null, "e": 27676, "s": 27586, "text": "It is used to mention all the details on the header of the card like title, subtitle etc." }, { "code": null, "e": 27794, "s": 27676, "text": "This section is anchored to the bottom of the card., that contains the copyright symbol with year, company name, etc." }, { "code": null, "e": 28039, "s": 27794, "text": "The above elements are primarily used for pre-styled content containers, instead of using any additional APIs. However, the align property with <mat-card-actions>, is mainly used to position the actions at the ‘start’ or ‘end’ of the container." }, { "code": null, "e": 28060, "s": 28039, "text": "Installation Syntax:" }, { "code": null, "e": 28335, "s": 28060, "text": "In order to use the Basic Card Section in the Angular Material, we must have Angular CLI installed in the local machine, that will help to add and configure the Angular material library. After satisfying the required condition, type the following command on the Angular CLI:" }, { "code": null, "e": 28360, "s": 28335, "text": "ng add @angular/material" }, { "code": null, "e": 28486, "s": 28360, "text": "Please refer to the Adding Angular Material Component to Angular Application article for the detailed installation procedure." }, { "code": null, "e": 28505, "s": 28486, "text": "Project Structure:" }, { "code": null, "e": 28588, "s": 28505, "text": "After successful installation, the project structure will look like the following:" }, { "code": null, "e": 28676, "s": 28588, "text": "Example: The below example illustrates the implementation of the Angular Material Card." }, { "code": null, "e": 28690, "s": 28676, "text": "app.module.ts" }, { "code": "import { NgModule } from \"@angular/core\";import { BrowserModule } from \"@angular/platform-browser\";import { FormsModule } from \"@angular/forms\"; import { AppComponent } from \"./app.component\";import { MatCardModule } from \"@angular/material/card\";import { MatButtonModule } from \"@angular/material/button\"; @NgModule({ imports: [BrowserModule, FormsModule, MatCardModule, MatButtonModule ], declarations: [AppComponent], bootstrap: [AppComponent],})export class AppModule {}", "e": 29182, "s": 28690, "text": null }, { "code": null, "e": 29200, "s": 29182, "text": "app.component.css" }, { "code": "@import \"~material-icons/iconfont/material-icons.css\";p { font-family: \"Lato\", sans-serif; text-align: justify;}.example-card { max-width: 450px; margin: 10px;} mat-card-subtitle { font-size: 18px;} mat-card-title { color: green; font-size: 55px; justify-content: center; display: flex;}", "e": 29499, "s": 29200, "text": null }, { "code": null, "e": 29518, "s": 29499, "text": "app.component.html" }, { "code": "<mat-card class=\"example-card\"> <mat-card-header> <mat-card-title>GeeksforGeeks</mat-card-title> <mat-card-subtitle> One stop solution for all CS Subjects </mat-card-subtitle> </mat-card-header> <mat-card-content> <p> With the idea of imparting programming knowledge, Mr. Sandeep Jain, an IIT Roorkee alumnus started a dream, GeeksforGeeks. Whether programming excites you or you feel stifled, wondering how to prepare for interview questions or how to ace data structures and algorithms, GeeksforGeeks is a one-stop solution. With every tick of time, we are adding arrows in our quiver. From articles on various computer science subjects to programming problems for practice, from basic to premium courses, from technologies to entrance examinations, we have been building ample content with superior quality. In a short span, we have built a community of 1 Million+ Geeks around the world, 20,000+ Contributors and 500+ Campus Ambassador in various colleges across the nation. Our success stories include a lot of students who benefitted in their placements and landed jobs at tech giants. Our vision is to build a gigantic network of geeks and we are only a fraction of it yet. </p> </mat-card-content> <mat-card-actions> <button mat-button style= \"background-color:blue; color:white\"> LIKE </button> <button mat-button style= \"background-color:green; color:white\"> SHARE </button> </mat-card-actions></mat-card>", "e": 31374, "s": 29518, "text": null }, { "code": null, "e": 31391, "s": 31374, "text": "app.component.ts" }, { "code": "import { Component } from '@angular/core'; @Component({ selector: 'my-app', templateUrl: './app.component.html', styleUrls: [ './app.component.css' ]})export class AppComponent {}", "e": 31576, "s": 31391, "text": null }, { "code": null, "e": 31584, "s": 31576, "text": "Output:" }, { "code": null, "e": 31668, "s": 31584, "text": "Reference: https://material.angular.io/components/card/overview#basic-card-sections" }, { "code": null, "e": 31681, "s": 31668, "text": "bijaybhaskar" }, { "code": null, "e": 31698, "s": 31681, "text": "Angular-material" }, { "code": null, "e": 31705, "s": 31698, "text": "Picked" }, { "code": null, "e": 31715, "s": 31705, "text": "AngularJS" }, { "code": null, "e": 31719, "s": 31715, "text": "CSS" }, { "code": null, "e": 31736, "s": 31719, "text": "Web Technologies" }, { "code": null, "e": 31834, "s": 31736, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 31869, "s": 31834, "text": "Angular PrimeNG Dropdown Component" }, { "code": null, "e": 31904, "s": 31869, "text": "Angular PrimeNG Calendar Component" }, { "code": null, "e": 31939, "s": 31904, "text": "Angular PrimeNG Messages Component" }, { "code": null, "e": 31963, "s": 31939, "text": "Angular 10 (blur) Event" }, { "code": null, "e": 32016, "s": 31963, "text": "How to make a Bootstrap Modal Popup in Angular 9/8 ?" }, { "code": null, "e": 32066, "s": 32016, "text": "How to insert spaces/tabs in text using HTML/CSS?" }, { "code": null, "e": 32128, "s": 32066, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 32176, "s": 32128, "text": "How to update Node.js and NPM to next version ?" }, { "code": null, "e": 32234, "s": 32176, "text": "How to create footer to stay at the bottom of a Web page?" } ]
Bulma | Image - GeeksforGeeks
18 Jun, 2020 Bulma is a free and open-source CSS framework based on Flexbox. It is component rich, compatible, and well documented. It is highly responsive in nature. It uses classes to implement its design.The image class is kind of a container since images took few minutes to load, an image container is reserved space for that image so that website’s layout not going to break while image loading or even in image errors. Example 1: This example using Bulma to display the image. <!DOCTYPE html><html> <head> <title>Bulma Image</title> <link rel='stylesheet' href='https://cdnjs.cloudflare.com/ajax/libs/bulma/0.7.5/css/bulma.css'> <!-- font-awesome cdn --> <script src='https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.12.0-2/js/all.min.js'> </script> <!-- custom css --> <style> div.columns { margin-top: 20px; } h1 { margin-top: 10px; margin-bottom: 20px; color: green !important } p { font-family: calibri; font-size: 16px; text-align: justify; } div p { margin-top: 10px; } </style></head> <body> <div class='container has-text-centered'> <div class='columns is-mobile is-centered'> <div class='column is-6'> <div> <h1 class='title has-text-centered'> Display image </h1> </div> <div class='box'> <div> <figure class="image is-5by3"> <img src="https://media.geeksforgeeks.org/wp-content/uploads/20200617121258/gfg-image2.png"> </figure> </div> <div> <p> A computer is a machine that can be instructed to carry out sequences of arithmetic or logical operations automatically via computer programming. Modern computers have the ability to follow generalized sets of operations, called programs. These programs enable computers to perform an extremely wide range of tasks. </p> </div> </div> </div> </div> </div></body> </html> Output: Example 2: This example using Bulma to display loading error or image error. <html> <head> <title>Bulma Image</title> <link rel='stylesheet' href='https://cdnjs.cloudflare.com/ajax/libs/bulma/0.7.5/css/bulma.css'> <!-- font-awesome cdn --> <script src='https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.12.0-2/js/all.min.js'> </script> <!-- custom css --> <style> div.columns { margin-top: 20px; } h1 { margin-top: 10px; margin-bottom: 20px; color: green !important } p { font-family: calibri; font-size: 16px; text-align: justify; } div p { margin-top: 10px; } </style></head> <body> <div class='container has-text-centered'> <div class='columns is-mobile is-centered'> <div class='column is-6'> <div> <h1 class='title has-text-centered'> Image Error </h1> </div> <div class='box'> <div> <figure class="image is-5by3"> <!-- image url does not exist --> <img src="https://false/image"> </figure> </div> <div> <p> A computer is a machine that can be instructed to carry out sequences of arithmetic or logical operations automatically via computer programming. Modern computers have the ability to follow generalized sets of operations, called programs. These programs enable computers to perform an extremely wide range of tasks. </p> </div> </div> </div> </div> </div></body> </html> Output: Explanation: Bulma image class acts as a container that reserved space for the image so that website layout is not going to break even when image error occurs. Here we provide a false image URL but in spite of that space is reserved for the image to load. Example 3: This example using Bulma to create a rounded Image. <html> <head> <title>Bulma Image</title> <link rel='stylesheet' href='https://cdnjs.cloudflare.com/ajax/libs/bulma/0.7.5/css/bulma.css'> <!-- font-awesome cdn --> <script src='https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.12.0-2/js/all.min.js'> </script> <!-- custom css --> <style> div.columns { margin-top: 80px; } .buttons { margin-top: 15px; } </style></head> <body> <div class='container has-text-centered'> <div class='columns is-mobile is-centered'> <div class='column is-5'> <div class="box"> <article class="media"> <div class="media-left"> <figure class="image is-128x128"> <img class='is-rounded' src="https://media.geeksforgeeks.org/wp-content/uploads/20200617121759/bill-gates.jpg"> </figure> </div> <div class="media-content"> <div class="content"> <p> <strong>Bill Gates</strong> <small>@BillGates</small> <small>36m</small> <br> The horrifying killings of George Floyd, Ahmaud Arbery, Breonna Taylor and far too many other Black people—and the protests they sparked—are shining a light on the brutal injustices that Black people experience every day... </p> </div> <nav class="level is-mobile"> <div class="level-left"> <a class="level-item"> <span class="icon is-small"> <i class="fas fa-reply"></i> </span> </a> <a class="level-item"> <span class="icon is-small"> <i class="fas fa-retweet"></i> </span> </a> <a class="level-item"> <span class="icon is-small"> <i class="fas fa-heart"></i> </span> </a> </div> </nav> </div> </article> </div> </div> </div> </div></body> </html> Output: Example 4: This example using Bulma to create different size of images. <html> <head> <title>Bulma Image</title> <link rel='stylesheet' href='https://cdnjs.cloudflare.com/ajax/libs/bulma/0.7.5/css/bulma.css'> <!-- custom css --> <style> div.columns { margin-top: 80px; } p { font-size: 20px } th { font-size: 20px; } </style></head> <body> <div class='container has-text-centered'> <div class='columns is-mobile is-centered'> <div class='column is-6'> <div class="box"> <table class='table is-fullwidth'> <thead> <tr> <th>Size</th> <th>Image</th> </tr> </thead> <tbody> <tr> <td> <p>24x24px</p> </td> <td> <figure class='image is-24x24'> <img src="https://media.geeksforgeeks.org/wp-content/uploads/20200617121933/24x241.png"> </figure> </td> </tr> <tr> <td> <p>32x32px</p> </td> <td> <figure class='image is-32x32'> <img src="https://media.geeksforgeeks.org/wp-content/uploads/20200617122005/32x32.png"> </figure> </td> </tr> <tr> <td> <p>48x48px</p> </td> <td> <figure class='image is-48x48'> <img src="https://media.geeksforgeeks.org/wp-content/uploads/20200617122245/48x48.png"> </figure> </td> </tr> <tr> <td> <p>64x64px</p> </td> <td> <figure class='image is-64x64'> <img src="https://media.geeksforgeeks.org/wp-content/uploads/20200617122039/64x64.png"> </figure> </td> </tr> <tr> <td> <p>96x96px</p> </td> <td> <figure class='image is-96x96'> <img src="https://media.geeksforgeeks.org/wp-content/uploads/20200617122433/96x96.png"> </figure> </td> </tr> <tr> <td> <p>128x128px</p> </td> <td> <figure class='image is-128x128'> <img src="https://media.geeksforgeeks.org/wp-content/uploads/20200617122510/128x128.png"> </figure> </td> </tr> </tbody> </table> </div> </div> </div> </div></body> </html> Output: Example 5: This example uses Bulma to create a responsive image with aspect ratio. <!DOCTYPE html><html> <head> <title>Bulma Image</title> <link rel='stylesheet' href='https://cdnjs.cloudflare.com/ajax/libs/bulma/0.7.5/css/bulma.css'> <!-- custom css --> <style> div.columns { margin-top: 20px; } p { font-size: 20px } th { font-size: 20px; } </style></head> <body> <div class='container has-text-centered'> <div class='columns is-mobile is-centered'> <div class='column is-6'> <div class="box"> <table class='table is-fullwidth'> <thead> <tr> <th>Size</th> <th>Image</th> </tr> </thead> <tbody> <tr> <td> <p>1by1</p> </td> <td> <figure class='image is-1by1'> <img src="https://media.geeksforgeeks.org/wp-content/uploads/20200617121258/gfg-image2.png"> </figure> </td> </tr> <tr> <td> <p>5by4</p> </td> <td> <figure class='image is-5by4'> <img src="https://media.geeksforgeeks.org/wp-content/uploads/20200617121258/gfg-image2.png"> </figure> </td> </tr> </tbody> </table> </div> </div> </div> </div></body> </html> Output: Example 6: This example uses Bulma to create a responsive image with aspect ratio. <!DOCTYPE html><html> <head> <title>Bulma Image</title> <link rel='stylesheet' href='https://cdnjs.cloudflare.com/ajax/libs/bulma/0.7.5/css/bulma.css'> <!-- custom css --> <style> div.columns { margin-top: 20px; } p { font-size: 20px } th { font-size: 20px; } </style></head> <body> <div class='container has-text-centered'> <div class='columns is-mobile is-centered'> <div class='column is-6'> <div class="box"> <table class='table is-fullwidth'> <thead> <tr> <th>Size</th> <th>Image</th> </tr> </thead> <tbody> <tr> <td> <p>4by3</p> </td> <td> <figure class='image is-4by3'> <img src="https://media.geeksforgeeks.org/wp-content/uploads/20200617121258/gfg-image2.png"> </figure> </td> </tr> <tr> <td> <p>3by2</p> </td> <td> <figure class='image is-3by2'> <img src="https://media.geeksforgeeks.org/wp-content/uploads/20200617121258/gfg-image2.png"> </figure> </td> </tr> </tbody> </table> </div> </div> </div> </div></body> </html> Output: Example 7: This example uses Bulma to create a responsive image with aspect ratio. <!DOCTYPE html><html> <head> <title>Bulma Image</title> <link rel='stylesheet' href='https://cdnjs.cloudflare.com/ajax/libs/bulma/0.7.5/css/bulma.css'> <!-- custom css --> <style> div.columns { margin-top: 5px; } p { font-size: 20px } th { font-size: 20px; } </style></head> <body> <div class='container has-text-centered'> <div class='columns is-mobile is-centered'> <div class='column is-6'> <div class="box"> <table class='table is-fullwidth'> <thead> <tr> <th>Size</th> <th>Image</th> </tr> </thead> <tbody> <tr> <td> <p>5by3</p> </td> <td> <figure class='image is-5by3'> <img src="https://media.geeksforgeeks.org/wp-content/uploads/20200617121258/gfg-image2.png"> </figure> </td> </tr> <tr> <td> <p>16by9</p> </td> <td> <figure class='image is-16by9'> <img src="https://media.geeksforgeeks.org/wp-content/uploads/20200617121258/gfg-image2.png"> </figure> </td> </tr> <tr> <td> <p>2by1</p> </td> <td> <figure class='image is-2by1'> <img src="https://media.geeksforgeeks.org/wp-content/uploads/20200617121258/gfg-image2.png"> </figure> </td> </tr> </tbody> </table> </div> </div> </div> </div></body> </html> Output: Note: Here in all the above examples, we use some extra Bulma classes like container, column, title, table, etc. to design the content well. Bulma CSS Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to insert spaces/tabs in text using HTML/CSS? Top 10 Projects For Beginners To Practice HTML and CSS Skills How to update Node.js and NPM to next version ? How to create footer to stay at the bottom of a Web page? How to apply style to parent if it has child with CSS? 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": 27353, "s": 27325, "text": "\n18 Jun, 2020" }, { "code": null, "e": 27766, "s": 27353, "text": "Bulma is a free and open-source CSS framework based on Flexbox. It is component rich, compatible, and well documented. It is highly responsive in nature. It uses classes to implement its design.The image class is kind of a container since images took few minutes to load, an image container is reserved space for that image so that website’s layout not going to break while image loading or even in image errors." }, { "code": null, "e": 27824, "s": 27766, "text": "Example 1: This example using Bulma to display the image." }, { "code": "<!DOCTYPE html><html> <head> <title>Bulma Image</title> <link rel='stylesheet' href='https://cdnjs.cloudflare.com/ajax/libs/bulma/0.7.5/css/bulma.css'> <!-- font-awesome cdn --> <script src='https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.12.0-2/js/all.min.js'> </script> <!-- custom css --> <style> div.columns { margin-top: 20px; } h1 { margin-top: 10px; margin-bottom: 20px; color: green !important } p { font-family: calibri; font-size: 16px; text-align: justify; } div p { margin-top: 10px; } </style></head> <body> <div class='container has-text-centered'> <div class='columns is-mobile is-centered'> <div class='column is-6'> <div> <h1 class='title has-text-centered'> Display image </h1> </div> <div class='box'> <div> <figure class=\"image is-5by3\"> <img src=\"https://media.geeksforgeeks.org/wp-content/uploads/20200617121258/gfg-image2.png\"> </figure> </div> <div> <p> A computer is a machine that can be instructed to carry out sequences of arithmetic or logical operations automatically via computer programming. Modern computers have the ability to follow generalized sets of operations, called programs. These programs enable computers to perform an extremely wide range of tasks. </p> </div> </div> </div> </div> </div></body> </html>", "e": 29468, "s": 27824, "text": null }, { "code": null, "e": 29476, "s": 29468, "text": "Output:" }, { "code": null, "e": 29553, "s": 29476, "text": "Example 2: This example using Bulma to display loading error or image error." }, { "code": "<html> <head> <title>Bulma Image</title> <link rel='stylesheet' href='https://cdnjs.cloudflare.com/ajax/libs/bulma/0.7.5/css/bulma.css'> <!-- font-awesome cdn --> <script src='https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.12.0-2/js/all.min.js'> </script> <!-- custom css --> <style> div.columns { margin-top: 20px; } h1 { margin-top: 10px; margin-bottom: 20px; color: green !important } p { font-family: calibri; font-size: 16px; text-align: justify; } div p { margin-top: 10px; } </style></head> <body> <div class='container has-text-centered'> <div class='columns is-mobile is-centered'> <div class='column is-6'> <div> <h1 class='title has-text-centered'> Image Error </h1> </div> <div class='box'> <div> <figure class=\"image is-5by3\"> <!-- image url does not exist --> <img src=\"https://false/image\"> </figure> </div> <div> <p> A computer is a machine that can be instructed to carry out sequences of arithmetic or logical operations automatically via computer programming. Modern computers have the ability to follow generalized sets of operations, called programs. These programs enable computers to perform an extremely wide range of tasks. </p> </div> </div> </div> </div> </div></body> </html>", "e": 31155, "s": 29553, "text": null }, { "code": null, "e": 31163, "s": 31155, "text": "Output:" }, { "code": null, "e": 31419, "s": 31163, "text": "Explanation: Bulma image class acts as a container that reserved space for the image so that website layout is not going to break even when image error occurs. Here we provide a false image URL but in spite of that space is reserved for the image to load." }, { "code": null, "e": 31482, "s": 31419, "text": "Example 3: This example using Bulma to create a rounded Image." }, { "code": "<html> <head> <title>Bulma Image</title> <link rel='stylesheet' href='https://cdnjs.cloudflare.com/ajax/libs/bulma/0.7.5/css/bulma.css'> <!-- font-awesome cdn --> <script src='https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.12.0-2/js/all.min.js'> </script> <!-- custom css --> <style> div.columns { margin-top: 80px; } .buttons { margin-top: 15px; } </style></head> <body> <div class='container has-text-centered'> <div class='columns is-mobile is-centered'> <div class='column is-5'> <div class=\"box\"> <article class=\"media\"> <div class=\"media-left\"> <figure class=\"image is-128x128\"> <img class='is-rounded' src=\"https://media.geeksforgeeks.org/wp-content/uploads/20200617121759/bill-gates.jpg\"> </figure> </div> <div class=\"media-content\"> <div class=\"content\"> <p> <strong>Bill Gates</strong> <small>@BillGates</small> <small>36m</small> <br> The horrifying killings of George Floyd, Ahmaud Arbery, Breonna Taylor and far too many other Black people—and the protests they sparked—are shining a light on the brutal injustices that Black people experience every day... </p> </div> <nav class=\"level is-mobile\"> <div class=\"level-left\"> <a class=\"level-item\"> <span class=\"icon is-small\"> <i class=\"fas fa-reply\"></i> </span> </a> <a class=\"level-item\"> <span class=\"icon is-small\"> <i class=\"fas fa-retweet\"></i> </span> </a> <a class=\"level-item\"> <span class=\"icon is-small\"> <i class=\"fas fa-heart\"></i> </span> </a> </div> </nav> </div> </article> </div> </div> </div> </div></body> </html>", "e": 33781, "s": 31482, "text": null }, { "code": null, "e": 33789, "s": 33781, "text": "Output:" }, { "code": null, "e": 33861, "s": 33789, "text": "Example 4: This example using Bulma to create different size of images." }, { "code": "<html> <head> <title>Bulma Image</title> <link rel='stylesheet' href='https://cdnjs.cloudflare.com/ajax/libs/bulma/0.7.5/css/bulma.css'> <!-- custom css --> <style> div.columns { margin-top: 80px; } p { font-size: 20px } th { font-size: 20px; } </style></head> <body> <div class='container has-text-centered'> <div class='columns is-mobile is-centered'> <div class='column is-6'> <div class=\"box\"> <table class='table is-fullwidth'> <thead> <tr> <th>Size</th> <th>Image</th> </tr> </thead> <tbody> <tr> <td> <p>24x24px</p> </td> <td> <figure class='image is-24x24'> <img src=\"https://media.geeksforgeeks.org/wp-content/uploads/20200617121933/24x241.png\"> </figure> </td> </tr> <tr> <td> <p>32x32px</p> </td> <td> <figure class='image is-32x32'> <img src=\"https://media.geeksforgeeks.org/wp-content/uploads/20200617122005/32x32.png\"> </figure> </td> </tr> <tr> <td> <p>48x48px</p> </td> <td> <figure class='image is-48x48'> <img src=\"https://media.geeksforgeeks.org/wp-content/uploads/20200617122245/48x48.png\"> </figure> </td> </tr> <tr> <td> <p>64x64px</p> </td> <td> <figure class='image is-64x64'> <img src=\"https://media.geeksforgeeks.org/wp-content/uploads/20200617122039/64x64.png\"> </figure> </td> </tr> <tr> <td> <p>96x96px</p> </td> <td> <figure class='image is-96x96'> <img src=\"https://media.geeksforgeeks.org/wp-content/uploads/20200617122433/96x96.png\"> </figure> </td> </tr> <tr> <td> <p>128x128px</p> </td> <td> <figure class='image is-128x128'> <img src=\"https://media.geeksforgeeks.org/wp-content/uploads/20200617122510/128x128.png\"> </figure> </td> </tr> </tbody> </table> </div> </div> </div> </div></body> </html>", "e": 36652, "s": 33861, "text": null }, { "code": null, "e": 36660, "s": 36652, "text": "Output:" }, { "code": null, "e": 36743, "s": 36660, "text": "Example 5: This example uses Bulma to create a responsive image with aspect ratio." }, { "code": "<!DOCTYPE html><html> <head> <title>Bulma Image</title> <link rel='stylesheet' href='https://cdnjs.cloudflare.com/ajax/libs/bulma/0.7.5/css/bulma.css'> <!-- custom css --> <style> div.columns { margin-top: 20px; } p { font-size: 20px } th { font-size: 20px; } </style></head> <body> <div class='container has-text-centered'> <div class='columns is-mobile is-centered'> <div class='column is-6'> <div class=\"box\"> <table class='table is-fullwidth'> <thead> <tr> <th>Size</th> <th>Image</th> </tr> </thead> <tbody> <tr> <td> <p>1by1</p> </td> <td> <figure class='image is-1by1'> <img src=\"https://media.geeksforgeeks.org/wp-content/uploads/20200617121258/gfg-image2.png\"> </figure> </td> </tr> <tr> <td> <p>5by4</p> </td> <td> <figure class='image is-5by4'> <img src=\"https://media.geeksforgeeks.org/wp-content/uploads/20200617121258/gfg-image2.png\"> </figure> </td> </tr> </tbody> </table> </div> </div> </div> </div></body> </html>", "e": 38192, "s": 36743, "text": null }, { "code": null, "e": 38200, "s": 38192, "text": "Output:" }, { "code": null, "e": 38283, "s": 38200, "text": "Example 6: This example uses Bulma to create a responsive image with aspect ratio." }, { "code": "<!DOCTYPE html><html> <head> <title>Bulma Image</title> <link rel='stylesheet' href='https://cdnjs.cloudflare.com/ajax/libs/bulma/0.7.5/css/bulma.css'> <!-- custom css --> <style> div.columns { margin-top: 20px; } p { font-size: 20px } th { font-size: 20px; } </style></head> <body> <div class='container has-text-centered'> <div class='columns is-mobile is-centered'> <div class='column is-6'> <div class=\"box\"> <table class='table is-fullwidth'> <thead> <tr> <th>Size</th> <th>Image</th> </tr> </thead> <tbody> <tr> <td> <p>4by3</p> </td> <td> <figure class='image is-4by3'> <img src=\"https://media.geeksforgeeks.org/wp-content/uploads/20200617121258/gfg-image2.png\"> </figure> </td> </tr> <tr> <td> <p>3by2</p> </td> <td> <figure class='image is-3by2'> <img src=\"https://media.geeksforgeeks.org/wp-content/uploads/20200617121258/gfg-image2.png\"> </figure> </td> </tr> </tbody> </table> </div> </div> </div> </div></body> </html>", "e": 39732, "s": 38283, "text": null }, { "code": null, "e": 39740, "s": 39732, "text": "Output:" }, { "code": null, "e": 39823, "s": 39740, "text": "Example 7: This example uses Bulma to create a responsive image with aspect ratio." }, { "code": "<!DOCTYPE html><html> <head> <title>Bulma Image</title> <link rel='stylesheet' href='https://cdnjs.cloudflare.com/ajax/libs/bulma/0.7.5/css/bulma.css'> <!-- custom css --> <style> div.columns { margin-top: 5px; } p { font-size: 20px } th { font-size: 20px; } </style></head> <body> <div class='container has-text-centered'> <div class='columns is-mobile is-centered'> <div class='column is-6'> <div class=\"box\"> <table class='table is-fullwidth'> <thead> <tr> <th>Size</th> <th>Image</th> </tr> </thead> <tbody> <tr> <td> <p>5by3</p> </td> <td> <figure class='image is-5by3'> <img src=\"https://media.geeksforgeeks.org/wp-content/uploads/20200617121258/gfg-image2.png\"> </figure> </td> </tr> <tr> <td> <p>16by9</p> </td> <td> <figure class='image is-16by9'> <img src=\"https://media.geeksforgeeks.org/wp-content/uploads/20200617121258/gfg-image2.png\"> </figure> </td> </tr> <tr> <td> <p>2by1</p> </td> <td> <figure class='image is-2by1'> <img src=\"https://media.geeksforgeeks.org/wp-content/uploads/20200617121258/gfg-image2.png\"> </figure> </td> </tr> </tbody> </table> </div> </div> </div> </div></body> </html>", "e": 41610, "s": 39823, "text": null }, { "code": null, "e": 41618, "s": 41610, "text": "Output:" }, { "code": null, "e": 41759, "s": 41618, "text": "Note: Here in all the above examples, we use some extra Bulma classes like container, column, title, table, etc. to design the content well." }, { "code": null, "e": 41765, "s": 41759, "text": "Bulma" }, { "code": null, "e": 41769, "s": 41765, "text": "CSS" }, { "code": null, "e": 41786, "s": 41769, "text": "Web Technologies" }, { "code": null, "e": 41884, "s": 41786, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 41934, "s": 41884, "text": "How to insert spaces/tabs in text using HTML/CSS?" }, { "code": null, "e": 41996, "s": 41934, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 42044, "s": 41996, "text": "How to update Node.js and NPM to next version ?" }, { "code": null, "e": 42102, "s": 42044, "text": "How to create footer to stay at the bottom of a Web page?" }, { "code": null, "e": 42157, "s": 42102, "text": "How to apply style to parent if it has child with CSS?" }, { "code": null, "e": 42197, "s": 42157, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 42230, "s": 42197, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 42275, "s": 42230, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 42318, "s": 42275, "text": "How to fetch data from an API in ReactJS ?" } ]
Introducing Hoeffding’s Inequality for creating Storage-less Decision Trees | by Dr. Robert Kübler | Towards Data Science
Imagine that you have a huge labeled dataset and you want to build a model for a prediction task. This can be Twitter, for example, where you have more Tweets (the features) than you can count including the corresponding number of likes (labels). Now you want to build a model that can predict whether a tweet will be liked more than 100 times or not, trained on all tweets written in the last year, i.e. we want to solve a classification task. A label of 1 means that the tweet has more than 100 likes, 0 otherwise. You decide to use a Decision Tree or even something smart derived from it, like a Random Forest or Gradient Boosting. But Decision Trees, models based on them, and even other models share the following disadvantage: You need the training data readily available in memory. In the best case, the complete training data fits into your local machine’s memory. However, you realize that the tweets dataset is larger than 8–32GB, so you are out of luck. Maybe you have access to a cluster with 512GB of RAM, but this is not large enough, too. How large is the dataset actually? Let us do a rough estimation. Twitter itself and several other sources (here and here) report that there are around 6,000 Tweets per second. This means around 6,000 * 602 * 24 * 365 = 189,216,000,000‬ tweets per year. Let us assume that each tweet has a size of 140 bytes, one byte for each character in the bag-of-words encoding. We ignore that each tweet might have some metadata attached and that we could also use bigrams, trigrams, etc. This is a whopping 140 * 189,216,000,000‬ / 109= 26,490 GB of tweet data for a single year! So, using RAM is not an option. And even if you happen to own a hard disk big enough to fit the whole dataset, reading the data from it would make the training awfully slow, as you can see here (Figure 3). Well, what to do? Pedro Domingos and Geoff Hulten from the Department of Computer Science & Engineering of the University of Washington introduced a variant of Decision Trees — called Hoeffding Trees [1] — that can be used in a streaming fashion. This means that we have to parse the large training dataset only once and build the tree along the way. We don’t even have to store the samples used: We can grab them directly from Twitter (or any large database), process them by increasing some counters and forget about them again. Why this is possible can be explained using Hoeffding’s Inequality, giving the Hoeffding Trees their name. The high-level idea is that we do not have to look at all the samples, but only at a sufficiently large random subset at each splitting point in the Decision Tree algorithm. How large this subset has to be is the subject of the next section. I am writing this article since Domingos’ and Hulten’s paper is quite technical (and therefore, also precise) and I want to present a high-level, easy to understand view on why the authors’ method works. Also, if you do not want to deal with the math in the next sections, check out the last section for some code at least! There, I am using the package scikit-multiflow to use Hoeffding Trees. Let us examine what Hoeffding’s Inequality says and how we can utilize it to solve the storage problem. Wassily Hoeffding, a Finnish statistician and one of the founders of nonparametric statistics, invented (building upon ideas of Herman Chernoff) discovered an inequality [2] quantifying the following statement: The sum (and also mean) of bounded random variables is tightly concentrated around its expected value. Take a fair coin (probability of seeing heads = 0.5) that we flip 1000 times, for example. Define random variables X1, ..., X1000 with Then the number of heads — let us call it X — is just the sum of the Xi’s. We already know that we can expect 500 times heads since Now Hoeffding’s Inequality got us covered: We also know that X will not deviate much from 500 with high probability, see the illustration below. We will see what “much” and “with high probability” mean in a second. Let X1, ..., Xn be independent Bernoulli random variables, i.e. each of them takes the values 0 or 1. Let X = X1 + ... + Xn be their sum. Then Note: A more general formula holds, where the Xi’s can be bounded between any real numbers a and b and don’t even have to be stochastically independent. But we work with the version presented here. Intuitively, the inequality makes sense: The larger t gets, i.e. the larger we allow the error to become, the more the probability of landing inside the interval or length 2t increases. But the real interesting thing is the following: The right side of the equation only includes the amount of random variables n and the allowed error t. The most important thing, the probability of the Xi’s being equal to one, is nowhere to be found on the right-hand side of the inequality. The probabilities can be known or unknown to us, they can be the same for all i or not, it just does not matter. This is what makes this inequality so versatile and great to work with. Other inequalities with this property are the easier Markov’s Inequality and Chebyshev’s Inequality, but the lower bounds on the right-hand side they give us are much worse. To be fair, these two inequalities do not need that our random variables are bounded. Hoeffding’s Inequality, however, uses the fact that the Xi’s are bounded between 0 and 1. Taking the inequality, replacing t with nt and dividing in the inequality inside P(...) by n yields the Hoeffding Inequality for the mean: where Let us see the inequalities in action now. At first, we will talk about a very basic coin example. Then we will go to the second very important example of estimating shares, that we will need to understand why Hoeffding Trees work. Let’s say that we want to compute the probability of getting less than or equal 450 or greater than or equal 550 heads. Since E(X)=500, we can set t=50 and end up with This means that the probability of deviating less than 50 from the expected value is very high. The number of heads is extremely concentrated around 500. Assume that there is a large pool of N balls, an unknown share p of them being white and the rest being black. A natural question might be: How large is the share p of white balls? If the pool size N is large enough (think of several billion), picking up every ball and checking it is not an option. Of course, the natural thing to do is to uniformly sample a few — let’s say n — balls with replacement and check them. If w of them are white, we would like to conclude that p≈w/n. But how large should our subsample be? What is a good size for n? Is 10 ok? 100? 1000? Well, it depends on how much deviation from p you are fine with and how much confidence you need to be within this deviation. You can set two parameters: an upper bound for the error on p, let’s call it t again a lower bound for the probability of being within the interval centered around p with length 2t, let’s call is 1-ɛ for a small ɛ>0. This means that t and ɛ are fixed, and we want to find a number n of examples, such that with probability at least 1-ɛ the fraction w/n does not differ from p by more than t. We shall formalize this now. Let us define n random variables X1, ..., Xn with Since we randomly draw balls with replacement, the probability of Xi being 1 is exactly p, the unknown share. This is also exactly the expected value of Xi. Let X̅=w/n be the mean of these Bernoulli variables again. Then we also have and Hoeffding’s Inequality gives us Now we want the right-hand side to be larger than 1-ɛ, which gives us a lower bound on X̅=w/n deviating from p by not more than t with probability at least 1-ɛ. Thus, we have to solve the inequality for n. Using some elementary operations, we get If we tolerate an absolute error of at most 1% from p with probability at least 99%, we have to set t=0.01 and ɛ=0.01, giving us a required subsample size of at least Let’s try it out in Python. We consider a pool of 30,000,000 balls, 10,000,000 of them being white (labeled 1) and 20,000,000 being black (labeled 0). So the real share of white balls is 0.3333... which we pretend we don’t know. import numpy as npnp.random.seed(0)# Create a pool with 30 million entries, 10 million being a one (white ball) and 20 million being a zero (black ball).# This means that we have a share of 1/3=0.3333... white balls. pool = 200000000 * [0] + 100000000 * [1]# Set Hoeffding parameters.t = 0.01eps = 0.01hoeffding_amount = int(np.ceil(np.log(2 / eps) / (2 * t ** 2)))subsample = np.random.choice(pool, size=hoeffding_amount, replace=True)print(subsample.mean())# Result: 0.32975992752529065 Looks good! The error is only about 0.0035 < 0.01 = t. But the probability for this to happen was at least 99% anyway, so why are we even celebrating? ;) Note that instead of sampling, saving, and then taking the mean of the 26,492 samples, we can merely sample, increase a counter whenever we have drawn a white ball (a one) and then forget about the sample again. This way we only have to keep track of the counter and the total number of balls we looked at, making this a very memory-efficient memory algorithm (logarithmic in our subsample size n). In total, we can say that a subsample of size around 26,500 is enough for determining the share of white balls with high confidence. In the last example, we have seen how to compute the share of white balls in a gigantic pool of black and white balls without checking the entire pool and without a large error with good probability. We will use this knowledge to train a Decision Tree without the need of having a large amount of training data available in memory, the problem we wanted to solve in the first place. But first, we have to repeat how a Decision Tree is built the usual way. I will not go into much detail here how the (better to say: any) Decision Tree algorithm works. There are many great videos and articles about that on the web and here on Medium. But if the complete training dataset fits into our memory, usually this is what happens in the first step in the algorithm: We calculate a measure of impurity I1 of the labels of the complete dataset, e.g. the Shannon Entropy for classification tasks, which we will also use now. Then we take a feature f and a cut point c. Using these, we partition the complete dataset into two disjoint subsets: One with all the samples where feature f has values smaller (or equal) than c. The other one with all the samples where feature f has values smaller strictly greater than c. The impurity of these two sets is measured again and combined into a weighted average, giving a single impurity measure I2 for both sets. Then the Information Gain is calculated as G=I1-I2. Consider the following example of one split: This is done for all features and all possible cut points and the one with the largest Information Gain G is chosen as the first split in the tree. We repeat this recursively for all leaves in the tree now until some stopping criterion is met (the impurity of a node is smaller than a threshold, the tree has reached a maximum depth, there are too few samples in a node, ...). Now, we have to simulate the behavior using fewer samples. As we have seen for the normal Decision Tree: Only the share p of samples with label 1 matter to compute the impurity! Fortunately, we can approximate this share p and hence the impurity using a subsample of the original training set, as discussed in the section about Hoeffding’s Inequality. Labels with label 1 are the white balls, samples with label 0 are the black balls, in the language of the ball example. Considering a single split, we can approximate I1 using only about 26,500 samples. However, for estimating I2, we need 26,500 in each child node. If we are lucky and the samples get split evenly into the two nodes, 2*26,500=53,000 samples are enough to start with. Otherwise, we might need more, but as long as we need less than several millions or billions of samples, we’re better off than before. And even if we need a million: since we can stream them into the tree and keep track of some counters, we will not run into memory issues. This way we can safely train our model, even on every tweet made on Twitter. Happy large-scale training! If you want to know how this is done in detail, please read the paper [1]. The authors describe their algorithm in pseudo-code with all the counters necessary and they also give proofs on how much the Hoeffding Tree built via streaming the data, and the corresponding normal Decision Tree will deviate. We have seen that training Decision Trees on extremely large training sets is infeasible. Overcoming this problem has taken subsampling the right amount of training samples and build the tree with incomplete, yet quite accurate information. This subsampling is justified by Hoeffding’s Inequality, giving these special Decision Trees also their names: Hoeffding Trees. Moreover, we do not even have to store the subsamples, we just have to keep track of how many samples with label one (white balls) we have seen while scanning the training data, which is an easy and effective way to reduce memory complexity even further. We have only seen vanilla Hoeffding Trees for classification tasks in this article. There also exist algorithms for Regression and even methods to counter the so-called concept shift, i.e. when the training distribution changes over time. Luckily, these algorithms are all implemented by the developers of scikit-multiflow for Python! Let us do a quick test. First, do a fast pip install scikit-multiflow and then let us compare fitting a Hoeffding Tree on the complete training set (=enough RAM available) vs. passing in each sample one by one. More elaborate tests like this can also be found in [1]. from sklearn.datasets import make_classificationfrom sklearn.model_selection import train_test_splitfrom skmultiflow.trees import HoeffdingTreeimport matplotlib.pyplot as pltres = []# Create a dataset.X, y = make_classification(10000, random_state=123)X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=123)# Define a tree for fitting the complete dataset and one for streaming.ht_complete = HoeffdingTree()ht_partial = HoeffdingTree()# Fit the complete dataset.ht_complete.fit(X_train, y_train)ht_complete_score = ht_complete.score(X_test, y_test)print(f'Score when fitting at once: {ht_complete_score}')# Streaming samples one after another.timer = Falsej = 0for i in range(len(X_train)): ht_partial.partial_fit(X_train[i].reshape(1, -1), np.array([y_train[i]])) res.append(ht_partial.score(X_test, y_test)) print(f'Score when streaming after {i} samples: {res[-1]}') if res[-1] >= ht_complete_score - 0.01: print(f'(Almost) full score reached! Continue for another {20 - j} samples.') timer = True if timer: j += 1 if j == 20: break# Plot the scores after each sample.plt.figure(figsize=(12, 6))plt.plot([0, i], [ht_complete_score, ht_complete_score], '--', label='Hoeffding Tree built at once')plt.plot(res, label='Incrementally built Hoeffding Tree')plt.xlabel('Number of Samples', fontsize=15)plt.ylabel('Accuracy', fontsize=15)plt.title('Fitting a Hoeffding Tree at once (enough Memory available) vs fitting it via Streaming', fontsize=20)plt.legend() The resulting graphic might look like this: [1] P. Domingos and G. Hulten, Mining High-Speed Data Streams (2000), Proceedings of the Sixth ACM SIGKDD International Conference on Knowledge Discovery and Data Mining [2] W. Hoeffding, Probability inequalities for sums of bounded random variables (1962), Journal of the American Statistical Association. 58 (301) I hope that you learned something new, interesting, and useful today. Thanks for reading! As the last point, if you want to support me in writing more about machine learning andplan to get a Medium subscription anyway, want to support me in writing more about machine learning and plan to get a Medium subscription anyway, why not do it via this link? This would help me a lot! 😊 To be transparent, the price for you does not change, but about half of the subscription fees go directly to me. Thanks a lot, if you consider supporting me! If you have any questions, write me on LinkedIn!
[ { "code": null, "e": 689, "s": 172, "text": "Imagine that you have a huge labeled dataset and you want to build a model for a prediction task. This can be Twitter, for example, where you have more Tweets (the features) than you can count including the corresponding number of likes (labels). Now you want to build a model that can predict whether a tweet will be liked more than 100 times or not, trained on all tweets written in the last year, i.e. we want to solve a classification task. A label of 1 means that the tweet has more than 100 likes, 0 otherwise." }, { "code": null, "e": 905, "s": 689, "text": "You decide to use a Decision Tree or even something smart derived from it, like a Random Forest or Gradient Boosting. But Decision Trees, models based on them, and even other models share the following disadvantage:" }, { "code": null, "e": 961, "s": 905, "text": "You need the training data readily available in memory." }, { "code": null, "e": 1226, "s": 961, "text": "In the best case, the complete training data fits into your local machine’s memory. However, you realize that the tweets dataset is larger than 8–32GB, so you are out of luck. Maybe you have access to a cluster with 512GB of RAM, but this is not large enough, too." }, { "code": null, "e": 1795, "s": 1226, "text": "How large is the dataset actually? Let us do a rough estimation. Twitter itself and several other sources (here and here) report that there are around 6,000 Tweets per second. This means around 6,000 * 602 * 24 * 365 = 189,216,000,000‬ tweets per year. Let us assume that each tweet has a size of 140 bytes, one byte for each character in the bag-of-words encoding. We ignore that each tweet might have some metadata attached and that we could also use bigrams, trigrams, etc. This is a whopping 140 * 189,216,000,000‬ / 109= 26,490 GB of tweet data for a single year!" }, { "code": null, "e": 2001, "s": 1795, "text": "So, using RAM is not an option. And even if you happen to own a hard disk big enough to fit the whole dataset, reading the data from it would make the training awfully slow, as you can see here (Figure 3)." }, { "code": null, "e": 2019, "s": 2001, "text": "Well, what to do?" }, { "code": null, "e": 2352, "s": 2019, "text": "Pedro Domingos and Geoff Hulten from the Department of Computer Science & Engineering of the University of Washington introduced a variant of Decision Trees — called Hoeffding Trees [1] — that can be used in a streaming fashion. This means that we have to parse the large training dataset only once and build the tree along the way." }, { "code": null, "e": 2639, "s": 2352, "text": "We don’t even have to store the samples used: We can grab them directly from Twitter (or any large database), process them by increasing some counters and forget about them again. Why this is possible can be explained using Hoeffding’s Inequality, giving the Hoeffding Trees their name." }, { "code": null, "e": 2881, "s": 2639, "text": "The high-level idea is that we do not have to look at all the samples, but only at a sufficiently large random subset at each splitting point in the Decision Tree algorithm. How large this subset has to be is the subject of the next section." }, { "code": null, "e": 3085, "s": 2881, "text": "I am writing this article since Domingos’ and Hulten’s paper is quite technical (and therefore, also precise) and I want to present a high-level, easy to understand view on why the authors’ method works." }, { "code": null, "e": 3276, "s": 3085, "text": "Also, if you do not want to deal with the math in the next sections, check out the last section for some code at least! There, I am using the package scikit-multiflow to use Hoeffding Trees." }, { "code": null, "e": 3380, "s": 3276, "text": "Let us examine what Hoeffding’s Inequality says and how we can utilize it to solve the storage problem." }, { "code": null, "e": 3591, "s": 3380, "text": "Wassily Hoeffding, a Finnish statistician and one of the founders of nonparametric statistics, invented (building upon ideas of Herman Chernoff) discovered an inequality [2] quantifying the following statement:" }, { "code": null, "e": 3694, "s": 3591, "text": "The sum (and also mean) of bounded random variables is tightly concentrated around its expected value." }, { "code": null, "e": 3829, "s": 3694, "text": "Take a fair coin (probability of seeing heads = 0.5) that we flip 1000 times, for example. Define random variables X1, ..., X1000 with" }, { "code": null, "e": 3961, "s": 3829, "text": "Then the number of heads — let us call it X — is just the sum of the Xi’s. We already know that we can expect 500 times heads since" }, { "code": null, "e": 4176, "s": 3961, "text": "Now Hoeffding’s Inequality got us covered: We also know that X will not deviate much from 500 with high probability, see the illustration below. We will see what “much” and “with high probability” mean in a second." }, { "code": null, "e": 4319, "s": 4176, "text": "Let X1, ..., Xn be independent Bernoulli random variables, i.e. each of them takes the values 0 or 1. Let X = X1 + ... + Xn be their sum. Then" }, { "code": null, "e": 4517, "s": 4319, "text": "Note: A more general formula holds, where the Xi’s can be bounded between any real numbers a and b and don’t even have to be stochastically independent. But we work with the version presented here." }, { "code": null, "e": 4703, "s": 4517, "text": "Intuitively, the inequality makes sense: The larger t gets, i.e. the larger we allow the error to become, the more the probability of landing inside the interval or length 2t increases." }, { "code": null, "e": 5179, "s": 4703, "text": "But the real interesting thing is the following: The right side of the equation only includes the amount of random variables n and the allowed error t. The most important thing, the probability of the Xi’s being equal to one, is nowhere to be found on the right-hand side of the inequality. The probabilities can be known or unknown to us, they can be the same for all i or not, it just does not matter. This is what makes this inequality so versatile and great to work with." }, { "code": null, "e": 5529, "s": 5179, "text": "Other inequalities with this property are the easier Markov’s Inequality and Chebyshev’s Inequality, but the lower bounds on the right-hand side they give us are much worse. To be fair, these two inequalities do not need that our random variables are bounded. Hoeffding’s Inequality, however, uses the fact that the Xi’s are bounded between 0 and 1." }, { "code": null, "e": 5668, "s": 5529, "text": "Taking the inequality, replacing t with nt and dividing in the inequality inside P(...) by n yields the Hoeffding Inequality for the mean:" }, { "code": null, "e": 5674, "s": 5668, "text": "where" }, { "code": null, "e": 5906, "s": 5674, "text": "Let us see the inequalities in action now. At first, we will talk about a very basic coin example. Then we will go to the second very important example of estimating shares, that we will need to understand why Hoeffding Trees work." }, { "code": null, "e": 6074, "s": 5906, "text": "Let’s say that we want to compute the probability of getting less than or equal 450 or greater than or equal 550 heads. Since E(X)=500, we can set t=50 and end up with" }, { "code": null, "e": 6228, "s": 6074, "text": "This means that the probability of deviating less than 50 from the expected value is very high. The number of heads is extremely concentrated around 500." }, { "code": null, "e": 6528, "s": 6228, "text": "Assume that there is a large pool of N balls, an unknown share p of them being white and the rest being black. A natural question might be: How large is the share p of white balls? If the pool size N is large enough (think of several billion), picking up every ball and checking it is not an option." }, { "code": null, "e": 6796, "s": 6528, "text": "Of course, the natural thing to do is to uniformly sample a few — let’s say n — balls with replacement and check them. If w of them are white, we would like to conclude that p≈w/n. But how large should our subsample be? What is a good size for n? Is 10 ok? 100? 1000?" }, { "code": null, "e": 6950, "s": 6796, "text": "Well, it depends on how much deviation from p you are fine with and how much confidence you need to be within this deviation. You can set two parameters:" }, { "code": null, "e": 7007, "s": 6950, "text": "an upper bound for the error on p, let’s call it t again" }, { "code": null, "e": 7139, "s": 7007, "text": "a lower bound for the probability of being within the interval centered around p with length 2t, let’s call is 1-ɛ for a small ɛ>0." }, { "code": null, "e": 7314, "s": 7139, "text": "This means that t and ɛ are fixed, and we want to find a number n of examples, such that with probability at least 1-ɛ the fraction w/n does not differ from p by more than t." }, { "code": null, "e": 7393, "s": 7314, "text": "We shall formalize this now. Let us define n random variables X1, ..., Xn with" }, { "code": null, "e": 7550, "s": 7393, "text": "Since we randomly draw balls with replacement, the probability of Xi being 1 is exactly p, the unknown share. This is also exactly the expected value of Xi." }, { "code": null, "e": 7627, "s": 7550, "text": "Let X̅=w/n be the mean of these Bernoulli variables again. Then we also have" }, { "code": null, "e": 7663, "s": 7627, "text": "and Hoeffding’s Inequality gives us" }, { "code": null, "e": 7862, "s": 7663, "text": "Now we want the right-hand side to be larger than 1-ɛ, which gives us a lower bound on X̅=w/n deviating from p by not more than t with probability at least 1-ɛ. Thus, we have to solve the inequality" }, { "code": null, "e": 7910, "s": 7862, "text": "for n. Using some elementary operations, we get" }, { "code": null, "e": 8077, "s": 7910, "text": "If we tolerate an absolute error of at most 1% from p with probability at least 99%, we have to set t=0.01 and ɛ=0.01, giving us a required subsample size of at least" }, { "code": null, "e": 8306, "s": 8077, "text": "Let’s try it out in Python. We consider a pool of 30,000,000 balls, 10,000,000 of them being white (labeled 1) and 20,000,000 being black (labeled 0). So the real share of white balls is 0.3333... which we pretend we don’t know." }, { "code": null, "e": 8795, "s": 8306, "text": "import numpy as npnp.random.seed(0)# Create a pool with 30 million entries, 10 million being a one (white ball) and 20 million being a zero (black ball).# This means that we have a share of 1/3=0.3333... white balls. pool = 200000000 * [0] + 100000000 * [1]# Set Hoeffding parameters.t = 0.01eps = 0.01hoeffding_amount = int(np.ceil(np.log(2 / eps) / (2 * t ** 2)))subsample = np.random.choice(pool, size=hoeffding_amount, replace=True)print(subsample.mean())# Result: 0.32975992752529065" }, { "code": null, "e": 8949, "s": 8795, "text": "Looks good! The error is only about 0.0035 < 0.01 = t. But the probability for this to happen was at least 99% anyway, so why are we even celebrating? ;)" }, { "code": null, "e": 9348, "s": 8949, "text": "Note that instead of sampling, saving, and then taking the mean of the 26,492 samples, we can merely sample, increase a counter whenever we have drawn a white ball (a one) and then forget about the sample again. This way we only have to keep track of the counter and the total number of balls we looked at, making this a very memory-efficient memory algorithm (logarithmic in our subsample size n)." }, { "code": null, "e": 9481, "s": 9348, "text": "In total, we can say that a subsample of size around 26,500 is enough for determining the share of white balls with high confidence." }, { "code": null, "e": 9681, "s": 9481, "text": "In the last example, we have seen how to compute the share of white balls in a gigantic pool of black and white balls without checking the entire pool and without a large error with good probability." }, { "code": null, "e": 9864, "s": 9681, "text": "We will use this knowledge to train a Decision Tree without the need of having a large amount of training data available in memory, the problem we wanted to solve in the first place." }, { "code": null, "e": 9937, "s": 9864, "text": "But first, we have to repeat how a Decision Tree is built the usual way." }, { "code": null, "e": 10116, "s": 9937, "text": "I will not go into much detail here how the (better to say: any) Decision Tree algorithm works. There are many great videos and articles about that on the web and here on Medium." }, { "code": null, "e": 10240, "s": 10116, "text": "But if the complete training dataset fits into our memory, usually this is what happens in the first step in the algorithm:" }, { "code": null, "e": 10396, "s": 10240, "text": "We calculate a measure of impurity I1 of the labels of the complete dataset, e.g. the Shannon Entropy for classification tasks, which we will also use now." }, { "code": null, "e": 10514, "s": 10396, "text": "Then we take a feature f and a cut point c. Using these, we partition the complete dataset into two disjoint subsets:" }, { "code": null, "e": 10593, "s": 10514, "text": "One with all the samples where feature f has values smaller (or equal) than c." }, { "code": null, "e": 10688, "s": 10593, "text": "The other one with all the samples where feature f has values smaller strictly greater than c." }, { "code": null, "e": 10878, "s": 10688, "text": "The impurity of these two sets is measured again and combined into a weighted average, giving a single impurity measure I2 for both sets. Then the Information Gain is calculated as G=I1-I2." }, { "code": null, "e": 10923, "s": 10878, "text": "Consider the following example of one split:" }, { "code": null, "e": 11300, "s": 10923, "text": "This is done for all features and all possible cut points and the one with the largest Information Gain G is chosen as the first split in the tree. We repeat this recursively for all leaves in the tree now until some stopping criterion is met (the impurity of a node is smaller than a threshold, the tree has reached a maximum depth, there are too few samples in a node, ...)." }, { "code": null, "e": 11405, "s": 11300, "text": "Now, we have to simulate the behavior using fewer samples. As we have seen for the normal Decision Tree:" }, { "code": null, "e": 11478, "s": 11405, "text": "Only the share p of samples with label 1 matter to compute the impurity!" }, { "code": null, "e": 11772, "s": 11478, "text": "Fortunately, we can approximate this share p and hence the impurity using a subsample of the original training set, as discussed in the section about Hoeffding’s Inequality. Labels with label 1 are the white balls, samples with label 0 are the black balls, in the language of the ball example." }, { "code": null, "e": 12311, "s": 11772, "text": "Considering a single split, we can approximate I1 using only about 26,500 samples. However, for estimating I2, we need 26,500 in each child node. If we are lucky and the samples get split evenly into the two nodes, 2*26,500=53,000 samples are enough to start with. Otherwise, we might need more, but as long as we need less than several millions or billions of samples, we’re better off than before. And even if we need a million: since we can stream them into the tree and keep track of some counters, we will not run into memory issues." }, { "code": null, "e": 12416, "s": 12311, "text": "This way we can safely train our model, even on every tweet made on Twitter. Happy large-scale training!" }, { "code": null, "e": 12719, "s": 12416, "text": "If you want to know how this is done in detail, please read the paper [1]. The authors describe their algorithm in pseudo-code with all the counters necessary and they also give proofs on how much the Hoeffding Tree built via streaming the data, and the corresponding normal Decision Tree will deviate." }, { "code": null, "e": 13088, "s": 12719, "text": "We have seen that training Decision Trees on extremely large training sets is infeasible. Overcoming this problem has taken subsampling the right amount of training samples and build the tree with incomplete, yet quite accurate information. This subsampling is justified by Hoeffding’s Inequality, giving these special Decision Trees also their names: Hoeffding Trees." }, { "code": null, "e": 13343, "s": 13088, "text": "Moreover, we do not even have to store the subsamples, we just have to keep track of how many samples with label one (white balls) we have seen while scanning the training data, which is an easy and effective way to reduce memory complexity even further." }, { "code": null, "e": 13582, "s": 13343, "text": "We have only seen vanilla Hoeffding Trees for classification tasks in this article. There also exist algorithms for Regression and even methods to counter the so-called concept shift, i.e. when the training distribution changes over time." }, { "code": null, "e": 13702, "s": 13582, "text": "Luckily, these algorithms are all implemented by the developers of scikit-multiflow for Python! Let us do a quick test." }, { "code": null, "e": 13719, "s": 13702, "text": "First, do a fast" }, { "code": null, "e": 13748, "s": 13719, "text": "pip install scikit-multiflow" }, { "code": null, "e": 13946, "s": 13748, "text": "and then let us compare fitting a Hoeffding Tree on the complete training set (=enough RAM available) vs. passing in each sample one by one. More elaborate tests like this can also be found in [1]." }, { "code": null, "e": 15494, "s": 13946, "text": "from sklearn.datasets import make_classificationfrom sklearn.model_selection import train_test_splitfrom skmultiflow.trees import HoeffdingTreeimport matplotlib.pyplot as pltres = []# Create a dataset.X, y = make_classification(10000, random_state=123)X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=123)# Define a tree for fitting the complete dataset and one for streaming.ht_complete = HoeffdingTree()ht_partial = HoeffdingTree()# Fit the complete dataset.ht_complete.fit(X_train, y_train)ht_complete_score = ht_complete.score(X_test, y_test)print(f'Score when fitting at once: {ht_complete_score}')# Streaming samples one after another.timer = Falsej = 0for i in range(len(X_train)): ht_partial.partial_fit(X_train[i].reshape(1, -1), np.array([y_train[i]])) res.append(ht_partial.score(X_test, y_test)) print(f'Score when streaming after {i} samples: {res[-1]}') if res[-1] >= ht_complete_score - 0.01: print(f'(Almost) full score reached! Continue for another {20 - j} samples.') timer = True if timer: j += 1 if j == 20: break# Plot the scores after each sample.plt.figure(figsize=(12, 6))plt.plot([0, i], [ht_complete_score, ht_complete_score], '--', label='Hoeffding Tree built at once')plt.plot(res, label='Incrementally built Hoeffding Tree')plt.xlabel('Number of Samples', fontsize=15)plt.ylabel('Accuracy', fontsize=15)plt.title('Fitting a Hoeffding Tree at once (enough Memory available) vs fitting it via Streaming', fontsize=20)plt.legend()" }, { "code": null, "e": 15538, "s": 15494, "text": "The resulting graphic might look like this:" }, { "code": null, "e": 15708, "s": 15538, "text": "[1] P. Domingos and G. Hulten, Mining High-Speed Data Streams (2000), Proceedings of the Sixth ACM SIGKDD International Conference on Knowledge Discovery and Data Mining" }, { "code": null, "e": 15854, "s": 15708, "text": "[2] W. Hoeffding, Probability inequalities for sums of bounded random variables (1962), Journal of the American Statistical Association. 58 (301)" }, { "code": null, "e": 15944, "s": 15854, "text": "I hope that you learned something new, interesting, and useful today. Thanks for reading!" }, { "code": null, "e": 15970, "s": 15944, "text": "As the last point, if you" }, { "code": null, "e": 16073, "s": 15970, "text": "want to support me in writing more about machine learning andplan to get a Medium subscription anyway," }, { "code": null, "e": 16135, "s": 16073, "text": "want to support me in writing more about machine learning and" }, { "code": null, "e": 16177, "s": 16135, "text": "plan to get a Medium subscription anyway," }, { "code": null, "e": 16234, "s": 16177, "text": "why not do it via this link? This would help me a lot! 😊" }, { "code": null, "e": 16347, "s": 16234, "text": "To be transparent, the price for you does not change, but about half of the subscription fees go directly to me." }, { "code": null, "e": 16392, "s": 16347, "text": "Thanks a lot, if you consider supporting me!" } ]
access command in linux with examples - GeeksforGeeks
22 Jul, 2021 In Linux, access command is used to check whether the calling program has access to a specified file. It can be used to check whether a file exists or not. The check is done using the calling process’s real UID and GID. int access(const char *pathname, int mode); Here, the first argument takes the path to the directory/file and the second argument takes flags R_OK, W_OK, X_OK or F_OK. F_OK flag : Used to check for existence of file. R_OK flag : Used to check for read permission bit. W_OK flag : Used to check for write permission bit. X_OK flag : Used to check for execute permission bit. Note: If access() cannot access the file, it will return -1 or else it will be 0. Example 1 : F_OK flag #include<stdio.h>#include<unistd.h>#include<errno.h>#include<sys/types.h>#include<sys/stat.h>#include<fcntl.h> extern int errno; int main(int argc, const char *argv[]){ int fd = access("sample.txt", F_OK); if(fd == -1){ printf("Error Number : %d\n", errno); perror("Error Description:"); } else printf("No error\n"); return 0;} Explanation: In the output, we get the message “No error” because the file is present in the current directory. If the file does not exist, the value of fd will become -1. In the above code, the only possible way we will get an error is if the file doesn’t exist for the specified path. It can also give an error if the pathname is too long. Note: perror() is used to print the error and errno is used to print the error code. Example 2 : Check for all permission bits (read, write, execute) #include<stdio.h>#include<unistd.h>#include<errno.h>#include<sys/types.h>#include<sys/stat.h>#include<fcntl.h> extern int errno; int main(int argc, const char *argv[]){ int fd = access("sample.txt", (R_OK | W_OK) & X_OK); if(fd == -1){ printf("Error Number : %d\n", errno); perror("Error Description:"); } else{ printf("No error\n"); } return 0;} Explanation: In the output, the write and execute user permission bits were set and since we were testing for a case where (R_OK | W_OK) & X_OK, we get no error. The file descriptor value is 0. We can use bitwise operations to decide the mode argument in access() system call. Example 3 : Check for all permission bits (read, write, execute) to demonstrate how the code functions, when we get an error. #include<stdio.h>#include<unistd.h>#include<errno.h>#include<sys/types.h>#include<sys/stat.h>#include<fcntl.h> extern int errno; int main(int argc, const char *argv[]){ int fd = access("sample.txt", R_OK & W_OK & X_OK); if(fd == -1){ printf("Error Number : %d\n", errno); perror("Error Description:"); } else{ printf("No error\n"); } return 0;} Here, fd = -1 and we get the error message for the reason of failure of the calling process. linux-command Linux-file-commands Picked Technical Scripter 2018 Linux-Unix Technical Scripter Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments tar command in Linux with examples UDP Server-Client implementation in C 'crontab' in Linux with Examples diff command in Linux with examples Cat command in Linux with examples echo command in Linux with Examples Mutex lock for Linux Thread Synchronization touch command in Linux with Examples Tail command in Linux with examples Compiling with g++
[ { "code": null, "e": 24666, "s": 24638, "text": "\n22 Jul, 2021" }, { "code": null, "e": 24886, "s": 24666, "text": "In Linux, access command is used to check whether the calling program has access to a specified file. It can be used to check whether a file exists or not. The check is done using the calling process’s real UID and GID." }, { "code": null, "e": 24931, "s": 24886, "text": "int access(const char *pathname, int mode);\n" }, { "code": null, "e": 25055, "s": 24931, "text": "Here, the first argument takes the path to the directory/file and the second argument takes flags R_OK, W_OK, X_OK or F_OK." }, { "code": null, "e": 25104, "s": 25055, "text": "F_OK flag : Used to check for existence of file." }, { "code": null, "e": 25155, "s": 25104, "text": "R_OK flag : Used to check for read permission bit." }, { "code": null, "e": 25207, "s": 25155, "text": "W_OK flag : Used to check for write permission bit." }, { "code": null, "e": 25261, "s": 25207, "text": "X_OK flag : Used to check for execute permission bit." }, { "code": null, "e": 25343, "s": 25261, "text": "Note: If access() cannot access the file, it will return -1 or else it will be 0." }, { "code": null, "e": 25365, "s": 25343, "text": "Example 1 : F_OK flag" }, { "code": "#include<stdio.h>#include<unistd.h>#include<errno.h>#include<sys/types.h>#include<sys/stat.h>#include<fcntl.h> extern int errno; int main(int argc, const char *argv[]){ int fd = access(\"sample.txt\", F_OK); if(fd == -1){ printf(\"Error Number : %d\\n\", errno); perror(\"Error Description:\"); } else printf(\"No error\\n\"); return 0;}", "e": 25747, "s": 25365, "text": null }, { "code": null, "e": 26089, "s": 25747, "text": "Explanation: In the output, we get the message “No error” because the file is present in the current directory. If the file does not exist, the value of fd will become -1. In the above code, the only possible way we will get an error is if the file doesn’t exist for the specified path. It can also give an error if the pathname is too long." }, { "code": null, "e": 26174, "s": 26089, "text": "Note: perror() is used to print the error and errno is used to print the error code." }, { "code": null, "e": 26239, "s": 26174, "text": "Example 2 : Check for all permission bits (read, write, execute)" }, { "code": "#include<stdio.h>#include<unistd.h>#include<errno.h>#include<sys/types.h>#include<sys/stat.h>#include<fcntl.h> extern int errno; int main(int argc, const char *argv[]){ int fd = access(\"sample.txt\", (R_OK | W_OK) & X_OK); if(fd == -1){ printf(\"Error Number : %d\\n\", errno); perror(\"Error Description:\"); } else{ printf(\"No error\\n\"); } return 0;}", "e": 26627, "s": 26239, "text": null }, { "code": null, "e": 26904, "s": 26627, "text": "Explanation: In the output, the write and execute user permission bits were set and since we were testing for a case where (R_OK | W_OK) & X_OK, we get no error. The file descriptor value is 0. We can use bitwise operations to decide the mode argument in access() system call." }, { "code": null, "e": 27030, "s": 26904, "text": "Example 3 : Check for all permission bits (read, write, execute) to demonstrate how the code functions, when we get an error." }, { "code": "#include<stdio.h>#include<unistd.h>#include<errno.h>#include<sys/types.h>#include<sys/stat.h>#include<fcntl.h> extern int errno; int main(int argc, const char *argv[]){ int fd = access(\"sample.txt\", R_OK & W_OK & X_OK); if(fd == -1){ printf(\"Error Number : %d\\n\", errno); perror(\"Error Description:\"); } else{ printf(\"No error\\n\"); } return 0;}", "e": 27416, "s": 27030, "text": null }, { "code": null, "e": 27509, "s": 27416, "text": "Here, fd = -1 and we get the error message for the reason of failure of the calling process." }, { "code": null, "e": 27523, "s": 27509, "text": "linux-command" }, { "code": null, "e": 27543, "s": 27523, "text": "Linux-file-commands" }, { "code": null, "e": 27550, "s": 27543, "text": "Picked" }, { "code": null, "e": 27574, "s": 27550, "text": "Technical Scripter 2018" }, { "code": null, "e": 27585, "s": 27574, "text": "Linux-Unix" }, { "code": null, "e": 27604, "s": 27585, "text": "Technical Scripter" }, { "code": null, "e": 27702, "s": 27604, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27711, "s": 27702, "text": "Comments" }, { "code": null, "e": 27724, "s": 27711, "text": "Old Comments" }, { "code": null, "e": 27759, "s": 27724, "text": "tar command in Linux with examples" }, { "code": null, "e": 27797, "s": 27759, "text": "UDP Server-Client implementation in C" }, { "code": null, "e": 27830, "s": 27797, "text": "'crontab' in Linux with Examples" }, { "code": null, "e": 27866, "s": 27830, "text": "diff command in Linux with examples" }, { "code": null, "e": 27901, "s": 27866, "text": "Cat command in Linux with examples" }, { "code": null, "e": 27937, "s": 27901, "text": "echo command in Linux with Examples" }, { "code": null, "e": 27981, "s": 27937, "text": "Mutex lock for Linux Thread Synchronization" }, { "code": null, "e": 28018, "s": 27981, "text": "touch command in Linux with Examples" }, { "code": null, "e": 28054, "s": 28018, "text": "Tail command in Linux with examples" } ]
Python | Get a google map image of specified location using Google Static Maps API
31 May, 2019 Google Static Maps API lets embed a Google Maps image on the web page without requiring JavaScript or any dynamic page loading. The Google Static Maps API service creates the map based on URL parameters sent through a standard HTTP request and returns the map as an image one can display on the web page. To use this service, one must need an API key, get it form here . Note: One need to create billing account on google then only can use Google APIs. Modules needed : import requests Below is the implementation : # Python program to get a google map # image of specified location using # Google Static Maps API # importing required modulesimport requests # Enter your api key hereapi_key = "_your_api_key_" # url variable store urlurl = "https://maps.googleapis.com/maps/api/staticmap?" # center defines the center of the map,# equidistant from all edges of the map. center = "Dehradun" # zoom defines the zoom# level of the mapzoom = 10 # get method of requests module# return response objectr = requests.get(url + "center =" + center + "&zoom =" + str(zoom) + "&size = 400x400&key =" + api_key + "sensor = false") # wb mode is stand for write binary modef = open('address of the file location ', 'wb') # r.content gives content,# in this case gives imagef.write(r.content) # close method of file object# save and close the filef.close() Output : Note : For checking whether the API key is properly working or not, store r.content in .txt file, inspite of saving as .png file. If the API key is invalid, API will return this error message instead of image “The Google Maps API server rejected your request. The provided API key is invalid “. Following list shows the approximate level of detail one can expect to see at each zoom level : 1 : World 5 : Landmass/continent 10 : City 15 : Streets 20 : Buildings shubham_singh python-utility Python Python Programs 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() Python program to convert a list to string Defaultdict in Python Python | Get dictionary keys as a list Python | Convert a list to dictionary Python | Convert string dictionary to dictionary
[ { "code": null, "e": 28, "s": 0, "text": "\n31 May, 2019" }, { "code": null, "e": 333, "s": 28, "text": "Google Static Maps API lets embed a Google Maps image on the web page without requiring JavaScript or any dynamic page loading. The Google Static Maps API service creates the map based on URL parameters sent through a standard HTTP request and returns the map as an image one can display on the web page." }, { "code": null, "e": 399, "s": 333, "text": "To use this service, one must need an API key, get it form here ." }, { "code": null, "e": 481, "s": 399, "text": "Note: One need to create billing account on google then only can use Google APIs." }, { "code": null, "e": 498, "s": 481, "text": "Modules needed :" }, { "code": null, "e": 514, "s": 498, "text": "import requests" }, { "code": null, "e": 544, "s": 514, "text": "Below is the implementation :" }, { "code": "# Python program to get a google map # image of specified location using # Google Static Maps API # importing required modulesimport requests # Enter your api key hereapi_key = \"_your_api_key_\" # url variable store urlurl = \"https://maps.googleapis.com/maps/api/staticmap?\" # center defines the center of the map,# equidistant from all edges of the map. center = \"Dehradun\" # zoom defines the zoom# level of the mapzoom = 10 # get method of requests module# return response objectr = requests.get(url + \"center =\" + center + \"&zoom =\" + str(zoom) + \"&size = 400x400&key =\" + api_key + \"sensor = false\") # wb mode is stand for write binary modef = open('address of the file location ', 'wb') # r.content gives content,# in this case gives imagef.write(r.content) # close method of file object# save and close the filef.close()", "e": 1425, "s": 544, "text": null }, { "code": null, "e": 1434, "s": 1425, "text": "Output :" }, { "code": null, "e": 1730, "s": 1434, "text": "Note : For checking whether the API key is properly working or not, store r.content in .txt file, inspite of saving as .png file. If the API key is invalid, API will return this error message instead of image “The Google Maps API server rejected your request. The provided API key is invalid “. " }, { "code": null, "e": 1826, "s": 1730, "text": "Following list shows the approximate level of detail one can expect to see at each zoom level :" }, { "code": null, "e": 1898, "s": 1826, "text": "1 : World\n5 : Landmass/continent\n10 : City\n15 : Streets\n20 : Buildings\n" }, { "code": null, "e": 1912, "s": 1898, "text": "shubham_singh" }, { "code": null, "e": 1927, "s": 1912, "text": "python-utility" }, { "code": null, "e": 1934, "s": 1927, "text": "Python" }, { "code": null, "e": 1950, "s": 1934, "text": "Python Programs" }, { "code": null, "e": 2048, "s": 1950, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2066, "s": 2048, "text": "Python Dictionary" }, { "code": null, "e": 2108, "s": 2066, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 2130, "s": 2108, "text": "Enumerate() in Python" }, { "code": null, "e": 2165, "s": 2130, "text": "Read a file line by line in Python" }, { "code": null, "e": 2191, "s": 2165, "text": "Python String | replace()" }, { "code": null, "e": 2234, "s": 2191, "text": "Python program to convert a list to string" }, { "code": null, "e": 2256, "s": 2234, "text": "Defaultdict in Python" }, { "code": null, "e": 2295, "s": 2256, "text": "Python | Get dictionary keys as a list" }, { "code": null, "e": 2333, "s": 2295, "text": "Python | Convert a list to dictionary" } ]
VB.NET Interview Questions
Dear readers, these VB.NET Interview Questions have been designed specially to get you acquainted with the nature of questions you may encounter during your interview for the subject of VB.NET Language. As per my experience good interviewers hardly plan to ask any particular question during your interview, normally questions start with some basic concept of the subject and later they continue based on further discussion and what you answer: Visual Basic .NET (VB.NET) is an object-oriented computer programming language implemented on the .NET Framework. Although it is an evolution of classic Visual Basic language, it is not backwards-compatible with VB6, and any code written in the old version does not compile under VB.NET. Sub Main indicates the entry point of VB.Net program. Shared methods or static methods can be invoked without creating an object of the class. Shared declares a shared variable, which is not associated with any specific instance of a class or structure, rather available to all the instances of the class or structure. Shadows indicate that the variable re-declares and hides an identically named element, or set of overloaded elements, in a base class. Static indicates that the variable will retain its value, even when the after termination of the procedure in which it is declared. In VB.Net, constants are declared using the Const statement. The Const statement is used at module, class, structure, procedure, or block level for use in place of literal values. Ansi − Specifies that Visual Basic should marshal all strings to American National Standards Institute (ANSI) values regardless of the name of the external procedure being declared. Assembly − Specifies that an attribute at the beginning of a source file applies to the entire assembly. Async − Indicates that the method or lambda expression that it modifies is asynchronous. Such methods are referred to as async methods. The caller of an async method can resume its work without waiting for the async method to finish. Auto − The charsetmodifier part in the Declare statement supplies the character set information for marshaling strings during a call to the external procedure. It also affects how Visual Basic searches the external file for the external procedure name. The Auto modifier specifies that Visual Basic should marshal strings according to .NET Framework rules. ByRef − Specifies that an argument is passed by reference, i.e., the called procedure can change the value of a variable underlying the argument in the calling code. It is used under the contexts of − Declare Statement Declare Statement Function Statement Function Statement Sub Statement Sub Statement ByVal − Specifies that an argument is passed in such a way that the called procedure or property cannot change the value of a variable underlying the argument in the calling code. It is used under the contexts of − Declare Statement Declare Statement Function Statement Function Statement Operator Statement Operator Statement Property Statement Property Statement Sub Statement Sub Statement Default − Identifies a property as the default property of its class, structure, or interface. Friend − Specifies that one or more declared programming elements are accessible from within the assembly that contains their declaration, not only by the component that declares them. Friend access is often the preferred level for an application's programming elements, and Friend is the default access level of an interface, a module, a class, or a structure. In − It is used in generic interfaces and delegates. Iterator − Specifies that a function or Get accessor is an iterator. An iterator performs a custom iteration over a collection. Key − The Key keyword enables you to specify behavior for properties of anonymous types. Module − Specifies that an attribute at the beginning of a source file applies to the current assembly module. It is not same as the Module statement. MustInherit − Specifies that a class can be used only as a base class and that you cannot create an object directly from it. MustOverride − Specifies that a property or procedure is not implemented in this class and must be overridden in a derived class before it can be used. Narrowing − Indicates that a conversion operator (CType) converts a class or structure to a type that might not be able to hold some of the possible values of the original class or structure. NotInheritable − Specifies that a class cannot be used as a base class. NotOverridable − Specifies that a property or procedure cannot be overridden in a derived class. Optional − Specifies that a procedure argument can be omitted when the procedure is called. Out − For generic type parameters, the Out keyword specifies that the type is covariant. Overloads − Specifies that a property or procedure redeclares one or more existing properties or procedures with the same name. Overridable − Specifies that a property or procedure can be overridden by an identically named property or procedure in a derived class. Overrides − Specifies that a property or procedure overrides an identically named property or procedure inherited from a base class. ParamArray − ParamArray allows you to pass an arbitrary number of arguments to the procedure. A ParamArray parameter is always declared using ByVal. Partial − Indicates that a class or structure declaration is a partial definition of the class or structure. Private − Specifies that one or more declared programming elements are accessible only from within their declaration context, including from within any contained types. Protected − Specifies that one or more declared programming elements are accessible only from within their own class or from a derived class. Public − Specifies that one or more declared programming elements have no access restrictions. ReadOnly − Specifies that a variable or property can be read but not written. Shadows − Specifies that a declared programming element redeclares and hides an identically named element, or set of overloaded elements, in a base class. Shared − Specifies that one or more declared programming elements are associated with a class or structure at large, and not with a specific instance of the class or structure. Static − Specifies that one or more declared local variables are to continue to exist and retain their latest values after termination of the procedure in which they are declared. Unicode − Specifies that Visual Basic should marshal all strings to Unicode values regardless of the name of the external procedure being declared. Widening − Indicates that a conversion operator (CType) converts a class or structure to a type that can hold all possible values of the original class or structure. WithEvents − Specifies that one or more declared member variables refer to an instance of a class that can raise events. WriteOnly − Specifies that a property can be written but not read. Dim Statement − Declares and allocates storage space for one or more variables. Dim number As Integer Dim quantity As Integer = 100 Dim message As String = "Hello!" Const Statement − Declares and defines one or more constants. Const maximum As Long = 1000 Const naturalLogBase As Object = CDec(2.7182818284) Enum Statement − Declares an enumeration and defines the values of its members. Enum CoffeeMugSize Jumbo ExtraLarge Large Medium Small End Enum Class Statement − Declares the name of a class and introduces the definition of the variables, properties, events, and procedures that the class comprises. Class Box Public length As Double Public breadth As Double Public height As Double End Class Structure Statement − Declares the name of a structure and introduces the definition of the variables, properties, events, and procedures that the structure comprises. Structure Box Public length As Double Public breadth As Double Public height As Double End Structure Module Statement − Declares the name of a module and introduces the definition of the variables, properties, events, and procedures that the module comprises. Public Module myModule Sub Main() Dim user As String = InputBox("What is your name?") MsgBox("User name is" & user) End Sub End Module Interface Statement − Declares the name of an interface and introduces the definitions of the members that the interface comprises. Public Interface MyInterface Sub doSomething() End Interface Function Statement − Declares the name, parameters, and code that define a Function procedure. Function myFunction (ByVal n As Integer) As Double Return 5.87 * n End Function Sub Statement − Declares the name, parameters, and code that define a Sub procedure. Sub mySub(ByVal s As String) Return End Sub Declare Statement − Declares a reference to a procedure implemented in an external file. Declare Function getUserName Lib "advapi32.dll" Alias "GetUserNameA" ( ByVal lpBuffer As String, ByRef nSize As Integer) As Integer Operator Statement − Declares the operator symbol, operands, and code that define an operator procedure on a class or structure. Public Shared Operator + (ByVal x As obj, ByVal y As obj) As obj Dim r As New obj ' implemention code for r = x + y Return r End Operator Property Statement − Declares the name of a property, and the property procedures used to store and retrieve the value of the property. ReadOnly Property quote() As String Get Return quoteString End Get End Property Event Statement − Declares a user-defined event. Public Event Finished() Delegate Statement − Used to declare a delegate. Delegate Function MathOperator( ByVal x As Double, ByVal y As Double ) As Double The VB.Net compiler directives give instructions to the compiler to preprocess the information before actual compilation starts. All these directives begin with #, and only white-space characters may appear before a directive on a line. These directives are not statements. AddressOf − Returns the address of a procedure. AddHandler Button1.Click, AddressOf Button1_Click Await − It is applied to an operand in an asynchronous method or lambda expression to suspend execution of the method until the awaited task completes. Dim result As res = Await AsyncMethodThatReturnsResult() Await AsyncMethod() GetType − It returns a Type object for the specified type. The Type object provides information about the type such as its properties, methods, and events. MsgBox(GetType(Integer).ToString()) Function Expression − It declares the parameters and code that define a function lambda expression. Dim add5 = Function(num As Integer) num + 5 'prints 10 Console.WriteLine(add5(5)) If − It uses short-circuit evaluation to conditionally return one of two values. The If operator can be called with three arguments or with two arguments. Exit statement − Terminates the loop or select case statement and transfers execution to the statement immediately following the loop or select case. Continue statement − Causes the loop to skip the remainder of its body and immediately retest its condition prior to reiterating. GoTo statement − Transfers control to the labeled statement. Though it is not advised to use GoTo statement in your program. Dynamic arrays are arrays that can be dimensioned and re-dimensioned as par the need of the program. You can declare a dynamic array using the ReDim statement. A Jagged array is an array of arrays. A Jagged array is an array of arrays. The follwoing code shows declaring a jagged array named scores of Integers: Dim scores As Integer()() = New Integer(5)(){} It represents ordered collection of an object that can be indexed individually. It is basically an alternative to an array. However, unlike array, you can add and remove items from a list at a specified position using an index and the array resizes itself automatically. It also allows dynamic memory allocation, add, search and sort items in the list. It uses a key to access the elements in the collection. A hash table is used when you need to access elements by using key, and you can identify a useful key value. Each item in the hash table has a key/value pair. The key is used to access the items in the collection. It uses a key as well as an index to access the items in a list. A sorted list is a combination of an array and a hash table. It contains a list of items that can be accessed using a key or an index. If you access items using an index, it is an ArrayList, and if you access items using a key, it is a Hashtable. The collection of items is always sorted by the key value. It represents a last-in, first out collection of object. It is used when you need a last-in, first-out access of items. When you add an item in the list, it is called pushing the item, and when you remove it, it is called popping the item. It represents a first-in, first out collection of object. It is used when you need a first-in, first-out access of items. When you add an item in the list, it is called enqueue, and when you remove an item, it is called deque. It represents an array of the binary representation using the values 1 and 0. It is used when you need to store the bits but do not know the number of bits in advance. You can access items from the BitArray collection by using an integer index, which starts from zero. In VB.Net, a function can return a value to the calling code in two ways − By using the return statement. By using the return statement. By assigning the value to the function name. By assigning the value to the function name. By using the params keyword, a method parameter can be specified which takes a variable number of arguments or even no argument. No! additional parameters are not permitted after the params keyword in a method declaration. Only one params keyword is allowed in a method declaration. VB.NET exceptions are represented by classes. The exception classes in VB.NET are mainly directly or indirectly derived from the System.Exception class. Some of the exception classes derived from the System.Exception class are the System.ApplicationException and System.SystemException classes. The System.ApplicationException class supports exceptions generated by application programs. Hence the exceptions defined by the programmers should derive from this class. The System.SystemException class is the base class for all predefined system exception. The stream is basically the sequence of bytes passing through the communication path. There are two main streams: the input stream and the output stream. The input stream is used for reading data from file (read operation) and the output stream is used for writing into the file (write operation). The FileStream class in the System.IO namespace helps in reading from, writing to and closing files. This class derives from the abstract class Stream. The StreamReader class inherits from the abstract base class TextReader that represents a reader for reading series of characters. It is used for reading from text files. The StreamWriter class inherits from the abstract class TextWriter that represents a writer, which can write a series of character. It is used for writing to text files. The BinaryReader class is used to read binary data from a file. A BinaryReader object is created by passing a FileStream object to its constructor. The BinaryReader class is used for reading from a binary file. The BinaryWriter class is used to write binary data to a stream. A BinaryWriter object is created by passing a FileStream object to its constructor. The BinaryWriter class is used for writing to a binary file. The DirectoryInfo class is derived from the FileSystemInfo class. It has various methods for creating, moving, and browsing through directories and subdirectories. This class cannot be inherited. The FileInfo class is derived from the FileSystemInfo class. It has properties and instance methods for creating, copying, deleting, moving, and opening of files, and helps in the creation of FileStream objects. This class cannot be inherited. Every Visual Basic control consists of three important elements − Properties − Describes the object. Properties − Describes the object. Methods − Cause an object to do something. Methods − Cause an object to do something. Events − Happens when an object does something. Events − Happens when an object does something. It represents the container for all the controls that make up the user interface. It represents a Windows text box control. It represents a standard Windows label. It represents a Windows button control. It represents a Windows control to display a list of items. It represents a Windows combo box control. It enables the user to select a single option from a group of choices when paired with other RadioButton controls. It represents a Windows picture box control for displaying an image. It represents a Windows progress bar control. It Implements the basic functionality of a scroll bar control. It represents a Windows control that allows the user to select a date and a time and to display the date and time with a specified format. It displays a hierarchical collection of labeled items, each represented by a TreeNode. It represents a Windows list view control, which displays a collection of items that can be displayed using one of four different views. Further you can go through your past assignments you have done with the subject and make sure you are able to speak confidently on them. If you are fresher then interviewer does not expect you will answer very complex questions, rather you have to make your basics concepts very strong. Second it really doesn't matter much if you could not answer few questions but it matters that whatever you answered, you must have answered with confidence. So just feel confident during your interview. We at tutorialspoint wish you best luck to have a good interviewer and all the very best for your future endeavor. Cheers :-)
[ { "code": null, "e": 2879, "s": 2434, "text": "Dear readers, these VB.NET Interview Questions have been designed specially to get you acquainted with the nature of questions you may encounter during your interview for the subject of VB.NET Language. As per my experience good interviewers hardly plan to ask any particular question during your interview, normally questions start with some basic concept of the subject and later they continue based on further discussion and what you answer:" }, { "code": null, "e": 3168, "s": 2879, "text": " Visual Basic .NET (VB.NET) is an object-oriented computer programming language implemented on the .NET Framework. Although it is an evolution of classic Visual Basic language, it is not backwards-compatible with VB6, and any code written in the old version does not compile under VB.NET." }, { "code": null, "e": 3223, "s": 3168, "text": " Sub Main indicates the entry point of VB.Net program." }, { "code": null, "e": 3313, "s": 3223, "text": " Shared methods or static methods can be invoked without creating an object of the class." }, { "code": null, "e": 3490, "s": 3313, "text": " Shared declares a shared variable, which is not associated with any specific instance of a class or structure, rather available to all the instances of the class or structure." }, { "code": null, "e": 3626, "s": 3490, "text": " Shadows indicate that the variable re-declares and hides an identically named element, or set of overloaded elements, in a base class." }, { "code": null, "e": 3759, "s": 3626, "text": " Static indicates that the variable will retain its value, even when the after termination of the procedure in which it is declared." }, { "code": null, "e": 3940, "s": 3759, "text": " In VB.Net, constants are declared using the Const statement. The Const statement is used at module, class, structure, procedure, or block level for use in place of literal values." }, { "code": null, "e": 4123, "s": 3940, "text": " Ansi − Specifies that Visual Basic should marshal all strings to American National Standards Institute (ANSI) values regardless of the name of the external procedure being declared." }, { "code": null, "e": 4229, "s": 4123, "text": " Assembly − Specifies that an attribute at the beginning of a source file applies to the entire assembly." }, { "code": null, "e": 4464, "s": 4229, "text": " Async − Indicates that the method or lambda expression that it modifies is asynchronous. Such methods are referred to as async methods. The caller of an async method can resume its work without waiting for the async method to finish." }, { "code": null, "e": 4822, "s": 4464, "text": " Auto − The charsetmodifier part in the Declare statement supplies the character set information for marshaling strings during a call to the external procedure. It also affects how Visual Basic searches the external file for the external procedure name. The Auto modifier specifies that Visual Basic should marshal strings according to .NET Framework rules." }, { "code": null, "e": 5024, "s": 4822, "text": " ByRef − Specifies that an argument is passed by reference, i.e., the called procedure can change the value of a variable underlying the argument in the calling code. It is used under the contexts of −" }, { "code": null, "e": 5042, "s": 5024, "text": "Declare Statement" }, { "code": null, "e": 5060, "s": 5042, "text": "Declare Statement" }, { "code": null, "e": 5079, "s": 5060, "text": "Function Statement" }, { "code": null, "e": 5098, "s": 5079, "text": "Function Statement" }, { "code": null, "e": 5112, "s": 5098, "text": "Sub Statement" }, { "code": null, "e": 5126, "s": 5112, "text": "Sub Statement" }, { "code": null, "e": 5342, "s": 5126, "text": " ByVal − Specifies that an argument is passed in such a way that the called procedure or property cannot change the value of a variable underlying the argument in the calling code. It is used under the contexts of −" }, { "code": null, "e": 5360, "s": 5342, "text": "Declare Statement" }, { "code": null, "e": 5378, "s": 5360, "text": "Declare Statement" }, { "code": null, "e": 5397, "s": 5378, "text": "Function Statement" }, { "code": null, "e": 5416, "s": 5397, "text": "Function Statement" }, { "code": null, "e": 5435, "s": 5416, "text": "Operator Statement" }, { "code": null, "e": 5454, "s": 5435, "text": "Operator Statement" }, { "code": null, "e": 5473, "s": 5454, "text": "Property Statement" }, { "code": null, "e": 5492, "s": 5473, "text": "Property Statement" }, { "code": null, "e": 5506, "s": 5492, "text": "Sub Statement" }, { "code": null, "e": 5520, "s": 5506, "text": "Sub Statement" }, { "code": null, "e": 5616, "s": 5520, "text": " Default − Identifies a property as the default property of its class, structure, or interface." }, { "code": null, "e": 5802, "s": 5616, "text": " Friend − Specifies that one or more declared programming elements are accessible from within the assembly that contains their declaration, not only by the component that declares them." }, { "code": null, "e": 5979, "s": 5802, "text": "Friend access is often the preferred level for an application's programming elements, and Friend is the default access level of an interface, a module, a class, or a structure." }, { "code": null, "e": 6033, "s": 5979, "text": " In − It is used in generic interfaces and delegates." }, { "code": null, "e": 6162, "s": 6033, "text": " Iterator − Specifies that a function or Get accessor is an iterator. An iterator performs a custom iteration over a collection." }, { "code": null, "e": 6252, "s": 6162, "text": " Key − The Key keyword enables you to specify behavior for properties of anonymous types." }, { "code": null, "e": 6404, "s": 6252, "text": " Module − Specifies that an attribute at the beginning of a source file applies to the current assembly module. It is not same as the Module statement." }, { "code": null, "e": 6530, "s": 6404, "text": " MustInherit − Specifies that a class can be used only as a base class and that you cannot create an object directly from it." }, { "code": null, "e": 6683, "s": 6530, "text": " MustOverride − Specifies that a property or procedure is not implemented in this class and must be overridden in a derived class before it can be used." }, { "code": null, "e": 6876, "s": 6683, "text": " Narrowing − Indicates that a conversion operator (CType) converts a class or structure to a type that might not be able to hold some of the possible values of the original class or structure." }, { "code": null, "e": 6949, "s": 6876, "text": " NotInheritable − Specifies that a class cannot be used as a base class." }, { "code": null, "e": 7047, "s": 6949, "text": " NotOverridable − Specifies that a property or procedure cannot be overridden in a derived class." }, { "code": null, "e": 7140, "s": 7047, "text": " Optional − Specifies that a procedure argument can be omitted when the procedure is called." }, { "code": null, "e": 7230, "s": 7140, "text": " Out − For generic type parameters, the Out keyword specifies that the type is covariant." }, { "code": null, "e": 7359, "s": 7230, "text": " Overloads − Specifies that a property or procedure redeclares one or more existing properties or procedures with the same name." }, { "code": null, "e": 7497, "s": 7359, "text": " Overridable − Specifies that a property or procedure can be overridden by an identically named property or procedure in a derived class." }, { "code": null, "e": 7631, "s": 7497, "text": " Overrides − Specifies that a property or procedure overrides an identically named property or procedure inherited from a base class." }, { "code": null, "e": 7781, "s": 7631, "text": " ParamArray − ParamArray allows you to pass an arbitrary number of arguments to the procedure. A ParamArray parameter is always declared using ByVal." }, { "code": null, "e": 7891, "s": 7781, "text": " Partial − Indicates that a class or structure declaration is a partial definition of the class or structure." }, { "code": null, "e": 8061, "s": 7891, "text": " Private − Specifies that one or more declared programming elements are accessible only from within their declaration context, including from within any contained types." }, { "code": null, "e": 8204, "s": 8061, "text": " Protected − Specifies that one or more declared programming elements are accessible only from within their own class or from a derived class." }, { "code": null, "e": 8300, "s": 8204, "text": " Public − Specifies that one or more declared programming elements have no access restrictions." }, { "code": null, "e": 8379, "s": 8300, "text": " ReadOnly − Specifies that a variable or property can be read but not written." }, { "code": null, "e": 8535, "s": 8379, "text": " Shadows − Specifies that a declared programming element redeclares and hides an identically named element, or set of overloaded elements, in a base class." }, { "code": null, "e": 8713, "s": 8535, "text": " Shared − Specifies that one or more declared programming elements are associated with a class or structure at large, and not with a specific instance of the class or structure." }, { "code": null, "e": 8894, "s": 8713, "text": " Static − Specifies that one or more declared local variables are to continue to exist and retain their latest values after termination of the procedure in which they are declared." }, { "code": null, "e": 9043, "s": 8894, "text": " Unicode − Specifies that Visual Basic should marshal all strings to Unicode values regardless of the name of the external procedure being declared." }, { "code": null, "e": 9210, "s": 9043, "text": " Widening − Indicates that a conversion operator (CType) converts a class or structure to a type that can hold all possible values of the original class or structure." }, { "code": null, "e": 9332, "s": 9210, "text": " WithEvents − Specifies that one or more declared member variables refer to an instance of a class that can raise events." }, { "code": null, "e": 9400, "s": 9332, "text": " WriteOnly − Specifies that a property can be written but not read." }, { "code": null, "e": 9481, "s": 9400, "text": " Dim Statement − Declares and allocates storage space for one or more variables." }, { "code": null, "e": 9566, "s": 9481, "text": "Dim number As Integer\nDim quantity As Integer = 100\nDim message As String = \"Hello!\"" }, { "code": null, "e": 9630, "s": 9566, "text": " Const Statement − Declares and defines one or more constants. " }, { "code": null, "e": 9712, "s": 9630, "text": "Const maximum As Long = 1000\nConst naturalLogBase As Object \n= CDec(2.7182818284)" }, { "code": null, "e": 9794, "s": 9712, "text": " Enum Statement − Declares an enumeration and defines the values of its members. " }, { "code": null, "e": 9879, "s": 9794, "text": "Enum CoffeeMugSize\n Jumbo\n ExtraLarge\n Large\n Medium\n Small\nEnd Enum " }, { "code": null, "e": 10036, "s": 9879, "text": " Class Statement − Declares the name of a class and introduces the definition of the variables, properties, events, and procedures that the class comprises." }, { "code": null, "e": 10132, "s": 10036, "text": "Class Box\nPublic length As Double\nPublic breadth As Double \nPublic height As Double\nEnd Class" }, { "code": null, "e": 10301, "s": 10132, "text": " Structure Statement − Declares the name of a structure and introduces the definition of the variables, properties, events, and procedures that the structure comprises." }, { "code": null, "e": 10416, "s": 10301, "text": "Structure Box\nPublic length As Double \nPublic breadth As Double \nPublic height As Double\nEnd Structure" }, { "code": null, "e": 10576, "s": 10416, "text": " Module Statement − Declares the name of a module and introduces the definition of the variables, properties, events, and procedures that the module comprises." }, { "code": null, "e": 10714, "s": 10576, "text": "Public Module myModule\nSub Main()\nDim user As String = \nInputBox(\"What is your name?\") \nMsgBox(\"User name is\" & user)\nEnd Sub \nEnd Module" }, { "code": null, "e": 10847, "s": 10714, "text": " Interface Statement − Declares the name of an interface and introduces the definitions of the members that the interface comprises." }, { "code": null, "e": 10913, "s": 10847, "text": "Public Interface MyInterface\n Sub doSomething()\nEnd Interface " }, { "code": null, "e": 11009, "s": 10913, "text": " Function Statement − Declares the name, parameters, and code that define a Function procedure." }, { "code": null, "e": 11094, "s": 11009, "text": "Function myFunction\n(ByVal n As Integer) As Double \n Return 5.87 * n\nEnd Function" }, { "code": null, "e": 11180, "s": 11094, "text": " Sub Statement − Declares the name, parameters, and code that define a Sub procedure." }, { "code": null, "e": 11229, "s": 11180, "text": "Sub mySub(ByVal s As String)\n Return\nEnd Sub " }, { "code": null, "e": 11319, "s": 11229, "text": " Declare Statement − Declares a reference to a procedure implemented in an external file." }, { "code": null, "e": 11459, "s": 11319, "text": "Declare Function getUserName\nLib \"advapi32.dll\" \nAlias \"GetUserNameA\" \n(\n ByVal lpBuffer As String, \n ByRef nSize As Integer) As Integer " }, { "code": null, "e": 11589, "s": 11459, "text": " Operator Statement − Declares the operator symbol, operands, and code that define an operator procedure on a class or structure." }, { "code": null, "e": 11748, "s": 11589, "text": "Public Shared Operator +\n(ByVal x As obj, ByVal y As obj) As obj\n Dim r As New obj\n' implemention code for r = x + y\n Return r\n End Operator " }, { "code": null, "e": 11885, "s": 11748, "text": " Property Statement − Declares the name of a property, and the property procedures used to store and retrieve the value of the property." }, { "code": null, "e": 11984, "s": 11885, "text": "ReadOnly Property quote() As String \n Get \n Return quoteString\n End Get \nEnd Property" }, { "code": null, "e": 12034, "s": 11984, "text": " Event Statement − Declares a user-defined event." }, { "code": null, "e": 12058, "s": 12034, "text": "Public Event Finished()" }, { "code": null, "e": 12108, "s": 12058, "text": " Delegate Statement − Used to declare a delegate." }, { "code": null, "e": 12201, "s": 12108, "text": "Delegate Function MathOperator( \n ByVal x As Double, \n ByVal y As Double \n) As Double " }, { "code": null, "e": 12476, "s": 12201, "text": " The VB.Net compiler directives give instructions to the compiler to preprocess the information before actual compilation starts. All these directives begin with #, and only white-space characters may appear before a directive on a line. These directives are not statements." }, { "code": null, "e": 12526, "s": 12476, "text": " AddressOf − Returns the address of a procedure. " }, { "code": null, "e": 12576, "s": 12526, "text": "AddHandler Button1.Click,\nAddressOf Button1_Click" }, { "code": null, "e": 12731, "s": 12576, "text": " Await − It is applied to an operand in an asynchronous method or lambda expression to suspend execution of the method until the awaited task completes. " }, { "code": null, "e": 12808, "s": 12731, "text": "Dim result As res\n= Await AsyncMethodThatReturnsResult()\nAwait AsyncMethod()" }, { "code": null, "e": 12966, "s": 12808, "text": " GetType − It returns a Type object for the specified type. The Type object provides information about the type such as its properties, methods, and events. " }, { "code": null, "e": 13002, "s": 12966, "text": "MsgBox(GetType(Integer).ToString())" }, { "code": null, "e": 13104, "s": 13002, "text": " Function Expression − It declares the parameters and code that define a function lambda expression. " }, { "code": null, "e": 13187, "s": 13104, "text": "Dim add5 = Function(num As\n Integer) num + 5\n'prints 10\nConsole.WriteLine(add5(5))" }, { "code": null, "e": 13343, "s": 13187, "text": " If − It uses short-circuit evaluation to conditionally return one of two values. The If operator can be called with three arguments or with two arguments." }, { "code": null, "e": 13494, "s": 13343, "text": " Exit statement − Terminates the loop or select case statement and transfers execution to the statement immediately following the loop or select case." }, { "code": null, "e": 13625, "s": 13494, "text": " Continue statement − Causes the loop to skip the remainder of its body and immediately retest its condition prior to reiterating." }, { "code": null, "e": 13751, "s": 13625, "text": " GoTo statement − Transfers control to the labeled statement. Though it is not advised to use GoTo statement in your program." }, { "code": null, "e": 13912, "s": 13751, "text": " Dynamic arrays are arrays that can be dimensioned and re-dimensioned as par the need of the program. You can declare a dynamic array using the ReDim statement." }, { "code": null, "e": 14065, "s": 13912, "text": " A Jagged array is an array of arrays. A Jagged array is an array of arrays. The follwoing code shows declaring a jagged array named scores of Integers:" }, { "code": null, "e": 14112, "s": 14065, "text": "Dim scores As Integer()() = New Integer(5)(){}" }, { "code": null, "e": 14466, "s": 14112, "text": " It represents ordered collection of an object that can be indexed individually. It is basically an alternative to an array. However, unlike array, you can add and remove items from a list at a specified position using an index and the array resizes itself automatically. It also allows dynamic memory allocation, add, search and sort items in the list." }, { "code": null, "e": 14737, "s": 14466, "text": " It uses a key to access the elements in the collection. A hash table is used when you need to access elements by using key, and you can identify a useful key value. Each item in the hash table has a key/value pair. The key is used to access the items in the collection." }, { "code": null, "e": 15109, "s": 14737, "text": " It uses a key as well as an index to access the items in a list. A sorted list is a combination of an array and a hash table. It contains a list of items that can be accessed using a key or an index. If you access items using an index, it is an ArrayList, and if you access items using a key, it is a Hashtable. The collection of items is always sorted by the key value." }, { "code": null, "e": 15350, "s": 15109, "text": " It represents a last-in, first out collection of object. It is used when you need a last-in, first-out access of items. When you add an item in the list, it is called pushing the item, and when you remove it, it is called popping the item." }, { "code": null, "e": 15578, "s": 15350, "text": " It represents a first-in, first out collection of object. It is used when you need a first-in, first-out access of items. When you add an item in the list, it is called enqueue, and when you remove an item, it is called deque." }, { "code": null, "e": 15848, "s": 15578, "text": " It represents an array of the binary representation using the values 1 and 0. It is used when you need to store the bits but do not know the number of bits in advance. You can access items from the BitArray collection by using an integer index, which starts from zero." }, { "code": null, "e": 15924, "s": 15848, "text": " In VB.Net, a function can return a value to the calling code in two ways −" }, { "code": null, "e": 15955, "s": 15924, "text": "By using the return statement." }, { "code": null, "e": 15986, "s": 15955, "text": "By using the return statement." }, { "code": null, "e": 16031, "s": 15986, "text": "By assigning the value to the function name." }, { "code": null, "e": 16076, "s": 16031, "text": "By assigning the value to the function name." }, { "code": null, "e": 16206, "s": 16076, "text": " By using the params keyword, a method parameter can be specified which takes a variable number of arguments or even no argument." }, { "code": null, "e": 16361, "s": 16206, "text": " No! additional parameters are not permitted after the params keyword in a method declaration. Only one params keyword is allowed in a method declaration." }, { "code": null, "e": 16657, "s": 16361, "text": " VB.NET exceptions are represented by classes. The exception classes in VB.NET are mainly directly or indirectly derived from the System.Exception class. Some of the exception classes derived from the System.Exception class are the System.ApplicationException and System.SystemException classes." }, { "code": null, "e": 16918, "s": 16657, "text": " The System.ApplicationException class supports exceptions generated by application programs. Hence the exceptions defined by the programmers should derive from this class. The System.SystemException class is the base class for all predefined system exception." }, { "code": null, "e": 17216, "s": 16918, "text": "The stream is basically the sequence of bytes passing through the communication path. There are two main streams: the input stream and the output stream. The input stream is used for reading data from file (read operation) and the output stream is used for writing into the file (write operation)." }, { "code": null, "e": 17368, "s": 17216, "text": "The FileStream class in the System.IO namespace helps in reading from, writing to and closing files. This class derives from the abstract class Stream." }, { "code": null, "e": 17540, "s": 17368, "text": " The StreamReader class inherits from the abstract base class TextReader that represents a reader for reading series of characters. It is used for reading from text files." }, { "code": null, "e": 17711, "s": 17540, "text": " The StreamWriter class inherits from the abstract class TextWriter that represents a writer, which can write a series of character. It is used for writing to text files." }, { "code": null, "e": 17923, "s": 17711, "text": " The BinaryReader class is used to read binary data from a file. A BinaryReader object is created by passing a FileStream object to its constructor. The BinaryReader class is used for reading from a binary file." }, { "code": null, "e": 18134, "s": 17923, "text": " The BinaryWriter class is used to write binary data to a stream. A BinaryWriter object is created by passing a FileStream object to its constructor. The BinaryWriter class is used for writing to a binary file." }, { "code": null, "e": 18331, "s": 18134, "text": " The DirectoryInfo class is derived from the FileSystemInfo class. It has various methods for creating, moving, and browsing through directories and subdirectories. This class cannot be inherited." }, { "code": null, "e": 18576, "s": 18331, "text": " The FileInfo class is derived from the FileSystemInfo class. It has properties and instance methods for creating, copying, deleting, moving, and opening of files, and helps in the creation of FileStream objects. This class cannot be inherited." }, { "code": null, "e": 18643, "s": 18576, "text": " Every Visual Basic control consists of three important elements −" }, { "code": null, "e": 18678, "s": 18643, "text": "Properties − Describes the object." }, { "code": null, "e": 18713, "s": 18678, "text": "Properties − Describes the object." }, { "code": null, "e": 18756, "s": 18713, "text": "Methods − Cause an object to do something." }, { "code": null, "e": 18799, "s": 18756, "text": "Methods − Cause an object to do something." }, { "code": null, "e": 18847, "s": 18799, "text": "Events − Happens when an object does something." }, { "code": null, "e": 18895, "s": 18847, "text": "Events − Happens when an object does something." }, { "code": null, "e": 18978, "s": 18895, "text": " It represents the container for all the controls that make up the user interface." }, { "code": null, "e": 19021, "s": 18978, "text": " It represents a Windows text box control." }, { "code": null, "e": 19062, "s": 19021, "text": " It represents a standard Windows label." }, { "code": null, "e": 19103, "s": 19062, "text": " It represents a Windows button control." }, { "code": null, "e": 19164, "s": 19103, "text": " It represents a Windows control to display a list of items." }, { "code": null, "e": 19208, "s": 19164, "text": " It represents a Windows combo box control." }, { "code": null, "e": 19324, "s": 19208, "text": " It enables the user to select a single option from a group of choices when paired with other RadioButton controls." }, { "code": null, "e": 19394, "s": 19324, "text": " It represents a Windows picture box control for displaying an image." }, { "code": null, "e": 19441, "s": 19394, "text": " It represents a Windows progress bar control." }, { "code": null, "e": 19505, "s": 19441, "text": " It Implements the basic functionality of a scroll bar control." }, { "code": null, "e": 19645, "s": 19505, "text": " It represents a Windows control that allows the user to select a date and a time and to display the date and time with a specified format." }, { "code": null, "e": 19734, "s": 19645, "text": " It displays a hierarchical collection of labeled items, each represented by a TreeNode." }, { "code": null, "e": 19872, "s": 19734, "text": " It represents a Windows list view control, which displays a collection of items that can be displayed using one of four different views." }, { "code": null, "e": 20159, "s": 19872, "text": "Further you can go through your past assignments you have done with the subject and make sure you are able to speak confidently on them. If you are fresher then interviewer does not expect you will answer very complex questions, rather you have to make your basics concepts very strong." } ]
Venom – Pentesting Testing Scanner
23 Aug, 2021 Vulnerability Scanning or vuln scan is the automated process for identifying security flaws in the target or victim network or web applications. A vulnerability scan is also performed by attackers who try to find points of entry into your network. Various automated Vulnerability Scanners scans the network or Web Application for us. Venom is one of the computerized scanners which scans the domain for various security flaws like XSS, SQLi, RCE, and many more. Venom is a Python language-based tool. It’s open-source and completely free to use. Venom has adapted several new features that improve functionality and usability. It is primarily experimental software. Venom Tool is for finding and executing various vulnerabilities. It scavenges the web using dorks and organizes the URLs it finds. Note: Make Sure You have Python Installed on your System, as this is a python-based tool. Click to check the Installation process: Python Installation Steps on Linux Venom tool scans for LFI, RXE, XSS, etc, Security Flaws.Venom tool consists of Huge Dork Target Lists.Venom tool can detect WAFs Protection.Venom tool can find Admin Pages on Target Domain.Venom tool is open-source and free to use.Venom tool can perform DNS Brute-forcing.Venom tool is a cross-platform Python-based toolkit.Venom tool has a Cloudflare resolver. Venom tool scans for LFI, RXE, XSS, etc, Security Flaws. Venom tool consists of Huge Dork Target Lists. Venom tool can detect WAFs Protection. Venom tool can find Admin Pages on Target Domain. Venom tool is open-source and free to use. Venom tool can perform DNS Brute-forcing. Venom tool is a cross-platform Python-based toolkit. Venom tool has a Cloudflare resolver. Step 1: Install the Python3-dev using the following command. sudo apt-get install python3-dev Step 2: Install the Python-dev using the following command. sudo apt-get install python-dev Step 3: Fire up your Kali Linux terminal and move to Desktop using the following command. cd Desktop Step 4: You are on Desktop now create a new directory called Venom using the following command. In this directory, we will complete the installation of the Venom tool. mkdir Venom Step 5: Now switch to the Venom directory using the following command. cd Venom Step 6: Now you have to install the tool. You have to clone the tool from Github. git clone https://github.com/v3n0m-Scanner/V3n0M-Scanner.git Step 7: The tool has been downloaded successfully in the Venom directory. Now list out the contents of the tool by using the below command. ls Step 8: You can observe that there is a new directory created of the Venom tool that has been generated while we were installing the tool. Now move to that directory using the below command: cd V3n0M-Scanner/ Step 9: Once again to discover the contents of the tool, use the below command. ls Step 10: Run the setup.py file to fully install the tool, use the below command. python3 setup.py install --user Step 11: Run the v3n0m.py from the src directory. python v3n0m.py 1. In this example, We will be performing Vulnerability Scanning on our target geeksforgeeks.org. Required input values are given like target, random dorks, pages, increments. 2. In the below Screenshot, the types of scanning options are displayed and asking for the user input. After proving the essential option the scanning process will be started 3. In the below Screenshot, you can see that we have selected the 10th option (Scan all the things). So Venom tool will scan all the vulnerabilities on the geeksforgeeks.org domain and give the vulnerable points. In this example, We will be finding the Admin Pages which are associated or hosted on screenshotgeeksforgeeks.org. In the below screenshot, you can see that the Venom tool checks all possible pages along with its status code. 1. In this example, We will be performing DNS Brute Forcing. In the below screenshot, you can see that we got the Subdomains, CNAME Records, and the A records for our target domain. In this example, we will be enabling our proxy for setting up our proxy server for bypassing the WAF Firewalls. In the below Screenshot, we have specified the IP address, Type of Proxy, Port Number from which the Proxy Server will be enabled. 1. In this example, We will be Performing Cloudflare Resolving on geeksforgeeks.org. We have given the target link for resolving. 2. In the below Screenshot, you can see that we have got the information about the Cloudflare Resolving along with the Status and the IP address Kali-Linux Linux-Tools Linux-Unix Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Docker - COPY Instruction scp command in Linux with Examples chown command in Linux with Examples SED command in Linux | Set 2 mv command in Linux with examples nohup Command in Linux with Examples chmod command in Linux with examples Introduction to Linux Operating System Array Basics in Shell Scripting | Set 1 Basic Operators in Shell Scripting
[ { "code": null, "e": 28, "s": 0, "text": "\n23 Aug, 2021" }, { "code": null, "e": 825, "s": 28, "text": "Vulnerability Scanning or vuln scan is the automated process for identifying security flaws in the target or victim network or web applications. A vulnerability scan is also performed by attackers who try to find points of entry into your network. Various automated Vulnerability Scanners scans the network or Web Application for us. Venom is one of the computerized scanners which scans the domain for various security flaws like XSS, SQLi, RCE, and many more. Venom is a Python language-based tool. It’s open-source and completely free to use. Venom has adapted several new features that improve functionality and usability. It is primarily experimental software. Venom Tool is for finding and executing various vulnerabilities. It scavenges the web using dorks and organizes the URLs it finds." }, { "code": null, "e": 915, "s": 825, "text": "Note: Make Sure You have Python Installed on your System, as this is a python-based tool." }, { "code": null, "e": 991, "s": 915, "text": "Click to check the Installation process: Python Installation Steps on Linux" }, { "code": null, "e": 1353, "s": 991, "text": "Venom tool scans for LFI, RXE, XSS, etc, Security Flaws.Venom tool consists of Huge Dork Target Lists.Venom tool can detect WAFs Protection.Venom tool can find Admin Pages on Target Domain.Venom tool is open-source and free to use.Venom tool can perform DNS Brute-forcing.Venom tool is a cross-platform Python-based toolkit.Venom tool has a Cloudflare resolver." }, { "code": null, "e": 1410, "s": 1353, "text": "Venom tool scans for LFI, RXE, XSS, etc, Security Flaws." }, { "code": null, "e": 1457, "s": 1410, "text": "Venom tool consists of Huge Dork Target Lists." }, { "code": null, "e": 1496, "s": 1457, "text": "Venom tool can detect WAFs Protection." }, { "code": null, "e": 1546, "s": 1496, "text": "Venom tool can find Admin Pages on Target Domain." }, { "code": null, "e": 1589, "s": 1546, "text": "Venom tool is open-source and free to use." }, { "code": null, "e": 1631, "s": 1589, "text": "Venom tool can perform DNS Brute-forcing." }, { "code": null, "e": 1684, "s": 1631, "text": "Venom tool is a cross-platform Python-based toolkit." }, { "code": null, "e": 1722, "s": 1684, "text": "Venom tool has a Cloudflare resolver." }, { "code": null, "e": 1784, "s": 1722, "text": "Step 1: Install the Python3-dev using the following command." }, { "code": null, "e": 1817, "s": 1784, "text": "sudo apt-get install python3-dev" }, { "code": null, "e": 1877, "s": 1817, "text": "Step 2: Install the Python-dev using the following command." }, { "code": null, "e": 1909, "s": 1877, "text": "sudo apt-get install python-dev" }, { "code": null, "e": 1999, "s": 1909, "text": "Step 3: Fire up your Kali Linux terminal and move to Desktop using the following command." }, { "code": null, "e": 2010, "s": 1999, "text": "cd Desktop" }, { "code": null, "e": 2178, "s": 2010, "text": "Step 4: You are on Desktop now create a new directory called Venom using the following command. In this directory, we will complete the installation of the Venom tool." }, { "code": null, "e": 2190, "s": 2178, "text": "mkdir Venom" }, { "code": null, "e": 2261, "s": 2190, "text": "Step 5: Now switch to the Venom directory using the following command." }, { "code": null, "e": 2270, "s": 2261, "text": "cd Venom" }, { "code": null, "e": 2352, "s": 2270, "text": "Step 6: Now you have to install the tool. You have to clone the tool from Github." }, { "code": null, "e": 2413, "s": 2352, "text": "git clone https://github.com/v3n0m-Scanner/V3n0M-Scanner.git" }, { "code": null, "e": 2553, "s": 2413, "text": "Step 7: The tool has been downloaded successfully in the Venom directory. Now list out the contents of the tool by using the below command." }, { "code": null, "e": 2556, "s": 2553, "text": "ls" }, { "code": null, "e": 2747, "s": 2556, "text": "Step 8: You can observe that there is a new directory created of the Venom tool that has been generated while we were installing the tool. Now move to that directory using the below command:" }, { "code": null, "e": 2765, "s": 2747, "text": "cd V3n0M-Scanner/" }, { "code": null, "e": 2845, "s": 2765, "text": "Step 9: Once again to discover the contents of the tool, use the below command." }, { "code": null, "e": 2848, "s": 2845, "text": "ls" }, { "code": null, "e": 2929, "s": 2848, "text": "Step 10: Run the setup.py file to fully install the tool, use the below command." }, { "code": null, "e": 2961, "s": 2929, "text": "python3 setup.py install --user" }, { "code": null, "e": 3011, "s": 2961, "text": "Step 11: Run the v3n0m.py from the src directory." }, { "code": null, "e": 3027, "s": 3011, "text": "python v3n0m.py" }, { "code": null, "e": 3203, "s": 3027, "text": "1. In this example, We will be performing Vulnerability Scanning on our target geeksforgeeks.org. Required input values are given like target, random dorks, pages, increments." }, { "code": null, "e": 3378, "s": 3203, "text": "2. In the below Screenshot, the types of scanning options are displayed and asking for the user input. After proving the essential option the scanning process will be started" }, { "code": null, "e": 3591, "s": 3378, "text": "3. In the below Screenshot, you can see that we have selected the 10th option (Scan all the things). So Venom tool will scan all the vulnerabilities on the geeksforgeeks.org domain and give the vulnerable points." }, { "code": null, "e": 3817, "s": 3591, "text": "In this example, We will be finding the Admin Pages which are associated or hosted on screenshotgeeksforgeeks.org. In the below screenshot, you can see that the Venom tool checks all possible pages along with its status code." }, { "code": null, "e": 3999, "s": 3817, "text": "1. In this example, We will be performing DNS Brute Forcing. In the below screenshot, you can see that we got the Subdomains, CNAME Records, and the A records for our target domain." }, { "code": null, "e": 4242, "s": 3999, "text": "In this example, we will be enabling our proxy for setting up our proxy server for bypassing the WAF Firewalls. In the below Screenshot, we have specified the IP address, Type of Proxy, Port Number from which the Proxy Server will be enabled." }, { "code": null, "e": 4372, "s": 4242, "text": "1. In this example, We will be Performing Cloudflare Resolving on geeksforgeeks.org. We have given the target link for resolving." }, { "code": null, "e": 4517, "s": 4372, "text": "2. In the below Screenshot, you can see that we have got the information about the Cloudflare Resolving along with the Status and the IP address" }, { "code": null, "e": 4528, "s": 4517, "text": "Kali-Linux" }, { "code": null, "e": 4540, "s": 4528, "text": "Linux-Tools" }, { "code": null, "e": 4551, "s": 4540, "text": "Linux-Unix" }, { "code": null, "e": 4649, "s": 4551, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 4675, "s": 4649, "text": "Docker - COPY Instruction" }, { "code": null, "e": 4710, "s": 4675, "text": "scp command in Linux with Examples" }, { "code": null, "e": 4747, "s": 4710, "text": "chown command in Linux with Examples" }, { "code": null, "e": 4776, "s": 4747, "text": "SED command in Linux | Set 2" }, { "code": null, "e": 4810, "s": 4776, "text": "mv command in Linux with examples" }, { "code": null, "e": 4847, "s": 4810, "text": "nohup Command in Linux with Examples" }, { "code": null, "e": 4884, "s": 4847, "text": "chmod command in Linux with examples" }, { "code": null, "e": 4923, "s": 4884, "text": "Introduction to Linux Operating System" }, { "code": null, "e": 4963, "s": 4923, "text": "Array Basics in Shell Scripting | Set 1" } ]